blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
75d3c17a9fa8df4762cc4836270ca6da70304b0b | olibrook/data-structures-algos-python | /pyalgos/data_structures/heap.py | 2,307 | 3.59375 | 4 | import collections
Pair = collections.namedtuple('Pair', ['idx', 'v'])
class MinHeap:
def __init__(self):
self.l = []
def __len__(self):
return len(self.l)
def __iter__(self):
while len(self):
yield self.pop()
def item_at(self, idx):
return 0 <= idx < len(self.l) and Pair(idx, self.l[idx]) or None
def left_child(self, idx):
return self.item_at((2 * idx) + 1)
def right_child(self, idx):
return self.item_at((2 * idx) + 2)
def parent(self, idx):
return self.item_at(int((idx - 1) / 2))
def children(self, idx):
ret = (self.left_child(idx), self.right_child(idx))
ret = (x for x in ret if x is not None)
return list(ret)
def swap(self, i1, i2):
tmp = self.l[i1]
self.l[i1] = self.l[i2]
self.l[i2] = tmp
def peek(self):
return self.l[0]
def pop(self):
item = self.l.pop(0)
if len(self.l):
self.l.insert(0, self.l.pop())
self.heapify_down()
return item
def add(self, v):
self.l.append(v)
self.heapify_up()
def heapify_up(self):
# Take the last element of the heap and lift it up until we reach a
# parent with a value less then the current one.
if len(self.l):
current = self.item_at(len(self.l) - 1)
while True:
parent = self.parent(current.idx)
if parent is None or current.v >= parent.v:
break
else:
self.swap(current.idx, parent.idx)
current = self.item_at(parent.idx)
def heapify_down(self):
# Compare the root element to its children and swap root with the smallest
# of children. Do the same for next children after swap.
if len(self.l):
current = self.item_at(0)
while True:
children = self.children(current.idx)
smallest = (
min(children, key=lambda pair: pair.v) if children else None)
if smallest is None or current.v < smallest.v:
break
self.swap(current.idx, smallest.idx)
current = self.item_at(smallest.idx)
|
f49b3ec45e2dd8c2599d1e84a46defdedbebd25b | NeoWhiteHatA/all_my_python | /march/dr_huares.py | 1,069 | 4.25 | 4 | #Эта программа получает от пользователя оценки за контрольные работы
#и показывает буквенный эквивалент успеваемости
#нижеследующие константы представляют пороги уровней знаний
A_SCORE = 90
B_SCORE = 80
C_SCORE = 70
D_SCORE = 60
#получить от пользователя оценку контрольной работы
score = int(input('Введите свою оценку: '))
#определить буквенный уровень оценки
if score >= A_SCORE:
print('Ваш уровень знаний - А')
else:
if score >= B_SCORE:
print('Ваш уровень знаний - B')
else:
if score >= C_SCORE:
print('Ваш уровень знаний - C')
else:
if score >= D_SCORE:
print('Ваш уровень заний - D')
else:
print('Ваш уровень не знаний - F') |
d5e27b681b7b4a6684c13094541a75ff4db9ef10 | kzm1997/pythonDemo | /test/classOne.py | 495 | 3.609375 | 4 | class Person(object):
def __init__(self,name,age):
self._name=name
self._age=age
@property
def name(self):
return self._name
@property
def age(self):
return self._gae
@age.setter
def age(self,age):
self._age=age
def play(self):
if self._age<=16:
print('%s正在玩飞机'%self._name)
else:
print('%s正在玩斗地主'%self._name)
person =Person('王大锤',22)
person.play() |
0904932b3a2ddc8589dc310a2e9a76c159d0cc74 | bam6076/PythonEdX | /quiz3_part5.py | 610 | 4.125 | 4 | ## Write a function that receives a positive integer as function
## parameter and returns True if the integer is a perfect number,
## False otherwise. A perfect number is a number whose sum of the
## all the divisors (excluding itself) is equal to itself.
## For example: divisors of 6 (excluding 6 are) : 1, 2, 3 and
## their sum is 1+2+3 = 6. Therefore, 6 is a perfect number.
def _perfect(num):
sum = 0
for i in range(1,num):
if num%i == 0:
sum = sum + i
if num == sum:
return True
else:
return False
print (_perfect(6))
print (_perfect(10))
|
38c96698c7a34022dde7e1210387533c223ad672 | wngus9056/Datascience | /Python&DataBase/5.13/Python04_09_strFun04_김주현.py | 453 | 3.8125 | 4 | a = " hi "
print(a)
print(a.lstrip()+'WOW') # ' hi '의 왼쪽 공백을 제거하고 'WOW'를 붙인다.
print(a.rstrip()+'WOW') # ' hi '의 오른쪽 공백을 제거한다.
print(a.strip()+'WOW') # ' hi '의 양쪽 공백을 제거한다.
print('-'*15)
b = 'Life is too short'
print(b)
change = b.replace('Life', 'Your leg') # change변수에 b변수에서 'Life'를 'Your leg'로 바꾼 값을 저장한다.
print(change)
print('-'*15) |
70a8a0a15b77a92f104ff7e72db220b923bf262c | im-jonhatan/hackerRankPython | /numpy/linearAlgebra.py | 560 | 3.90625 | 4 | # Task
# You are given a square matrix A with dimensions NXN. Your task is to find the determinant. Note: Round the answer to 2 places after the decimal.
# Input Format
# The first line contains the integer N.
# The next N lines contains the N space separated elements of array A.
# Output Format
# Print the determinant of A.
# Sample Input
# 2
# 1.1 1.1
# 1.1 1.1
# Sample Output
# 0.0
import numpy
n = int(input())
a = numpy.array([input().split() for _ in range(n)], float)
result = numpy.around(numpy.linalg.det(a), 2)
print(result)
|
222397bc318f79845d6fab4a8476575aea71dc21 | ilkera/EPI | /Strings/StrStr/StrStr.py | 1,136 | 4.09375 | 4 | # Problem: Implement Strstr function
# (Search for a substring and return the first occurence index)
# Function
def strStr(str, target):
if not str or not target:
return -1
if len(str) < len(target):
return -1
current_str= 0
while current_str < len(str):
if str[current_str] != target[0]:
current_str += 1
continue
temp, current_target = current_str + 1, 1
while temp < len(str) and current_target < len(target) and str[temp] == target[current_target]:
temp +=1
current_target +=1
if current_target == len(target):
return current_str
current_str += 1
return -1
# Main program
# Valid
print(strStr("This is a test", "is"))
print(strStr("This is a test", "test"))
print(strStr("This is a test", "tes"))
print(strStr("This is a test", "This"))
print(strStr("This is a test", "a"))
# Invalid
print(strStr("This is a test", "apple"))
print(strStr("This is a test", "teste"))
print(strStr("This is a test", "tesa"))
print(strStr("This is a test", "Tha"))
print(strStr("This is a test", "Thiss")) |
ac40bbb61f30b25c190508a5c2b0b969dd29694f | jonik2909/Tkinter | /buttons.py | 494 | 3.734375 | 4 | from tkinter import *
root = Tk()
# Funsiyadan foydalanib chiqarish. bunda u buttonga command=berish kk.
def myClick():
myLabel = Label(root, text="Look! I clicked")
myLabel.pack()
#Creating Buttons,
# state=DISABLED (Bosilgan turadi),
# padx=eni, pady=bo'yi
# command buyrug'isiz ishmalaydi. () qoyilsa chiqib turadi.
# fg=text color, bg=background color
myButton = Button(root, text="Click Me!", padx=30, command=myClick, fg="#fff", bg="#333" )
myButton.pack()
root.mainloop() |
ff615b3266fa45d0017d31ebeb64b9e4a4b14945 | bryan-lima/python-cursoemvideo | /mundo-03/ex104.py | 531 | 4.21875 | 4 | # Crie um programa que tenha a função leiaInt(), que vai funcionar de forma semelhante à função input() do Python,
# só que fazendo a validação para aceitar apenas um valor numérico
def readInt(msg):
while True:
value = str(input(msg))
if value.isnumeric():
value = int(value)
break
else:
print('\033[1:31mERRO! Digite um número inteiro válido.\033[m')
return value
n = readInt('Digite um número: ')
print(f'Você acabou de digitar o número {n}')
|
6fcc79568e883fd9657708880689a7f6d2b2edfb | nik45/ReplitOnline | /main.py | 62 | 3.515625 | 4 | print("Hello World!!")
a = 5
n = 234
c = a + n * 0
print (c)
|
0906174006c16045d43b5f240d1a2614a87957fb | tmdgh98/replit | /ItsCote/Unit05 DFS,BFS/03재귀함수.py | 136 | 3.828125 | 4 | def recursive_function(i):
if i>=10:
return
print(i,"번쨰 재귀함수")
i+=1
recursive_function(i)
recursive_function(1) |
87e73847e235be7897172a8a7a91b1264e38a005 | AgataWa/lab5 | /bayes.py | 6,243 | 3.609375 | 4 | import csv
import random
import math
def loadCsv(filename):
lines = csv.reader(open(filename, "r"))
dataset = list(lines)
for i in range(len(dataset)):
for x_i, x in enumerate(dataset[i]):
dataset[i][x_i] = float(x)
return dataset
def testLoadCsv():
filename = 'pima-indians-diabetes.data.csv'
dataset = loadCsv(filename)
assert (len(dataset))
print('Loaded data file {0} with {1} rows'.format(filename, len(dataset)))
def splitDataset(dataset, splitRatio):
trainSet = []
# testSet = []
trainSize = int(len(dataset) * splitRatio)
testSet = list(dataset)
while len(trainSet) < trainSize:
index = random.randrange(len(testSet))
trainSet.append(testSet.pop(index))
return [trainSet, testSet]
def testSplitDataset():
dataset = [[1], [2], [3], [4], [5]]
splitRatio = 0.67
train, test = splitDataset(dataset, splitRatio)
assert (train)
assert (test)
print('Split {0} rows into train with {1} and test with {2}'.format(len(dataset), train, test))
def separateByClass(dataset):
"""Rozdziel zbiór uczący według klasy (v[-1]) przypisanej wektorowi cech v"""
separated = {}
for i in range(len(dataset)):
vector = dataset[i]
if vector[-1] not in separated:
separated[vector[-1]] = []
separated[vector[-1]].append(vector)
return separated
def testSeparateByClass():
dataset = [[1, 20, 1], [2, 21, 0], [3, 22, 1]]
separated = separateByClass(dataset)
assert (separated)
print('Separated instances: {0}'.format(separated))
def mean(numbers):
"""Oblicz średnią arytmetyczną z listy danych"""
mean = sum(numbers) / float(len(numbers))
return mean
def stdev(numbers):
"""Oblicz odchylenie standardowe z listy danych"""
avg = mean(numbers)
variance = sum([pow(x - avg, 2) for x in numbers]) / float(len(numbers) - 1)
return math.sqrt(variance)
def testMeanAndStdev():
numbers = [1, 2, 3, 4, 5]
assert (mean)
assert (stdev)
print('Summary of {0}: mean={1}, stdev={2}'.format(numbers, mean(numbers), stdev(numbers)))
def summarize(dataset):
summaries = [(mean(attribute), stdev(attribute)) for attribute in zip(*dataset)]
return summaries
def testSummarize():
dataset = [[1, 20, 0], [2, 21, 1], [3, 22, 0]]
summary = summarize(dataset)
assert (summary)
print('Attribute summaries: {0}'.format(summary))
def summarizeByClass(dataset):
separated = separateByClass(dataset)
summaries = {}
for classValue, instances in iter(separated.items()):
summaries[classValue] = summarize(instances)
return summaries
def calculateProbability(x, mean, stdev):
"""Oblicz prawdopodobieństwo"""
if stdev != 0:
exponent = math.exp(-(math.pow(x - mean, 2) / (2 * math.pow(stdev, 2))))
return (1 / (math.sqrt(2 * math.pi) * stdev)) * exponent
else:
return 0
def testCalculateProbability():
x = 71.5
mean = 73
stdev = 6.2
probability = calculateProbability(x, mean, stdev)
assert (probability)
print('Probability of belonging to this class: {0}'.format(probability))
def calculateClassProbabilities(summaries, inputVector):
"""Oblicz prawdopodobieństwo występowania klas"""
probabilities = {}
for value, summary in iter(summaries.items()):
probabilities[value] = 1
for i in range(len(summary)):
m = summary[i][0]
od = summary[i][1]
x = inputVector[i]
probabilities[value] *= calculateProbability(x, m, od)
return probabilities
def testCalculateClassProbabilities():
summaries = {0: [(1, 0.5)], 1: [(20, 5.0)]}
inputVector = [1.1, '?']
probabilities = calculateClassProbabilities(summaries, inputVector)
assert (probabilities)
print('Probabilities for each class: {0}'.format(probabilities))
def predict(summaries, inputVector):
"""Dokonaj predykcji jednego elementu zbioru danych wg danych prawdopodobieństw"""
probabilities = calculateClassProbabilities(summaries, inputVector)
bestLabel, bestProb = None, -1
for value, prob in iter(probabilities.items()):
if bestLabel is None or prob > bestProb:
bestProb = prob
bestLabel = value
return bestLabel
def testPredict():
summaries = {'A': [(1, 0.5)], 'B': [(20, 5.0)]}
inputVector = [1.1, '?']
result = predict(summaries, inputVector)
assert (result == 'A')
print('Prediction: {0}'.format(result))
def getPredictions(summaries, testSet):
"""Dokonaj predykcji dla wszystkich elementów w zbiorze danych"""
predictions = []
for i in range(len(testSet)):
predictions.append(predict(summaries, testSet[i]))
return predictions
def testGetPredictions():
summaries = {'A': [(1, 0.5)], 'B': [(20, 5.0)]}
testSet = [[1.1, '?'], [19.1, '?']]
predictions = getPredictions(summaries, testSet)
print('Predictions: {0}'.format(predictions))
def getAccuracy(testSet, predictions):
"""Oblicz dokładność przewidywań"""
correct = 0
for i in range(len(testSet)):
if testSet[i][-1] == predictions[i]:
correct += 1
return (correct / float(len(testSet))) * 100.0
def testGetAccuracy():
testSet = [[1, 1, 1, 'a'], [2, 2, 2, 'a'], [3, 3, 3, 'b']]
predictions = ['a', 'a', 'a']
accuracy = getAccuracy(testSet, predictions)
print('Accuracy: {0}'.format(accuracy))
def main():
filename = 'pima-indians-diabetes.data.csv'
splitRatio = 0.67
dataset = loadCsv(filename)
testLoadCsv()
trainingSet, testSet = splitDataset(dataset, splitRatio)
testSplitDataset()
print('Split {0} rows into train={1} and test={2} rows'.format(len(dataset), len(trainingSet), len(testSet)))
testSeparateByClass()
testMeanAndStdev()
testSummarize()
# prepare model
summaries = summarizeByClass(trainingSet)
testCalculateClassProbabilities()
testPredict()
testGetPredictions()
# test model
predictions = getPredictions(summaries, testSet)
testGetAccuracy()
accuracy = getAccuracy(testSet, predictions)
print('Accuracy: {0}%'.format(accuracy))
main()
|
188404d180fdedddcf88c40f080ff3aff2f30682 | haribalajihub/balaji | /rock,paper,scissor.py | 372 | 3.546875 | 4 | n,k=input().split()
if(n=="R" and k=="P"):
print("P")
elif(n=="R" and k=="S"):
print("R")
elif(n=="S" and k=="P"):
print("S")
elif(n=="S" and k=="R"):
print("R")
elif(n=="P" and k=="R"):
print("P")
elif(n=="P" and k=="S"):
print("S")
elif(n=="S" and k=="S"):
print("D")
elif(n=="p" and k=="P"):
print("D")
elif(n=="R" and k=="R"):
print("D")
|
333d90ad08b5cc5bb4fb0f5553beb3aa17dd633f | cmoussa1/sqlite-examples | /py-sqlite/py_sqlite.py | 3,303 | 3.765625 | 4 | '''
Python CLI utility/script to parse JSON object and
store them in an SQLite database.
Author: Christopher Moussa
Date: September 10th, 2019
'''
import json
import sqlite3
import pandas as pd
print("*" * 50)
print("\t\t PHASE 1")
print("*" * 50)
print("Description: Parse JSON file and read from dictionary")
print()
# open the json file in read mode, store the object as a dictionary
with open('pillar1.json', 'r') as f:
my_dict = json.load(f)
print("Accessing values by key")
print("-----------------------")
print("playerid: %s" % my_dict["playerid"])
print("name: %s" % my_dict["name"])
print("jersey_number: %d" % my_dict["jersey_number"])
print("primary_position: %s" % my_dict["primary_position"])
print("ops: %.3f" % my_dict["ops"])
print()
print("Printing dictionary object")
print("--------------------------")
print(json.dumps(my_dict, indent=2))
print()
print("*" * 50)
print("\t\t PHASE 2")
print("*" * 50)
print("Description: Parse dictionary object and store items in a list")
print()
# initialize empty list, append values to it to be used in a SQLite command
l = []
for val in my_dict:
l.append(my_dict[val])
print("List of values")
print("--------------")
print(l)
print()
print("*" * 50)
print("\t\t PHASE 3")
print("*" * 50)
print("Description: Connect to SQLite database and append values")
print()
conn = sqlite3.connect('BaseballPlayers.db')
print("opened BaseballPlayers DB successfully")
# access list elements to be used in SQLite command
conn.execute('''
INSERT INTO Giants (playerid, name, jersey_number, primary_position, ops)
VALUES (?, ?, ?, ?, ?);
''',(l[0], l[1], l[2], l[3], l[4]))
print("insert value into Giants table executed successfully")
l.clear()
print("****************")
print("* Giants Table *")
print("****************")
print(pd.read_sql_query("SELECT * FROM Giants", conn))
print()
print("print query successful")
print("*" * 50)
print("\t\t PHASE 4")
print("*" * 50)
print("Description: Read multiple JSON objects into a Python dictionary")
print()
# data will be a list of dictionaries
with open('players.json') as json_file:
data = json.load(json_file)
print("JSON file loaded successfully")
print()
print("Printing val from one of the dictionary objects")
print("-----------------------------------------------")
print(data[0]["name"]) # accessing dictionary value with the following syntax
print()
print("*" * 50)
print("\t\t PHASE 5")
print("*" * 50)
print("Description: Adding multiple dictionary objects to a SQLite table")
print()
print("Printing multiple dictionary objects from JSON file")
print("Adding multiple dictionary objects to a SQLite table")
print("---------------------------------------------------")
for d in data: # for each dictionary in the list of dictionaries
for k, v in d.items():
print("%s: %s" % (k, v))
l.append(v) # same process as before
conn.execute('''
INSERT INTO Giants (playerid, name, jersey_number, primary_position, ops)
VALUES (?, ?, ?, ?, ?);
''',(l[0], l[1], l[2], l[3], l[4]))
print("insert value into Giants table executed successfully")
l.clear()
print()
print("****************")
print("* Giants Table *")
print("****************")
print(pd.read_sql_query("SELECT * FROM Giants", conn))
print()
print("print query successful") |
542dd1d32912ae9624a68002ac2263be74cb1b67 | gomsang/AlgorithmTraining | /acmicpcdotnet/10809.py | 82 | 3.796875 | 4 | str = input()
for i in range(26):
print(str.find(chr(ord('a') + i)), end=' ') |
8b610007edef5073e395c8d56457a38f9588bb19 | MihaiPopa01/The-Cornfield-Application1 | /Algoritm2_Py/Algoritm2_Python/sort.py | 497 | 3.640625 | 4 | def partition(vector, left, right):
i = (left - 1)
pivot = vector[right]
for j in range(left, right):
if vector[j] <= pivot:
i = i + 1
vector[i], vector[j] = vector[j], vector[i]
vector[i + 1], vector[right] = vector[right], vector[i + 1]
return (i + 1)
def quick_sort(vector, left, right):
if left < right:
pi = partition(vector, left, right)
quick_sort(vector, left, pi - 1)
quick_sort(vector, pi + 1, right)
|
508aa3f26868ef7b56edeab3370afa6b3979260e | ashraf-amgad/Python | /Python Basics/date time/date_time.py | 794 | 4 | 4 |
# to get date and time
from datetime import datetime, timedelta
current_date = datetime.now()
print('\n',current_date.day,'-', current_date.month, '-', current_date.year)
print('current_date \t\t\t', current_date)
current_date_mince_one_minute = current_date - timedelta(minutes=1)
print('current_date_mince_one_minute \t',current_date_mince_one_minute)
current_date_mince_one_day = current_date - timedelta(days=1)
print('current_date_mince_one_day \t', current_date_mince_one_day)
current_date_mince_one_week = current_date - timedelta(weeks=1)
print('current_date_mince_one_week \t', current_date_mince_one_week, '\n')
birthday = input("please enter your birthday_date 'dd/mm/yyyy' ")
birthday_date = datetime.strptime(birthday, '%d/%m/%Y')
print('birthday is ', birthday_date)
|
438fcebc78ebda70c743b93f41b31141139de531 | sosma/rekt | /rekt.py | 2,500 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from random import choice
from time import sleep
different = "qwertyuiopasdfgjklzxcvbnm1234567890+!#¤%&/()=?<>|,;.:-_[]/QWERTYUIOPASDFGHJKLZXCVBNM "
while(True):
sleep(0.01)
letter0 = choice(different)
letter1 = choice(different)
letter2 = choice(different)
letter3 = choice(different)
letter4 = choice(different)
letter5 = choice(different)
letter6 = choice(different)
print letter0 + letter1 + letter2 + letter3 + letter4 + letter5 + letter6
if letter0=="[":
break
while(True):
sleep(0.0105)
letter0 = "["
letter1 = choice(different)
letter2 = choice(different)
letter3 = choice(different)
letter4 = choice(different)
letter5 = choice(different)
letter6 = choice(different)
print letter0 + letter1 + letter2 + letter3 + letter4 + letter5 + letter6
if letter1==" ":
break
while(True):
sleep(0.011)
letter0 = "["
letter1 = " "
letter2 = choice(different)
letter3 = choice(different)
letter4 = choice(different)
letter5 = choice(different)
letter6 = choice(different)
print letter0 + letter1 + letter2 + letter3 + letter4 + letter5 + letter6
if letter2=="]":
break
while(True):
sleep(0.01125)
letter0 = "["
letter1 = " "
letter2 = "]"
letter3 = choice(different)
letter4 = choice(different)
letter5 = choice(different)
letter6 = choice(different)
print letter0 + letter1 + letter2 + letter3 + letter4 + letter5 + letter6
if letter3=="R":
break
while(True):
sleep(0.0125)
letter0 = "["
letter1 = " "
letter2 = "]"
letter3 = "R"
letter4 = choice(different)
letter5 = choice(different)
letter6 = choice(different)
print letter0 + letter1 + letter2 + letter3 + letter4 + letter5 + letter6
if letter4=="e":
break
while(True):
sleep(0.015)
letter0 = "["
letter1 = " "
letter2 = "]"
letter3 = "R"
letter4 = "e"
letter5 = choice(different)
letter6 = choice(different)
print letter0 + letter1 + letter2 + letter3 + letter4 + letter5 + letter6
if letter5=="k":
break
while(True):
sleep(0.02)
letter0 = "["
letter1 = " "
letter2 = "]"
letter3 = "R"
letter4 = "e"
letter5 = "k"
letter6 = choice(different)
print letter0 + letter1 + letter2 + letter3 + letter4 + letter5 + letter6
if letter6=="t":
break
print "[x]Rekt"
|
533598eea11f5eda9c058ce3ef21a37c64a30a86 | SigitaD/python_mario | /more/mario.py | 600 | 3.9375 | 4 | from cs50 import get_int
# apibreziama pagindine funkcija, kuri yra piesti piramide
def main():
# paimamas piramides ausktis is f-cijos get_height
n = get_height()
for i in range(n):
print(" " * (n-i-1), end="")
print("#" * (i+1), end="")
print(" ", end="")
print("#" * (i+1))
# aprasoma f-cija, kuria is userio gaunamas piramides aukstis, kuris yra skaicius, ne daugiau 8 ir ne maziau 1
def get_height():
while True:
k = get_int("What is the height of the pyramid?\n")
if k < 9 and k > 0:
break
return k
main() |
ab88545ccc0b9393eb708bf009814d41de356c10 | GotfrydFamilyEnterprise/PythonTraining | /GCF.py | 808 | 3.953125 | 4 | # Greatest Common Factor - the largest number that x and y are divisible by
# ommit one from primes as it is goin to mess with our #MATH
primes = [2,3,5,7,11,13,17,19]
# x = 96 # /(2) => 48/(2) => 24/2 => 12/2 => 6/2 =>(3)
# y = 84 # /(2) => 42/(2) => 21/(3) => 7
x = 3*3*5*5*7*7*13*17
y = 2*2*3*5*5*7*19
divisors = []
_x = x
_y = y
for prime in primes:
while _x%prime == 0 and _y%prime == 0:
print (f"found common factor, {prime}")
_x = _x/prime
_y = _y/prime
divisors.append(prime)
gcf = 1
for divisor in divisors:
gcf = gcf * divisor
print(f"For {x} and {y}")
print(f"GCF = {gcf}")
# to find factors for each number
# pass one - looking for the first factor
# divide x and y by each number in variable primes until you find the
# smallest divisor with whole result |
eee12dc1af94842122b82a5d244dcb77c72fedda | kapteinstein/AlgDat | /div/quicksort.py | 688 | 3.796875 | 4 | def partition(A, lo, hi):
pivot = A[lo]
left = lo + 1
right = hi
done = False
while not done:
while left <= right and A[left] <= pivot:
left += 1
while left <= right and A[right] >= pivot:
right -= 1
if left > right:
done = True
else:
A[left], A[right] = A[right], A[left]
A[lo], A[right] = A[right], A[lo]
return(right)
def quicksort(A, lo, hi):
if lo < hi:
p = partition(A, lo, hi)
quicksort(A, lo, p-1)
quicksort(A, p+1, hi)
def main():
l = [1,4,3,5,76,5,3]
quicksort(l, 0, len(l)-1)
print(l)
if __name__ == '__main__':
main()
|
b368d0e2b778978a33fabded7c4fbbb6e27c1b08 | VicentePenaLet/RedesNeuronales | /DataLoader.py | 4,109 | 3.875 | 4 | import numpy as np
from sklearn.model_selection import train_test_split
class Dataset:
"""This Class defines a dataset and some key utilities for them"""
def __init__(self,path, oneHot = False, norm = False ):
"""The constructor for this class receibes the path to a .csv file with the data
:parameter path: a string containing the path of the data file
:parameter oneHot: False on default, set to True if the dataset labels are in One-hot encoding
:parameter norm: False on default, set to True if the dataset is already normalized"""
self.data = np.loadtxt(open(path, "rb"), delimiter=",", skiprows=1)
self.labels = self.data[:,-1]
self.features = self.data[:,0:-1]
self.onehot = oneHot
self.norm = norm
self.nClasses = int(max(self.labels)+1)
"""These matrix are used for splitting the dataset in train and test"""
self.trainFeatures = None
self.trainLabels = None
self.testFeatures = None
self.testLabels = None
def __len__(self):
"""The lenght of the dataset is the ammount of examples contained in it"""
return self.data.shape[0]
def nFeatures(self):
""":returns: number of features of the dataset"""
if self.onehot:
return int(self.data.shape[1]-self.nClasses)
else:
return self.data.shape[1]-1
def print(self):
"""This method prints the data as a matrix"""
print(self.data)
def normalization(self):
"""This method is used to normalize the features of the dataset,
if the dataset is already normalized, this method does nothing"""
if not self.norm:
"""Creates an auxiliary array for doing operations"""
temp=self.data
for i in range(temp.shape[1]-1):
"""Apply min-max normalization on each column of the dataset, excluding label columns"""
column = self.data[:,i]
max = column.max()
min = column.min()
normColumn = (column - min)/(max-min)
temp[:, i] = normColumn
self.data = temp
"""Set the norm parameter to true"""
self.norm = True
def OneHot(self):
"""Applies on-hot encoding to the labels of the dataset,
if the dataset is already in onehot encoded the method does nothing """
if not self.onehot:
"""extract labels from data, and useful information as number of classes"""
labels=self.data[:,-1]
n = int(self.data[:,-1].max())
"""create the new label matrix with the same number of rows as number of examples, and as many columns
as labels, initialize this matrix with 0"""
a, b = self.data.shape
temp = np.zeros((a, b + n))
temp[:,:-n]= self.data
for (example,i) in zip(labels,range(len(labels))):
"""For each example in the dataset put a 1 on the labels matrix based on the dataset label"""
temp[i, b-1] = 0
temp[i, b+int(example)-1] = 1
"""replace the old labels with the new label matrix"""
self.data = temp
self.labels = []
for i in range(n+1):
self.labels.append((self.data[:,b+i-1]).tolist())
self.labels = np.array(self.labels).T
"""Set the the onehot parameter to True"""
self.onehot = True
def trainTestSplit(self, testSize):
"""This method allows to split the dataset in test and train suing sklearn library"""
X_train, X_test, y_train, y_test = train_test_split(self.features, self.labels, test_size = testSize)
self.trainFeatures = X_train
self.trainLabels = y_train
self.testFeatures = X_test
self.testLabels = y_test
if __name__=='__main__':
"""Some test of the functions"""
Data = Dataset("Data/pulsar_stars.csv")
Data.normalization()
print(Data.nFeatures())
Data.OneHot()
print(Data.labels)
|
1a4f72b1d46d7f140ce166fdb1105e302799483b | scottwat86/Automate_Boring_Stuff_ | /ch2_flow_control/lesson05.py | 1,079 | 4.28125 | 4 | # Automate the Boring Stuff with Python 3
# Vid Lesson 5 - Flow Control
# name = 'Alice'
# name = 'Bob'
# if name == 'Alice': # Starts the if block statement
# print("Hi Alice") # Blocks are indented
# else:
# print('Bob')
# print('Done!')
#
# password = 'swordfish'
# if password == 'swordfish':
# print('Access granted!')
# else:
# print('Access Denied!')
name = 'Bob'
age = 3000
if name == 'Alice':
print('Hi Alice!')
elif age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead immortal vampire.')
elif age > 100:
print("You are not Alice granny.")
# you can have as many of the elif as you want but order of operation matter
else:
print("Hello?") # executes if none of the elif or if statement are true
# Truethy -> "" = False any other string is True
print("Enter your name")
name = input()
if name: # It is better to be explicit with conditionals
print('Thank you for entering a name.')
else:
print('You did not enter a name')
bool("t") # Evaluates truethy statements
|
f5b3f1baac1501f47e3cb0506415951f6cf1893b | AlexLymar/itstep | /lesson12/only_odd_arguments.py | 427 | 4.09375 | 4 | def only_odd_arguments(func):
def wrapper(*args):
for i in func(*args):
if i % 2:
return func
else:
print('Please add odd numbers!')
return wrapper
@only_odd_arguments
def add(a, b):
print(a + b)
return a, b
add(3, 3)
@only_odd_arguments
def multiply(a, b, c, d, e):
print(a * b * c * d * e)
return a, b, c, d, e
multiply(4, 5, 3, 1, 5)
|
ba265bb9d96f3ceeec3b311c1c36ce36f9c18206 | petitepirate/interviewQuestions | /q0028.py | 4,685 | 4.03125 | 4 | # This problem was asked by Palantir.
# Write an algorithm to justify text. Given a sequence of words and an integer line length
# k, return a list of strings which represents each line, fully justified.
# More specifically, you should have as many words as possible in each line. There should
# be at least one space between each word. Pad extra spaces when necessary so that each line
# has exactly length k. Spaces should be distributed as equally as possible, with the extra
# spaces, if any, distributed starting from the left.
# If you can only fit one word on a line, then you should pad the right-hand side with spaces.
# Each word is guaranteed not to be longer than k.
# For example, given the list of words ["the", "quick", "brown", "fox", "jumps", "over",
# "the", "lazy", "dog"] and k = 16, you should return the following:
# ["the quick brown", # 1 extra space on the left
# "fox jumps over", # 2 extra spaces distributed evenly
# "the lazy dog"] # 4 extra spaces distributed evenly
# ________________________________________________________________________________________
# Solution
# It seems like the justification algorithm is independent from the groupings, so immediately
# we should figure out two things:
# How to group lines together so that it is as close to k as possible (without going over)
# Given a grouping of lines, justifying the text by appropriately distributing spaces
# To solve the first part, let's write a function group_lines that takes in all the words in
# our input sequence as well as out target line length k, and return a list of list of words
# that represents the lines that we will eventually justify. Our main strategy will be to
# iterate over all the words, keep a list of words for the current line, and because we want
# to fit as many words as possible per line, estimate the current line length, assuming only
# one space between each word. Once we go over k, then save the word and start a new line with
# it. So our function will look something like this:
import math
def min_line(words):
return ' '.join(words)
def group_lines(words, k):
'''
Returns groupings of |words| whose total length, including 1 space in between,
is less than |k|.
'''
groups = []
current_sum = 0
current_line = []
for _, word in enumerate(words):
# Check if adding the next word would push it over
# the limit. If it does, then add |current_line| to
# group. Also reset |current_line| properly.
if len(min_line(current_line + [word])) > k:
groups.append(current_line)
current_line = []
current_line.append(word)
# Add the last line to groups.
groups.append(current_line)
return groups
# Then, we'll want to actually justify each line. We know for sure each line we feed
# from group_lines is the maximum number of words we can pack into a line and no more.
# What we can do is first figure out how many spaces we have available to distribute
# between each word. Then from that, we can calculate how much base space we should
# have between each word by dividing it by the number of words minus one. If there are
# any leftover spaces to distribute, then we can keep track of that in a counter, and
# as we rope in each new word we'll add the appropriate number of spaces. We can't add
# more than one leftover space per word.
def justify(words, length):
'''
Precondition: |words| can fit in |length|.
Justifies the words using the following algorithm:
- Find the smallest spacing between each word (available_spaces / spaces)
- Add a leftover space one-by-one until we run out
'''
if len(words) == 1:
word = words[0]
num_spaces = length - len(word)
spaces = ' ' * num_spaces
return word + spaces
spaces_to_distribute = length - sum(len(word) for word in words)
number_of_spaces = len(words) - 1
smallest_space = math.floor(spaces_to_distribute / number_of_spaces)
leftover_spaces = spaces_to_distribute - \
(number_of_spaces * smallest_space)
justified_words = []
for word in words:
justified_words.append(word)
current_space = ' ' * smallest_space
if leftover_spaces > 0:
current_space += ' '
leftover_spaces -= 1
justified_words.append(current_space)
return ''.join(justified_words).rstrip()
# The final solution should just combine our two functions:
def justify_text(words, k):
return [justify(group, k) for group in group_lines(words, k)]
|
307b11a20309f31bc0ff52f9c7913403730c5311 | BPCao/Assignments | /WEEK 1/THURSDAY/todo.py | 968 | 4.15625 | 4 | choice = ''
task_list = []
tasks = {}
def menu():
print ("Press 1 to add task: ")
print ("Press 2 to delete task: ")
print ("Press 3 to view all tasks: ")
print ("Press q to quit: ")
def user_input1():
user_task = input("Please enter a task: ")
user_priority = input("Please enter a priority: ")
tasks = {"Task name: " : user_task, "Task priority (HI, MED, LOW): " : user_priority}
task_list.append(tasks)
def user_input2():
user_input3()
deleter = int(input("Please select a number to delete that task: "))
deleter -= 1
del task_list[deleter]
def user_input3():
for index, task in enumerate(task_list, 1):
print (index, task["Task name: "], task["Task priority (HI, MED, LOW): "])
while choice != 'q':
menu()
choice = input("Please make your selection: ")
if choice == '1':
user_input1()
elif choice == '2':
user_input2()
elif choice == '3':
user_input3()
|
ebdad76a640d112fc965f85ec12901769b76240b | shuowenwei/LeetCodePython | /Medium/LC1305.py | 2,859 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
@author: Wei, Shuowen
https://leetcode.com/problems/all-elements-in-two-binary-search-trees/
MG: https://www.1point3acres.com/bbs/thread-841626-1-1.html
LC1305, LC173, LC21
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def getAllElements(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: List[int]
"""
def traverse(root, res):
if root is None:
return
traverse(root.left, res)
res.append(root.val)
traverse(root.right, res)
res1, res2 = [], []
traverse(root1, res1)
traverse(root2, res2)
p1, p2 = 0, 0
res = []
while p1 < len(res1) and p2 < len(res2):
if res1[p1] < res2[p2]:
res.append(res1[p1])
p1 += 1
else:
res.append(res2[p2])
p2 += 1
if p1 < len(res1):
res += res1[p1:]
if p2 < len(res2):
res += res2[p2:]
return res
# solution 2: use iterator, refer to LC173
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = []
self.pushLeftBranch(root)
def pushLeftBranch(self, ln):
while ln is not None:
self.stack.append(ln)
ln = ln.left
def peek(self):
"""
:rtype: int
"""
return self.stack[-1].val
def next(self):
"""
:rtype: int
"""
outnode = self.stack.pop()
self.pushLeftBranch(outnode.right)
return outnode.val
def hasNext(self):
"""
:rtype: bool
"""
return len(self.stack) > 0
class Solution(object):
def getAllElements(self, root1, root2):
"""
:type root1: TreeNode
:type root2: TreeNode
:rtype: List[int]
"""
res = []
iter1 = BSTIterator(root1)
iter2 = BSTIterator(root2)
# print(iter1, iter2, iter1==iter2)
while iter1.hasNext() and iter2.hasNext():
if iter1.peek() > iter2.peek():
res.append(iter2.next())
else:
res.append(iter1.next())
while iter1.hasNext():
res.append(iter1.next())
while iter2.hasNext():
res.append(iter2.next())
return res |
563e412c2fed2eb708b57591b0b22fcf0a140cb1 | hoju-os/comp-prob-solve | /ClassSeatingV2.py | 3,258 | 4.28125 | 4 | num = ""
while num != 'E':
print("1 - Find a student's name by entering a row and seat")
print("2 - Find a student's row and seat by entering their name")
print ("3 - Find all student's in a row by entering a row")
print ("4 - Find all student's sitting in a seat across all rows by entering a seat")
print("E - End the program")
HaveMenu = False
while HaveMenu == False:
try:
num = input("Enter a menu item: ")
if(num =="1" or num=="2" or num=="3" or num=="4" or num=="E"):
HaveMenu = True
except:
print ('please re-enter...')
#Array of names
names=[["joe","bill","tom","zeke"],["anne","kate","sally","joan"],["stu1","stu2","stu3","stu4"]]
#This is a nested loop on row and seat within a row using a range which gives us access to the row and seat index
if num == "1":
try:
row =int(input("Enter the row: "))
seat =int(input("Enter the seat: "))
except ValueError:
print("Integers only")
try:
print("The student sitting in row " + str(row)
+ " seat " + str(seat) + " is " + names[row-1][seat-1])
except IndexError:
print("Seat or row not valid")
except NameError:
pass
#The student sitting in row <row> seat <seat> is <name>
if num == "2":
found = False
searchname=input("Enter a name to find: ")
for row in range (0,len(names)):
for seat in range (0,len(names[row])):
if names[row][seat]==searchname:
print (searchname + " is sitting in row " + str(row+1) + " seat " + str(seat+1))
found = True
if found == False:
print("Name not found")
if num == "3":
print("menu item 3")
try:
row =int(input("Enter the row: "))
except ValueError:
print("Input must be an integer...")
try:
if row > 0 and row <= len(names):
print("The students sitting in row " + str(row) + " are ", end = "")
for x in names[row-1]:
print(x, end=" ")
print()
else:
print("Please enter a valid row number")
except NameError:
pass
#put code here
if num == "4":
print("menu item 4")
try:
seatSearch = int(input("Enter the seat: "))
except ValueError:
print("Input must be an integer...")
seatSearch = seatSearch - 1
if seatSearch > 0 and seatSearch < len(names[0]):
print("The students sitting in seat " + str(seatSearch + 1) + " are ", end = "")
for row in range (0,len(names)):
for seat in range (0,len(names[row])):
if seat == seatSearch:
print(names[row][seat] + " in row " + str(row + 1) + ",", end=" ")
print()
else:
print("Please enter valid seat number...")
#put code here
if num =="E":
print("Goodbye")
|
9b88c929699d064b78799710e831aaa52246bf74 | Nirali0029/Algorithms-in-python | /Algorithms/Searching/binary_search.py | 276 | 3.515625 | 4 | a=[3,54,74,6,88,99]
key=(int)(input())
a.sort()
n=len(a)
low=0
high=n-1
mid=0
while(low<=high):
mid=(low+high)//2
if a[mid]==key:
print(str(key)+"found")
break
elif key<a[mid]:
high=mid-1
elif key>a[mid]:
low=mid+1
else:
print(str(key)+" Not found")
|
e01a6745f3fe090c308d4e401d3d26b06978681b | jjennyko/python1 | /hw_31.py | 848 | 3.765625 | 4 | #1.
#女
#2.
def bayes_theorem(p_a, p_b_given_a, p_b_given_not_a):
# calculate P(not A)
not_a = 1 - p_a
# calculate P(B)
p_b = p_b_given_a * p_a + p_b_given_not_a * not_a
# calculate P(A|B)
p_a_given_b = (p_b_given_a * p_a) / p_b
return p_a_given_b
# P(A): P(女生)
# P(not A): P(男生)
p_a = 0.1
# P(B|A): P(長髮|女生)
p_b_given_a = 0.5
# P(B|not A): P(長髮|男生)
p_b_given_not_a = 0.1
# calculate P(A|B): P(女生|長髮)
result = bayes_theorem(p_a, p_b_given_a, p_b_given_not_a)
# summarize
# P(女生|長髮)
print('P(A|B) = {0}'.format(round(result * 100,2)))
#3.
#Anwer:透過貝式定理的運算,得出長髮男生的可能性大於女生,造成決策上的改變,所以以作業和投影片的例子可以看出,先驗分配的重要性,假設錯誤,決策可能就會錯誤。
|
9191773f87f9ecf49d1b50f30c2d38795ff1025c | nyp-sit/python | /functions/validator.py | 273 | 3.859375 | 4 | def is_number(string):
try:
float(string)
except ValueError:
return False
else:
return True
def is_valid_phone(string):
if len(string) == 8:
if string[0] == '6' or string[0] == '9':
return True
return False
|
a03c8a55792d2b3e5432778da8659d031281e252 | msitek/sql | /sqld.py | 492 | 3.90625 | 4 | # import from csv
# import the csv library
import csv
import sqlite3
with sqlite3.connect("new.db") as connection:
c = connection.cursor()
# open the csv file and assign it to a variable
employees = csv.reader(open("employees.csv", "rU"))
# create a new table called employees
c.executescript('''DROP TABLE IF EXISTS employees;
CREATE TABLE employees (firstname TEXT, lastname TEXT)''')
# insert data into table
c.executemany("INSERT INTO employees VALUES (?, ?)", employees)
|
95b533a22375c58adab5c78f94508ec288905f9b | kkloberdanz/Opperating-Systems | /Assignment 1/assignment-1/Problem3/testmult.py | 2,023 | 3.625 | 4 | import random
def sum_string(s):
tot = 0
for letter in s:
digit = int(letter)
tot += digit
return tot
def sum_vector(v):
tot = 0
for string in v:
tot += int(string)
return tot
def mult_with_carry(op1, op2, carry, result):
op1 = int(op1)
op2 = int(op2)
result = (op1 * op2) + carry
if result < 10:
carry = 0
return result, carry
else:
carry = result // 10
result = result % 10
return result, carry
def mult_big_ints(s1, s2):
result_vector = []
result_string = ""
if len(s1) > len(s2):
s1, s2 = s2, s1
print("Multiplying:", s1, s2)
n = 0
for i in range(len(s1) - 1, -1, -1):
carry = 0
result = 0
for j in range(len(s2) - 1, -1, -1):
result, carry = mult_with_carry(s1[i], s2[j], carry, result)
result_string += str(result)
# print(s1[i], '*' , s2[j], '=', result, "carry =", carry)
if carry:
result_string += str(carry)
result_string_reverse = result_string[::-1]
result_string_reverse += n*"0"
n += 1
# print(result_string_reverse)
result_vector.append(result_string_reverse)
result_string = ""
'''
print(result_vector)
print(sum_vector(result_vector))
'''
return sum_vector(result_vector)
for n in range(10):
s1 = ""
s2 = ""
for i in range(0, random.randint(1, 6)):
s1 += str(random.randint(1, 9))
for i in range(0, random.randint(1, 6)):
s2 += str(random.randint(1, 9))
print("Multiplying:", s1, s2)
actual_result = int(s1) * int(s2)
print("Actual result:", actual_result)
obtained_result = mult_big_ints(s1, s2)
print(obtained_result)
if obtained_result == actual_result:
print("GOOD")
else:
print("BAD")
'''
s2 = "1234"
s1 = "23"
'''
'''
s2 = "36943"
s1 = "8451"
print("Multiplying:", s1, s2)
print(mult_big_ints(s1, s2))
'''
|
a369359537df1b03ac7093b424582c997bed21c4 | njiiri12/passwordlocker | /credentials.py | 2,034 | 4.09375 | 4 | class User:
"""
Class that generates new instances of users
"""
user_list =[]
def __init__(self,first_name,last_name,password):
self.first_name = first_name
self.last_name = last_name
self.password = password
def save_user(self):
'''
save_user method saves user objects into user_list
'''
User.user_list.append(self)
new_user = User("Yvonne","Njiiri","yves012")
print("First Name?")
first_name = input()
print("Last Name?")
last_name = input()
print("Password?")
password = input()
user_name = first_name+ ""+last_name
print(user_name,password)
print("\n")
print(new_user.last_name,new_user.first_name,new_user.password)
class Credentials :
'''
class that creates users_accounts credentials
'''
credentials_list = []
def __init__(self, account_name, first_name, last_name, user_password):
self.account_name = account_name
self.first_name = first_name
self.last_name = last_name
self.user_password = user_password
@classmethod
def save_credential(self):
'''
Method to save a new object in the credential list
'''
Credentials.credentials_list.append(self)
@classmethod
def delete_credential(self):
'''
Method to delete a credential from the list
'''
Credentials.credentials_list.remove(self)
@classmethod
def find_by_account_name(cls, account_name):
'''
Method that takes in a site name and returns the credentials
'''
for credential in cls.credentials_list:
if credential.account_name == account_name:
return credential
@classmethod
def credential_exist(cls, account_name):
'''
Method that checks if a credential actually exists
'''
for credential in cls.credentials_list:
if credential.account_name == account_name:
return True
return False |
7cb265ba2946b255560b3ba38c72a7cd7774f29f | ashiqcvcv/Datastructure | /tree_firstapproach.py | 3,185 | 3.671875 | 4 | class node:
def __init__(self,key):
self.left = None
self.right = None
self.value = key
'''
10 -> root
/ \
5 15
/ \ / \
3 6 13 16
'''
#creating a tree from arr
head = node(10)
head.left = node(5)
head.left.left = node(3)
head.left.right = node(6)
head.right = node(15)
head.right.left = node(13)
head.right.right = node(16)
class tree:
def __init__(self,root):
self.root = root
def bfs(self):
if self.root == None:
return
queue = []
def que(data):
queue.append(data)
return queue
def deq():
queue.pop(0)
return
currentNode = self.root
que(currentNode)
while len(queue) > 0:
while currentNode == None and len(queue) > 1:
deq()
currentNode = queue[0]
if currentNode == None:
return
que(currentNode.left)
que(currentNode.right)
print(currentNode.value)
deq()
currentNode = queue[0]
def inorder(self):
if self.root == None:
return
currentRoot = self.root
def orderIn(currentRoot):
if currentRoot != None:
orderIn(currentRoot.left)
print(currentRoot.value)
orderIn(currentRoot.right)
orderIn(currentRoot)
def preorder(self):
if self.root == None:
return
currentRoot = self.root
def orderIn(currentRoot):
if currentRoot != None:
print(currentRoot.value)
orderIn(currentRoot.left)
orderIn(currentRoot.right)
orderIn(currentRoot)
def postorder(self):
if self.root == None:
return
currentRoot = self.root
def orderIn(currentRoot):
if currentRoot != None:
orderIn(currentRoot.left)
orderIn(currentRoot.right)
print(currentRoot.value)
orderIn(currentRoot)
def maxHeight(self):
def height(root,maxHeight,currentHeight):
if root == None:
return currentHeight-1
heightLeft = height(root.left,maxHeight,currentHeight+1)
heightRight = height(root.right,maxHeight,currentHeight+1)
if heightRight >= heightLeft and heightRight > maxHeight:
maxHeight = heightRight
elif heightLeft > heightRight and heightLeft > maxHeight:
maxHeight = heightLeft
return maxHeight
print(height(self.root,1,1))
def insertion(self,insertRoot,insertElement,position):
root = self.root
if root == None:
root = node(insertRoot)
if position == 'l':
root.left = node(insertElement)
return
def recursion(root):
if root == None:
return
if root.value == insertRoot:
if position == 'l':
root.left = node(insertElement)
elif position == 'r':
root.right = node(insertElement)
return
else:
recursion(root.left)
recursion(root.right)
return
recursion(root)
def deletion(self,deleteRoot):
if self.root == None:
return
currentRoot = self.root
def recursion(currentRoot):
if currentRoot.left == None or currentRoot.right == None:
return
if currentRoot.left.value == deleteRoot:
currentRoot.left = None
return
elif currentRoot.right.value == deleteRoot:
currentRoot.right = None
return
recursion(currentRoot.left)
recursion(currentRoot.right)
return
recursion(currentRoot)
complete = tree(head) |
0445968c798e213ec1180b7eeabc79954b897292 | zhuyuedlut/advanced_programming | /chapter2/starts_ends_with_exp.py | 912 | 3.8125 | 4 | file_name = 'python.txt'
print(file_name.endswith('.txt'))
print(file_name.startswith('abc'))
url_val = 'http://www.python.org'
print(url_val.startswith('http:'))
import os
file_name_list = os.listdir('.')
print(file_name_list)
print([name for name in file_name_list if name.endswith(('.py', '.h')) ])
print(any(name.endswith('.py') for name in file_name_list))
from urllib.request import urlopen
def read_data(name):
if name.startswith(('http:', 'https:', 'ftp:')):
return urlopen(name).read()
else:
with open(name) as f:
return f.read()
web_pre_list = ['http:', 'ftp:']
url_val = 'http://www.python.org'
print(url_val.startswith(tuple(web_pre_list)))
print(url_val.startswith(web_pre_list))
file_name = 'test.txt'
print(file_name[-4:] == '.txt')
url_val = 'http://www.python.org'
print(url_val[:5] == 'http:' or url_val[:6] == 'https:' or url_val[:4] == 'ftp:')
|
df5d2017e907e6927efe8ece3cfa8374b6cff522 | denizobi/aws-devops-workshop | /python/coding-challenges/cc-011-drawbox/mydrawbox.py | 211 | 4.03125 | 4 | hastag = int(input("Please enter the number"))
if hastag == 1:
print("#")
else:
print("#" * hastag)
for i in range(hastag-2):
print("#" + " " *(hastag-2) + "#")
print("#" * hastag)
|
5d0be30d045c6668fd8784bfa627b303466e2c89 | pedroceciliocn/python_work | /Chapter_5_if_statements/toppings_3.py | 1,267 | 4.21875 | 4 | #Checking for special items:
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
print(f"Adding {requested_topping}.")
print("\nFinished making your pizza!")
# but if the pizzeria runs out of green peppers?
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we are out of green peppers right now.")
else:
print(f"Adding {requested_topping}.")
print("\nFinished making your pizza!")
#Checking that a list is not empty:
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print(f"Adding {requested_topping}.")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")
#Using multiple lists:
availabe_toppings = ['mushrooms', 'olives', 'green peppers',
'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in availabe_toppings:
print(f"Adding {requested_topping}.")
else:
print(f"Sorry, we dont have {requested_topping}.")
print("\nFinished making your pizza!") |
de6cc09b3fb872fbee34d0016a7e3c3d79fe9940 | MengSunS/daily-leetcode | /design/432.py | 2,804 | 4 | 4 | class Block:
def __init__(self, val=0):
self.val = val
self.keys = set()
self.before = None
self.after = None
def insert_after(self, new_block):
tmp = self.after
self.after = new_block
new_block.before = self
new_block.after = tmp
tmp.before = new_block
def remove(self):
self.before.after = self.after
self.after.before = self.before
self.before = None
self.after = None
class AllOne:
def __init__(self):
"""
Initialize your data structure here.
"""
self.head = Block()
self.tail = Block()
self.head.after = self.tail
self.tail.before = self.head
self.dict = {}
def inc(self, key: str) -> None:
"""
Inserts a new key <Key> with value 1. Or increments an existing key by 1.
"""
if key in self.dict:
cur_block = self.dict[key]
cur_block.keys.remove(key)
else:
cur_block = self.head
if cur_block.val + 1!= cur_block.after.val:
new_block = Block(cur_block.val + 1)
cur_block.insert_after(new_block)
cur_block.after.keys.add(key)
self.dict[key] = cur_block.after
if cur_block.val != 0 and not cur_block.keys:
cur_block.remove()
def dec(self, key: str) -> None:
"""
Decrements an existing key by 1. If Key's value is 1, remove it from the data structure.
"""
cur_block = self.dict[key]
del self.dict[key]
cur_block.keys.remove(key)
if cur_block.val - 1 != cur_block.before.val:
new_block = Block(cur_block.val - 1)
cur_block.before.insert_after(new_block)
cur_block.before.keys.add(key)
self.dict[key] = cur_block.before
if cur_block.val != 0 and not cur_block.keys:
cur_block.remove()
def getMaxKey(self) -> str:
"""
Returns one of the keys with maximal value.
"""
if self.tail.before.val == 0:
return ""
ans = self.tail.before.keys.pop()
self.tail.before.keys.add(ans)
return ans
def getMinKey(self) -> str:
"""
Returns one of the keys with Minimal value.
"""
if self.head.after.val == 0:
return ""
ans = self.head.after.keys.pop()
self.head.after.keys.add(ans)
return ans
# Your AllOne object will be instantiated and called as such:
# obj = AllOne()
# obj.inc(key)
# obj.dec(key)
# param_3 = obj.getMaxKey()
# param_4 = obj.getMinKey()
|
c13ea6d47d1251808b9cd35efca5f65a6ede524d | pskim219/dojang | /ex0303.py | 178 | 3.546875 | 4 | # 코드 3-3 리스트를 만드는 코드
my_list1 = []
print(my_list1)
my_list2 = [1, -2, 3.14]
print(my_list2)
my_list3 = ['앨리스', 10, [1.0, 1.2]]
print(my_list3)
|
7231aaeea5e6fbf42c431d18ab516cd280cda804 | jdgsmallwood/ProjectEuler | /project_euler_solutions/problem_25.py | 264 | 3.640625 | 4 | num_of_digits = 1000
index = 2
fnum = 1
fnum_prev = 1
storage = 0
while len(str(fnum))<num_of_digits:
storage = fnum
fnum = fnum_prev + fnum
fnum_prev = storage
index +=1
print(fnum)
print('Index is %i' % index)
# I think the answer is 4782. |
7859312f80a3c46efc7a82d3d0e8ea3b6aab119b | ozgecangumusbas/I2DL-exercises | /exercise_04/exercise_code/networks/optimizer.py | 1,182 | 3.59375 | 4 | # Naive Optimizer using full batch gradient descent
import os
import pickle
import numpy as np
from exercise_code.networks.linear_model import *
class Optimizer(object):
def __init__(self, model, learning_rate=5e-5):
self.model = model
self.lr = learning_rate
def step(self, dw):
"""
:param dw: [D+1,1] array gradient of loss w.r.t weights of your linear model
:return weight: [D+1,1] updated weight after one step of gradient descent
"""
weight = self.model.W
########################################################################
# TODO: #
# Implement the gradient descent for 1 step to compute the weight #
########################################################################
pass
weight = weight - self.lr * dw
########################################################################
# END OF YOUR CODE #
########################################################################
self.model.W = weight
|
9ca7fe11c4cd4a3dd454efe38c60c98d1a631579 | vagaganova/homeworks | /hw04092020/HW2.py | 292 | 3.5625 | 4 | my_list = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123]
new_list =[my_list[i+1] for i in range(len(my_list)-1) if my_list[i+1]>my_list[i]]
print (list(new_list))
# my_list = [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123]
# new_list =[i*5 for i in my_list if i%3 == 0]
# print (list(new_list))
|
bd26c0a39b147f1be82ff2dd802d55c6d1b03a1b | office1978/python | /konstant.py | 381 | 3.546875 | 4 | # -*- encoding: utf-8 -*-
k = {"e":"2.718281828459045235360287471352", "pi":"3.1415926535897932384626433832795028841971"}
d=input("Введите константу: ")
d=d.lower()
if d in k:
t=int(input("Введите точность: "))
print ('%.*s' %((1+t+k[d].find(".")), k[d]))
else:
print ("Вы ошиблись. Попробуйте снова.")
|
80961f6272eacf308068d94c1c5ed9e579ca44dd | pwnmeow/Basic-Python-Exercise-Files | /ex/coinFlip.py | 143 | 3.5 | 4 | import random
def coilflip ():
coinValue = random.randint(0,1);
if coinValue == 1:
print("heads")
else:print("tails")
coilflip() |
8316fc4567d4af9951faf51ede04a5568f2824ad | pauliwu/Introduction-to-programming-in-python | /Laboratory 13/answers/wdp_ftopt_l12z02r_B.py | 1,100 | 3.640625 | 4 | """
Wstep do programowania
Kolokwium termin 0
9.01.2019 grupa P11-57j
imie:
nazwisko:
indeks:
"""
'''
Zadanie 2 (15 pkt.)
Przygotuj program, w którego zadaniem będzie wydrukowanie alfabetu
w porządku malejącym (od z do a). Wykorzystaj informację,
że w kodzie ASCI literom z-a odpowiadają liczby od 122 do 97.
Sformatuj napis wyjściowy tak aby w jednym wierszu znalazły się
3 kolejne litery alfabetu rozdzielone znakiem ,.
Pamiętaj o dobrych praktykach pisania kodu,
tzn. przygotuj funkcję main() oraz jej wywołanie.
Oczekiwany komunikat na ekranie:
Alfabet w porządku malejacym:
z,y,x
w,v,u
t,s,r
q,p,o
n,m,l
k,j,i
h,g,f
e,d,c
b,a,
'''
def main(): # definicja funkcji main 1pkt
print("Alfabet w porządku malejacym:")
x = 0 # zapewnienie sobie zmiennej do
for i in range(122, 96,-1): # poprawna pętla 4 pkt
x+=1
if x%3: # warunek na ; 2pkt
print(chr(i), end=",") # poprawna zamiana kodu ASCI na znak 3
else: # kiedy enter 2 pkt
print(chr(i), end="\n") # drukowanie komunikatów 2
main() # wywołanie funkcji main 1 pkt
|
04313bf78325ac255ec1db93e0ad26a435350e82 | he44/Practice | /aoc_2019/24/24.py | 3,055 | 3.703125 | 4 | """
Formulation
a scan of the entire area fits into a 5x5 grid (your puzzle input). The scan shows bugs (#) and empty spaces (.).
each tile updated every minute, simultaneously (counting for all first, then changing)
Maybe need some bit operation: 25-bit number
This way, it's easy to check if two layours are the same
"""
# Return the 2-D list
def read_input(file_path):
grid = [ [ 0 for i in range(5)] for j in range(5)]
with open(file_path, 'r') as fp:
lines = fp.readlines()
for i in range(len(lines)):
line = lines[i].strip()
for j in range(len(line)):
if line[j] == '#':
grid[i][j] = 1
else:
grid[i][j] = 0
return grid
# Convert grid to a number
# following the definition of biodiversity
def grid_to_num(grid):
num = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
power = i * 5 + j
# print(i, j, power, 2 ** power)
if grid[i][j] == 0:
continue
num += 2 ** (power)
return num
# Count adjacent bugs
def count_in_adjacent_tiles(grid, i, j):
count = 0
h = len(grid)
w = len(grid[0])
# top neighbor
if i - 1 >= 0:
count += int(grid[i-1][j] == 1)
# left neighbor
if j - 1 >= 0:
count += int(grid[i][j-1] == 1)
# right neighbor
if j + 1 < w:
count += int(grid[i][j+1] == 1)
# bottom neighbor
if i + 1 < h:
count += int(grid[i+1][j] == 1)
return count
# Update the grid
def update_grid(grid):
new_grid = [ [ 0 for i in range(5)] for j in range(5)]
for i in range(len(grid)):
for j in range(len(grid[i])):
# A bug dies (becoming an empty space)
# unless there is exactly one bug adjacent to it.
if grid[i][j] == 1 and count_in_adjacent_tiles(grid, i, j) != 1:
new_grid[i][j] = 0
# An empty space becomes infested with a bug
# if exactly one or two bugs are adjacent to it.
elif grid[i][j] == 0 and count_in_adjacent_tiles(grid, i, j) in (1,2):
new_grid[i][j] = 1
else:
new_grid[i][j] = grid[i][j]
return new_grid
# Visualize the grid
def visual_grid(grid):
print('+++++++++++++++++++++++++++')
for row in grid:
print(row)
print(grid_to_num(grid))
print('+++++++++++++++++++++++++++')
def main():
minute = 0
# grid = read_input('eg_input.txt')
grid = read_input('24_input.txt')
num = grid_to_num(grid)
visual_grid(grid)
new_grid = grid
seen_numbers = {}
while True:
minute += 1
if minute % 100 == 0:
print(minute)
new_grid = update_grid(new_grid)
new_num = grid_to_num(new_grid)
if new_num in seen_numbers:
print('Done!')
visual_grid(new_grid)
break
seen_numbers[new_num] = 1
if __name__ == "__main__":
main()
|
adb8bc099f0140000ca5bf9ae4dbb898d6c6c57e | Guzinanda/Interview-Training-Microsoft | /03 Data Structures/Linked Lists/linked_list.py | 3,323 | 3.96875 | 4 | """
Linked List (Singly Linked List)
HEAD
NODE [A | ] -> [B|] -> [C|] -> [D|] -> NULL
DATA NEXT
"""
class Node:
def __init__(self, data): # Constructor
self.data = data
self.next = None
class LinkedList:
def __init__(self): # Constructor
self.head = None
def print_list(self):
cur_node = self.head
while cur_node:
print(cur_node.data)
cur_node = cur_node.next
# Append new nodes and creates the initial node if there is no one: [A|] -> NULL or [A|] -> [B|] -> NULL
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
# Insert at the beggining of the Linked List: [E|] -> [A|] -> [B|] -> NULL
def prepend(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
# Insert a node in a place: [A|] -> [B|] -> [E|] -> [C|] -> NULL
def insert_after_node(self, prev_node, data):
if not prev_node:
print("Previous node is not in the list")
return
new_node = Node(data)
new_node.next = prev_node.next
prev_node.next = new_node
# Delete a node by key (value)
def delete_node(self,key):
cur_node = self.head
# If is the head:
if cur_node and cur_node.data == key:
self.head = cur_node.next
cur_node = None
return
# If is anithing else:
prev = None
while cur_node and cur_node.data != key:
prev = cur_node
cur_node = cur_node.next
if cur_node is None:
return
prev.next = cur_node.next
# Delete a node by position
def delete_node_at_pos(self, pos):
cur_node = self.head
# If is the head:
if pos == 0:
self.head = cur_node.next
cur_node = None
return
# If is anything else:
prev = None
count = 0
while cur_node and count != pos:
prev = cur_node
cur_node = cur_node.next
count += 1
if cur_node is None:
return
prev.next = cur_node.next
cur_node = None
# Know the len of the Linked List in a iterative way
def len_iterative(self):
count = 0
cur_node = self.head
while cur_node:
count += 1
cur_node = cur_node.next
return count
# Know the len of the Linked List in a recursive way
def len_recursive(self, node):
if node is None:
return 0
return 1 + self.len_recursive(node.next)
# TEST __________________________________________________________________________________________
"""
llist = LinkedList()
llist.append('A')
llist.append('B')
llist.append('C')
llist.append('D')
llist.prepend('E')
llist.insert_after_node(llist.head.next, "F")
llist.delete_node('B')
llist.delete_node_at_pos(4)
print(llist.len_iterative())
print(llist.len_recursive(llist.head))
llist.print_list()
"""
|
73b07c83ccae53743e87f04e500c221c7cf3eae7 | linux740305/git-test | /git-test/3-13變量的類型-以及變量的轉換.py | 266 | 3.6875 | 4 | age = input("請輸入年齡")#input輸入年齡
age_num = int(age)#....>整形....去除雙引號之後的值20
if age_num>18:#if 條件:如果年齡大於如果年齡大於18便可進入網咖用if來判斷是否已滿18
print("已成年可以去網咖囉!")
|
090006de77e98890dc5b76a18ee8f010027d8f80 | axg1/Algorithm_Study | /CodeUp/CodeUp_6079.py | 80 | 3.578125 | 4 | a = int(input())
sum = 0
b = 0
while sum<a:
b += 1
sum += b
print(b)
|
6f0c0d0b1e159674153b43b36f4920961deb4b26 | wazcov/devscover-youtube | /learning_python/unit_testing/pymain.py | 544 | 3.625 | 4 | #! /usr/local/bin/python3
def textStuff():
initdata = ['picard', 'kirk', 'Picard', 'archer', 'janeway', 'picard', 'archer']
mr = {}
for word in initdata:
word = word.upper()
if (word in mr):
mr[word] += 1
else:
mr[word] = 1
print(mr)
print('----')
reduced = {}
mr2 = list(map(str.upper, initdata))
for x in mr2:
reduced[x] = mr2.count(x)
print(reduced)
def doubleme(x):
print(x * 2)
return x * 2
if __name__ == "__main__":
textStuff() |
c46851da30843c6e92d53e84490e7de7cb3166d2 | imji0319/myProject | /pro1/test1/test1_4.py | 357 | 3.8125 | 4 | '''
Created on 2017. 9. 17.
@author: jihye
'''
#문자 회문(palindrome) 찾기
#-*- coding:utf-8 -*-
user_str=input('글자를 입력하시오 :')
str_len=len(user_str)
for i in range(0,str_len-1):
if user_str[i]==user_str[str_len-1+i]:
print('palindrome')
else :
print('not a palindrome')
|
fc43f83d8f5283559289816c22cfab7a41604b37 | mbyrd314/cryptopals | /set2_challenge13.py | 6,482 | 3.53125 | 4 | from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from base64 import b64encode, b64decode
import os, random, string
def parse_cookie(cookie):
"""
Takes inputs in the form of 'foo=bar&baz=qux' and converts them into a dictionary
mapping keys to values. Assumes that the input strings are well-formed.
Args:
cookie (str): String consisting of key=value pairs separated by '&'
Returns:
ans {dict}: Dictionary mapping keys to values
"""
ans = {}
cookie = cookie.split(b'&')
for pair in cookie:
k, v = pair.split(b'=')
ans[k] = v
return ans
def profile_for(email):
"""
Creates a user profile with the given email address. Encodes it in the key=value
cookie format described in parse_cookie. Generates a uid and defaults to user
level access for new profiles. Email strings are sanitized before encoding.
Args:
email (str): String email address to be encoded in a profile
Returns:
cookie (str): Formatted cookie representing the new profile
"""
email = sanitize(email)
uid = 10 # This hopefully wouldn't be fixed in a real implementation, but this could work for other uids
role = 'user'
cookie = f'email={email}&uid={uid}&role={role}'.encode()
print(f'Making profile. cookie: {cookie}')
return cookie
def encrypt_profile(email, key):
profile = profile_for(email)
return encrypt_aes_ecb(profile, key)
def decrypt_profile(ciphertext, key):
"""
Does byte-at-a-time decryption of the encrypted profile using the functions
written for the last challenge. Returns the parsed profile.
Args:
ciphertext (bytes): Encrypted profile to be decrypted
Returns:
(dict): Dictionary mapping profile keys to values
"""
cookie = decrypt_aes_ecb(ciphertext, key)
print(f'cookie: {cookie}')
return parse_cookie(cookie)
def PKCS_7_pad(msg, block_size):
"""
Implementation of PKCS7 padding
Args:
msg (bytes): Message to be padded
block_size (bytes): Block size that the message needs to be padded to
Returns:
b_msg (bytes): PKCS padded version of the input message
"""
if len(msg) > block_size:
diff = block_size - len(msg) % block_size
else:
diff = block_size - len(msg)
#print(diff)
b_msg = msg
#print(bytes([diff])*diff)
b_msg += bytes([diff]) * diff
#print(b_msg)
return b_msg
def PKCS_7_unpad(msg):
"""
Undoes PKCS7 padding
Args:
msg (bytes): Message to be unpadded. If not padded with PKCS7, returns the original message
Returns:
new_msg (bytes): Returns either the unpadded version of the original message
or the original message if not padded
"""
padding_size = msg[-1]
#print('padding_size: %d' % padding_size)
for i in range(len(msg)-1, len(msg)-padding_size-1, -1):
if msg[i] != padding_size:
#print('No Padding')
return msg
#print('Padding Removed')
new_msg = msg[:-padding_size]
return new_msg
def encrypt_aes_ecb(plaintext, key):
"""
Implementation of AES ECB mode encryption using the Python cryptography library
Args:
plaintext (bytes): The plaintext message to be encrypted
key (bytes): The AES secret key
Returns:
cmsg (bytes): The encrypted ciphertext of the plaintext input
"""
block_size = len(key)
msg = PKCS_7_pad(plaintext, block_size)
backend = default_backend()
cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
encryptor = cipher.encryptor()
cmsg = encryptor.update(msg) + encryptor.finalize()
return cmsg
def decrypt_aes_ecb(ciphertext, key):
"""
Implementation of AES ECB mode decryption using the Python cryptography library
Args:
ciphertext (bytes): The ciphertext message to be decrypted
key (bytes): The AES secret key
Returns:
msg (bytes): The decrypted version of the ciphertext input
"""
backend = default_backend()
cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
decryptor = cipher.decryptor()
msg = decryptor.update(ciphertext) + decryptor.finalize()
return PKCS_7_unpad(msg)
def aes_keygen(keysize):
"""
Generates a random key of length keysize
Args:
keysize (int): Length of the desired key in bytes
Returns:
(bytes): A generated key of length keysize
"""
return os.urandom(keysize)
def sanitize(s):
"""
Implements rudimentary input sanitization to prevent obvious injection flaws
Args:
s (str): String input to be sanitized
Returns:
ret (str): Sanitized version of the input string
"""
ret = ''
for c in s:
if c not in ['&', '=']:
ret += c
else:
ret += '_'
return ret
if __name__ == '__main__':
"""
Main function that will determine a ciphertext that will correctly correspond
to a user with admin access.
"""
key = aes_keygen(16)
# Making an arbitrary email of the correct length so that the cookie string
# email=test_email&uid=10&role= will end a block after role=. This will be the
# prefix of the forged cookie.
test_email = 'AAfoo@bar.com'
test_ctext = encrypt_profile(test_email, key)
# All but the last block of the ciphertext forms the prefix of the forged cookie
prefix = test_ctext[:-16]
# Forming another arbitrary email string. This time it needs to be the correct
# length so that the word admin PKCS#7 padded to the block size will occur at
# the beginning of a block.
admin_email = b'oo@bar.com'
admin_block = PKCS_7_pad(b'admin', 16)
# Appending the padded admin string to the end of the email
admin_email += admin_block
admin_ctext = encrypt_profile(admin_email.decode(), key)
# The ciphertext of admin padded to the block size is the second block
admin_suffix = admin_ctext[16:32]
# Forging a new valid ciphertext by appending the admin suffix to the prefix
forged_profile_ctext = prefix + admin_suffix
# Decrypting the forged profile to show that it does indeed have the role admin
forged_profile = decrypt_profile(forged_profile_ctext, key)
for k in forged_profile.keys():
print(f'{k}: {forged_profile[k].decode()}')
|
11db707184923941bad481e3b14aa2b4d1d9dd32 | Thilagaa22/python-codes | /33.py | 79 | 3.5625 | 4 | a = int()
count = 0
for i in a:
if (i == ""):
count +=1
print(count)
|
d9f89bb79d0e41d2ef7776f47297d00c872105eb | tonyxiahua/CIS-40-Python | /Labs/Lab2.py | 2,879 | 4.53125 | 5 | '''
1. Write a function named powers that has one parameter named num. This function should always produce 11 lines of output, one for the parameter raised to the 0th power through one for the parameter raised to the 10th power.
Show both your function definition and three calls of the function, along with the output from those calls. Here are my three calls along with their output.
>>> powers(2)
1
2
4
8
16
32
64
128
256
512
1024
>>> powers(3)
1
3
9
27
81
243
729
2187
6561
19683
59049
>>> powers(10)
1
10
100
1000
10000
100000
1000000
10000000
100000000
1000000000
10000000000
>>>
2. Write a function named palindrome that has five parameters, named l1, l2, l3, l4, and l5. This function should be called with five single-char string arguments. palindrome should produce two lines of output, one of the parameters in order from left to right, and one of the parameters in order from right to left, so that a quick visual inspection will reveal whether the parameter is a palindrome or not. (A palindrome is a word that is spelled the same forwards as backwards.)
Show both your function definition and three calls of the function, along with the output from those calls. Here are my three calls along with their output.
>>> palindrome('l','e','v','e','l')
level
level
>>> palindrome('r','e','f','e','r')
refer
refer
>>> palindrome('s','y','r','u','p')
syrup
purys
>>>
3. Write a function named miles_converter that has one parameter, named miles. This function should produce one line of output, showing the number of yards, feet, and inches represented by miles.
Show both your function definition and one call of the function, along with the output from that call. Here is my one call along with its output.
>>> miles_converter(3.4)
3.4 miles = 5984.0 yards, 17952.0 feet, 215424.0 inches
>>>
'''
#Question 1
def powers(num):
print(num**0)
print(num**1)
print(num**2)
print(num**3)
print(num**4)
print(num**5)
print(num**6)
print(num**7)
print(num**8)
print(num**9)
print(num**10)
powers(4)
powers(5)
powers(6)
#Output 1
'''
1
4
16
64
256
1024
4096
16384
65536
262144
1048576
1
5
25
125
625
3125
15625
78125
390625
1953125
9765625
1
6
36
216
1296
7776
46656
279936
1679616
10077696
60466176
'''
#Question 2
def palindrome(l1,l2,l3,l4,l5):
print(l1+l2+l3+l4+l5)
print(l5+l4+l3+l2+l1)
palindrome('h','a','p','p','y')
palindrome('r','o','g','o','r')
palindrome('l','e','b','e','l')
#Output 2
'''
happy
yppah
rogor
rogor
lebel
lebel
'''
#Question 3
def miles_converter(miles):
yards = 1760 * miles
feet = 5280 * miles
inches = 63360 * miles
print (miles,"miles =",yards,"yards,",feet,"feet,",inches,"inches")
miles_converter(3.2)
miles_converter(4.8)
miles_converter(9.6)
#Output 3
'''
3.2 miles = 5632.0 yards, 16896.0 feet, 202752.0 inches
4.8 miles = 8448.0 yards, 25344.0 feet, 304128.0 inches
9.6 miles = 16896.0 yards, 50688.0 feet, 608256.0 inches
''' |
4505f3fe72193464c4fe2e0e5374b5a9c41d9d44 | cqq03/edu_python | /data04/클래스만들기/트럭.py | 578 | 3.859375 | 4 | class Truck:
#클래스: 멤버변수(인스턴스변수)+멤버함수
weight = None
company = None
def move(self):
print(self.weight, '의 짐을 실어나르다.')
def own(self):
print(self.company, '회사 소속의 트럭입니다.')
def __str__(self):
return str(self.weight) + ', ' + str(self.company)
if __name__ == '__main__':
truck1 = Truck() #객체 생성
truck1.weight = '1톤'
truck1.company = 'mega'
print(truck1)
print(truck1.weight)
print(truck1.company)
truck1.own()
truck1.move() |
fea2a2c33607e5efa1372f2addd7fceaed4dd529 | ehbaker/WXmunge | /LVL1.py | 29,526 | 3.546875 | 4 | '''
LVL1 WX Cleaning Functions
'''
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def remove_malfunctioning_sensor_data(dat, bad_sensor_dates_dat):
'''
Function to set bad sensor data to NAN, during specified timeframes. Returns dataframe with NANs in place, and switched values, as indicated with "switch_label"
dat: dataframe containing data that you are editing. Index MUST BE in local time.
bad_sensor_dates_dat: dataframe containing sensor name, start/end date of bad sensor data
Example table format for bad_sensor_dates_dat:
Sensor Start_Date End_Date Action Correct_Label Location
------------------------------------------------------------------------------------
TAspirated2 4/25/2014 6:45 9/4/2014 9:00 switch_label TPassive2 Wolverine990
Tpassive1 5/7/2013 2:15 11/6/2013 8:00 bad NAN Wolverine990
'''
for xx in bad_sensor_dates_dat.index:
#If sensor data is bad, set to NAN
if bad_sensor_dates_dat.loc[xx,'Action']=='bad':
Start_Date=bad_sensor_dates_dat.loc[xx, 'Start_Date']
End_Date=bad_sensor_dates_dat.loc[xx, 'End_Date']
if End_Date=='end':
End_Date=dat.index[-1] #set end-date to the last available in the data
Sensor=bad_sensor_dates_dat.loc[xx, 'Sensor']
print(str(Start_Date) + " " + str(End_Date) + " " + Sensor)
dat.loc[Start_Date:End_Date, Sensor]=np.nan
#If sensor is mislabeled, switch label for indicated time period
elif bad_sensor_dates_dat.loc[xx,'Action']=='switch_label':
Start_Date=bad_sensor_dates_dat.loc[xx, 'Start_Date']
End_Date=bad_sensor_dates_dat.loc[xx, 'End_Date']
Sensor=bad_sensor_dates_dat.loc[xx, 'Sensor']
Correct_Label=bad_sensor_dates_dat.loc[xx, 'Correct_Label']
dat.loc[Start_Date:End_Date, Correct_Label]=dat.loc[Start_Date:End_Date, Sensor] #put data in correctly labeled column
dat.loc[Start_Date:End_Date, Sensor]=np.nan #change the original location to NAN (no data was collected from this sensor)
elif bad_sensor_dates_dat.loc[xx,'Action']=='correct':
Start_Date=bad_sensor_dates_dat.loc[xx, 'Start_Date']
End_Date=bad_sensor_dates_dat.loc[xx, 'End_Date']
Sensor=bad_sensor_dates_dat.loc[xx, 'Sensor']
Value_to_add=bad_sensor_dates_dat.loc[xx, 'Correct_Label']
print("adding "+ str(Value_to_add)+ " to " + Sensor + " at " + str(Start_Date))
if End_Date=='end':
dat.loc[Start_Date:, Sensor]=dat.loc[Start_Date:, Sensor]+ Value_to_add
else:
dat.loc[Start_Date:End_Date, Sensor]=dat.loc[Start_Date:End_Date, Sensor]+ Value_to_add
return(dat)
def remove_error_temperature_values(temps, low_temp_cutoff, high_temp_cutoff):
'''
temps: pandas series of temperatures (NANs OK)
low_temp_cutoff: numeric value of low cutoff temperature
high_temp_cutoff: numeric value of high temperature cutoff
'''
temps.loc[temps>high_temp_cutoff]=np.nan
temps.loc[temps<low_temp_cutoff]=np.nan
return(temps)
def remove_error_precip_values_old(precip_cumulative, obvious_error_precip_cutoff, precip_high_cutoff, precip_drain_cutoff):
'''
precip_cumulative: pandas series of cumulative precip values; index must be a date-time
obvious_error_precip_cutoff..: number, giving value that for a 15 minute timestep is obviously an error (unlikely to rain 0.3m in 15 min)
precip_high_cutoff:
precip_drain_cutoff: negative number giving value above which a negative 15 min change is related to station maintenance draining
'''
#The order of the steps here is very important; as soon as derivative is created and re-summed, loose info on sensor malfunctions
precip_edit=precip_cumulative.copy() #create copy, to avoid inadvertently editing original pandas series
#Step 1 : use incremental precip to set sensor malfunction jumps to NAN in CUMULATIVE timeseres
dPrecip=precip_edit -precip_edit.shift(1) #create incremental precip timeseries
for ii in range(0, len(dPrecip)):
if abs(dPrecip[ii])>obvious_error_precip_cutoff:
precip_edit[ii]=np.nan
#Step2: remove remaining outliers using one-day (96 samples) median filter
rolling_median=precip_edit.rolling(96, center=True).median().fillna(method='ffill').fillna(method='bfill')
difference=np.abs(precip_edit - rolling_median)
threshold=0.2 #threshold for difference between median and the given value
outlier_idx=difference>threshold
precip_edit[outlier_idx]=np.nan
#Step3 - remove NANs in cumulative series output by instruments
precip_edit=precip_edit.interpolate(method='linear', limit=96) #interpolate for gaps < 1 day
#Step4 -recalculate incremental precip, set values outside expected range to 0
dPrecip=precip_edit -precip_edit.shift(1) #incremental precip
dPrecip.loc[dPrecip>obvious_error_precip_cutoff]=0
dPrecip.loc[(dPrecip>precip_high_cutoff) & (dPrecip.index.month>=8) & (dPrecip.index.month<=11)]=0 #set precip refills to 0
dPrecip.loc[dPrecip<precip_drain_cutoff]=0 #set precip drains to 0
new_precip_cumulative=dPrecip.cumsum()
new_precip_cumulative[0]=0 #set beginning equal to 0, not NAN as is created with the cumulative sum
return(new_precip_cumulative)
#def precip_remove_drain_and_fill(precip_cumulative, obvious_error_precip_cutoff):
# precip_edit=precip_cumulative.copy()
# dPrecip=precip_edit -precip_edit.shift(1) #create incremental precip timeseries
#
# #Set locations where sum of 3 sequential values > the precip refill error limit to 0 (some refills span several timesteps; generally under an hour however)
# counter=0
# for ii in range(2, len(dPrecip)):
# if counter>0:
# counter=counter-1
# continue #skip iteration of loop if dPrecip already modified below
# #If jump in initial precip series is over the cutoff
# if abs(precip_edit[ii]-precip_edit[ii-2])>obvious_error_precip_cutoff:
# print("PROBLEM!" + str(dPrecip.index.date[ii-2]))
# #Find end of the filling event; when > 20 incremental values in a row are less than 2 cm
# for xx in range(ii, ii+30):
# if (dPrecip[xx: xx+20]<(2)).all():
# dPrecip[ii-2:xx+1]=0
# print("Gage Drain/ Fill Event on " + str(dPrecip.index.date[ii-2]))
# print("found the end - removed at " + str(dPrecip.index[ii-2])+ ":" + "until" + str(dPrecip.index[xx]))
# break #continue to outer loop
# else:
# print('continuing')
# counter=counter+1
# continue
#
# new_cumulative= calculate_cumulative(cumulative_vals_orig=precip_edit, incremental_vals=dPrecip)
# return(new_cumulative)
def precip_remove_drain_and_fill(precip_cumulative, obvious_error_precip_cutoff, n_window):
'''
function to remove drain/ fill events from cumulative precipitation record. Returns cumulative timeseries of precip w/ NANs as placed in original
precip_cumulative: pandas series of cumulative precipitation
obvious_error_precip_cutoff: cutoff for sum of 3 consecutive values, if over, represents a drain/ fill event
n_window: size of window
'''
filled=precip_cumulative.interpolate()
dPrecip=filled-filled.shift(1)
#rolling_sum=dPrecip.abs().rolling(n_window, center=True).sum()
rolling_sum=abs(dPrecip.rolling(n_window, center=True).sum())
error_center=rolling_sum>obvious_error_precip_cutoff
for xx in range(n_window*-1,n_window+1):
#print("fixing errors at error + "+ str(xx))
select_boolean_ser=error_center.shift(xx)
select_boolean_ser[0:n_window]=False #set first and last xx vals to false (otherwise NAN)
select_boolean_ser[n_window*-1:]=False
dPrecip[select_boolean_ser]=0 #set incremental precip @ these timesteps surrounding problem to 0 as well
new_cumulative=calculate_cumulative(precip_cumulative, dPrecip)
return(new_cumulative)
def precip_remove_daily_outliers(precip_cumulative, n=96):
precip_edit=precip_cumulative.copy()
#Step2: remove remaining outliers using one-day (96 samples for 15 min data) median filter
rolling_median=precip_edit.rolling(n, center=True).median().fillna(method='ffill').fillna(method='bfill')
difference=np.abs(precip_edit - rolling_median)
threshold=0.2 #threshold for difference between median and the given value
outlier_idx=difference>threshold
precip_edit[outlier_idx]=np.nan
return(precip_edit)
def precip_interpolate_gaps_under1day(precip_cumulative, n=96):
#Step3 - remove NANs in cumulative series output by instruments
precip_edit=precip_cumulative.copy()
precip_edit=precip_edit.interpolate(method='linear', limit=96)
return(precip_edit)
def precip_remove_maintenance_noise(precip_cumulative, obvious_error_precip_cutoff, noise_cutoff):
'''
returns cumulative precip w/o fill and drain events
'''
precip_edit=precip_cumulative.copy()
dPrecip=precip_edit -precip_edit.shift(1) #incremental precip
dPrecip.loc[abs(dPrecip)>obvious_error_precip_cutoff]=0
dPrecip.loc[(dPrecip>noise_cutoff) & (dPrecip.index.month>=8) & (dPrecip.index.month<=11)]=0 #set precip refills to 0 in fall months
dPrecip.loc[abs(dPrecip)>noise_cutoff]=0 #set precip drains to 0
#Re-sum cumulative timeseries
new_cumulative=calculate_cumulative(precip_cumulative, dPrecip)
return(new_cumulative)
def precip_remove_high_frequency_noiseNayak2010(precip_cumulative_og, noise, bucket_fill_drain_cutoff, n_forward_noise_free=20):
'''
precip_cumulative_og= pandas series of cumulative precipitation
noise: numeric; limit for incremental change
bucket_fill_drain_cutoff= numeric; limit for change that indicates a bucket refill or drain, performed during station maintenance
'''
precip_cumulative=precip_cumulative_og.copy()
precip_cumulative=precip_cumulative.reindex() #reset index to integers from time
precip_incremental=precip_cumulative-precip_cumulative.shift(1)
flag='good' #create initial value for flag
counter=0 #used to skip over iterations in outer loop which have already been edited by inner
for ii in range(1, len(precip_incremental)):
start_noise=np.nan
end_noise=np.nan
if flag=='skip_iteration': #this skips a single iteration if a single value has been edited
#print(' skipping iteration' + str(precip_incremental.index[ii]))
flag='good' #reset flag
continue
if counter>0: #this part skips as many iterations as have been edited below
counter=counter-1
#print("SKIPPING " + str(precip_incremental.index[ii]))
continue
if abs(precip_incremental[ii])>noise:
start_noise=ii-1 #mark value before error
#print("noise starts at "+ str(precip_incremental.index[ii])+ " ; " + str(ii))
for jj in range(ii, len(precip_incremental)-n_forward_noise_free):
#print(jj)
newslice=precip_incremental[jj+1:jj+n_forward_noise_free+1] #slice of N values forward from location noise identified
if (abs(newslice)>noise).any():
continue #additional noise is present in new slice; get new slice with subsequent loop iteration
if(abs(newslice)<noise).all():
end_noise=jj+1 #jj is still a noisy value that should be replaced
if ii==jj:
#print(" single value removed at " + str(precip_incremental.index[jj]))
Dy=precip_cumulative[end_noise]-precip_cumulative[start_noise]
precip_incremental[jj]=Dy/2
precip_incremental[jj+1]=Dy/2#[jj:jj+2] selects 2 values (jj and jj+1) only
flag='skip_iteration' #need to skip next iteration of outer loop (altered precip[ii+1])
break #continue outer loop
if abs(precip_cumulative[end_noise]-precip_cumulative[start_noise])<bucket_fill_drain_cutoff: #if issue is noise
precip_incremental[start_noise+1: end_noise]=np.nan #this does not change val @ end_noise
precip_cumulative[start_noise+1: end_noise]=np.nan
dY=precip_cumulative[end_noise] - precip_cumulative[start_noise]
dx=(end_noise)-(start_noise+1)+1
precip_incremental[start_noise+1: end_noise+1]=dY/dx #linear interpolation
#print(" interpolated noise at locations " + str(precip_incremental.index[start_noise+1]) + ":" +str(precip_incremental.index[end_noise]))
counter=len(precip_incremental[start_noise+1:end_noise+1])
if abs(precip_cumulative[end_noise]-precip_cumulative[start_noise])>bucket_fill_drain_cutoff: # if issue is gage maintenance
precip_incremental[start_noise+1:end_noise+1] =0 #no incremental precip occurs during bucket drain or refill
#print(" removed gage maintenance at " + str(precip_incremental.index[start_noise+1]) + ":" +str(precip_incremental.index[end_noise]))
break #this simple exits the inner loop, continuing the outer
#print("recalculating cumulative")
new_cumulative=calculate_cumulative(cumulative_vals_orig=precip_cumulative_og, incremental_vals=precip_incremental)
new_cumulative.reindex_like(precip_cumulative_og) #reset index to time
return(new_cumulative)
def hampel_old_loop(x,k, t0=3):
'''adapted from hampel function in R package pracma
x= 1-d numpy array of numbers to be filtered
k= number of items in window/2 (# forward and backward wanted to capture in median filter)
t0= number of standard deviations to use; 3 is default
'''
n = len(x)
y = x #y is the corrected series
L = 1.4826
for i in range((k + 1),(n - k)):
if np.isnan(x[(i - k):(i + k+1)]).all(): #the +1 is neccessary for Python indexing (excludes last value k if not present)
continue
x0 = np.nanmedian(x[(i - k):(i + k+1)]) #median
S0 = L * np.nanmedian(np.abs(x[(i - k):(i + k+1)] - x0))
if (np.abs(x[i] - x0) > t0 * S0):
y[i] = x0
return(y)
def hampel(vals_orig, k=7, t0=3):
'''
vals: pandas series of values from which to remove outliers
k: size of window (including the sample; 7 is equal to 3 on either side of value, which is the default in Matlab's implmentation)
t0= number of median absolute deviations before replacing; default = 3
'''
#Make copy so original not edited
vals=vals_orig.copy()
#Hampel Filter
L= 1.4826
rolling_median=vals.rolling(k, center=True).median()
difference=np.abs(rolling_median-vals)
median_abs_deviation=difference.rolling(k, center=True).median()
threshold= t0 *L * median_abs_deviation
outlier_idx=difference>threshold
vals[outlier_idx]=rolling_median
return(vals)
def basic_median_outlier_strip(vals_orig, k, threshold, min_n_for_val=3):
'''
vals: pandas series of initial cumulative values
k: window size
threshold: cutoff threshold for values to strip
RETURNS: series of instantaneous change values
'''
vals=vals_orig.copy()
rolling_median=vals.rolling(k, min_periods=min_n_for_val, center=True).median() #center=True keeps label on center value
difference=np.abs(rolling_median-vals)
outlier_idx=difference>threshold
vals[outlier_idx]=rolling_median #set incremental change at index where cumulative is out of range to 0
return(vals)
def inner_precip_smoothing_func_Nayak2010(precip):
'''
precip smoothing routine from Nayak 2010 thesis:
First 3 records must be >0: check progressively to ensure
translated from Nayak 2010 thesis; slightly different than Shad's implementation in Matlab.
Should be run both forward and backwards to smooth data uniformly
precip: 1-d ndarray of numeric, incremental (non-cumulative) precipitation values
'''
precip=precip.copy() #avoid modifying original series; make a copy
precip=pd.Series(precip)
if precip[0]<0:
precip[1]=precip[1]+precip[0]
precip[0]=0 #force initial value to 0, if increment is negative
if precip[1]<0:
if np.nansum(precip[0:3])<0:
precip[2]=(np.nansum(precip[0:3]))
precip[0]=0
precip[1]=0
else:
precip[0]=np.nansum(precip[0:3])/3
precip[1]=precip[0]
precip[2]=precip[0]
precip[0:3]=precip[0:3] #set values in precip series to the values as edited above; necceary for smoothing
#Smoothing Loop
for ii in precip.index[3:-3]:
#if all NAN in the 5-sample window, skip to next iteration
if precip.iloc[ii-2:ii+3].isnull().all():
continue
if precip[ii]<0:
check=np.nansum(precip.iloc[ii-2:ii+3])
if check>=0: #if positive, 5 window values are set to mean of all 5
precip.iloc[ii-2:ii+3]=np.nanmean(precip.iloc[ii-2:ii+3])
else:
precip.iloc[ii+2]=np.nansum(precip.iloc[ii-2:ii+3])
precip.iloc[ii-2:ii+2]=0
else:
precip[ii]=precip[ii]
return(precip)
def smooth_precip_Nayak2010(precip_cumulative):
'''
Routine for smoothing precipitation data from Nayak 2010 thesis/ 2008 paper.
Returns dataframe with smoothed precip column (overwrites existing column)
-relies on inner_precip_smoothing_func_Nayak2010, as included above in this module
-----
precip_cumulative: pandas series of data to smooth
'''
precip=precip_cumulative.copy() #copy, to avoid inadvertently altering original data
precip=precip.interpolate() #fill nans (needed to preserve increases in precip during times where no data was recorded for some reason)
precip_incr=precip-precip.shift(1)
#precip_incr[0]=0
#precip_incr[-1]=0
#Smooth data in forward direction
print(" smoothing data in forward direction; may take a minute")
smooth_forward=inner_precip_smoothing_func_Nayak2010(precip_incr.values)
#Smooth Data in backwards direction
reverse_sorted_data=precip_incr.copy().sort_index(ascending=False).values
print(" smoothing data in reverse direction; may take a minute")
smooth_backwards=inner_precip_smoothing_func_Nayak2010(reverse_sorted_data)
smooth_backwards=smooth_backwards[::-1] #sort forwards again, so in the correct order to store in dataframe
#Average
smooth_forward.index=precip_cumulative.index #Reindex in order to add back to original dataframe
smooth_backwards.index=precip_cumulative.index #Reindex in order to add back to original dataframe
dat2=pd.DataFrame()
dat2['smooth_forward']=smooth_forward #re-combine into single dataframe
dat2['smooth_backwards']=smooth_backwards
dat2['avg']=dat2[['smooth_forward', 'smooth_backwards']].mean(axis=1, skipna=False)
#If first 3 values <0, set to 0. Same with end and last incremental 3 values.
for ii in range(-3,0):
if dat2.ix[ii, 'avg']<0:
dat2.ix[ii, 'avg']=0
for ii in range(0,3):
if dat2.ix[ii, 'avg']<0:
dat2.ix[ii, 'avg']=0
#New smooth precip data
smooth_incr_precip=dat2['avg'] #overwrite old precip column with new smoothed values
#Re-sum cumulative timeseries
new_cumulative=calculate_cumulative(cumulative_vals_orig=precip_cumulative, incremental_vals=smooth_incr_precip)
return(new_cumulative)
#def smooth_precip_Nayak2010_broken(precip_cumulative):
# '''
# Routine for smoothing precipitation data from Nayak 2010 thesis/ 2008 paper.
# Returns dataframe with smoothed precip column (overwrites existing column)
# -relies on inner_precip_smoothing_func_Nayak2010, as included above in this module
# -----
# precip_cumulative: pandas series of data to smooth
# '''
#
# precip_copy=precip_cumulative.copy() #copy, to avoid inadvertently altering original data
# precip_incr=precip_copy-precip_copy.shift(1)
# #precip_incr[0]=0 #set first and last values to 0
# #precip_incr[-1]=0
# #Smooth data in forward direction
# print(" smoothing data in forward direction; may take a minute")
# smooth_forward=inner_precip_smoothing_func_Nayak2010(precip_incr.values)
# #Smooth Data in backwards direction
# reverse_sorted_data=precip_incr.copy().sort_index(ascending=False).values
# print(" smoothing data in reverse direction; may take a minute")
# smooth_backwards=inner_precip_smoothing_func_Nayak2010(reverse_sorted_data)
# smooth_backwards=smooth_backwards[::-1] #sort forwards again, so in the correct order to store in dataframe
#
# #Average
# smooth_forward.index=precip_cumulative.index #Reindex in order to add back to original dataframe
# smooth_backwards.index=precip_cumulative.index #Reindex in order to add back to original dataframe
#
# dat2=pd.DataFrame()
# dat2['smooth_forward']=smooth_forward #re-combine into single dataframe
# dat2['smooth_backwards']=smooth_backwards
# dat2['avg']=dat2[['smooth_forward', 'smooth_backwards']].mean(axis=1)
#
# #If first 3 values <0, set to 0. Same with end and last incremental 3 values.
# for ii in range(-3,0):
# if dat2.ix[ii, 'avg']<0:
# dat2.ix[ii, 'avg']=0
# for ii in range(0,3):
# if dat2.ix[ii, 'avg']<0:
# dat2.ix[ii, 'avg']=0
#
# #New smooth precip data
# #smooth_incr_precip=dat2['avg'] #overwrite old precip column with new smoothed values
#
# #Re-sum cumulative timeseries
# #new_cumulative=calculate_cumulative(cumulative_vals_orig=precip_cumulative, incremental_vals=smooth_incr_precip)
#
# return(smooth_backwards)
def rename_pandas_columns_for_plotting(data_o, desired_columns, append_text):
'''
Function that takes dataframe, subsets to desired columns, and renames those columns as indicated.
For plotting multiple iterations of the same data in a single plot, but with different labels.
data: dataframe
desired_columns: list of what columns the text should be appended to
append_text: text to append to the selected columns
'''
data=data_o.copy()
append_text= append_text
df=data[desired_columns].copy()
df=df.add_suffix(append_text)
return(df)
def calculate_cumulative_newVersion_bad(cumulative_vals_orig, incremental_vals):
'''
function to calculate cumulative timeseries from two things: an input (edited) incremental series, and the original cumulative series.
'''
#Original values in cumulative series
cumulative_vals_old=cumulative_vals_orig.copy()
#Save original incremental values (for NAN locations)
incremental_vals_orig=incremental_vals.copy()
incremental_vals[incremental_vals.isnull()]=0
#Calculate cumulative sum of incremental values
new_cumulative=incremental_vals.cumsum()
#Adjust so begins as same absolute value as input
if not np.isnan(cumulative_vals_old[0]):
start_value=cumulative_vals_old[0]
new_cumulative = new_cumulative + start_value
new_cumulative[0]=cumulative_vals_old[0] #needed, as first value of incremental series is always a NAN
#If data begins with NANs, must adjust based on first valid value, not first value
else:
start_data_index=cumulative_vals_old.first_valid_index()
start_value=cumulative_vals_old[start_data_index]
new_cumulative=new_cumulative+start_value
new_cumulative[incremental_vals_orig.isnull()]=np.nan #replace original NANs
return(new_cumulative)
def calculate_cumulative_old_nanProbs(cumulative_vals_orig, incremental_vals):
'''
function to calculate cumulative timeseries from two things: an input (edited) incremental series, and the original cumulative series.
'''
#Original values in cumulative series
cumulative_vals_old=cumulative_vals_orig.copy()
#Calculate cumulative sum of incremental values
new_cumulative=incremental_vals.cumsum()
#Adjust so begins as same absolute value as input
if not np.isnan(cumulative_vals_old[0]):
if cumulative_vals_orig.isnull().any():
print("STOP! Series contains NANs, which will result in unintended jumps in cumulative timeseries!")
print("NANs at " +str(cumulative_vals_old.index[cumulative_vals_old.isnull()]))
start_value=cumulative_vals_old[0]
new_cumulative = new_cumulative + start_value
new_cumulative[0]=cumulative_vals_old[0] #needed, as first value of incremental series is a NAN
#If data begins with NANs, must adjust based on first valid value, not first value
else:
start_data_index=cumulative_vals_old.first_valid_index()
start_value=cumulative_vals_old[start_data_index]
new_cumulative=new_cumulative+start_value
return(new_cumulative)
def calculate_cumulative(cumulative_vals_orig, incremental_vals):
'''
function to calculate cumulative timeseries from two things: an input (edited) incremental series, and the original cumulative series.
-interpolates any missing values, and re-adds those back to the timeseries at the end
'''
#Original values in cumulative series
cumulative_vals=cumulative_vals_orig.copy()
#store location of NANs in original timeseries
nan_locations=cumulative_vals.isnull()
#Calculate cumulative sum of incremental values
new_cumulative=incremental_vals.cumsum()
#Adjust so begins as same absolute value as input
if not np.isnan(cumulative_vals[0]):
start_value=cumulative_vals[0]
new_cumulative = new_cumulative + start_value
new_cumulative[0]=cumulative_vals[0] #needed, as first value of incremental series is a NAN
#If data begins with NANs, must adjust based on first valid value, not first value
else:
start_data_index=cumulative_vals.first_valid_index()
start_value=cumulative_vals[start_data_index]
new_cumulative=new_cumulative+start_value
#put NANs back in cumulative timeseries
new_cumulative[nan_locations]=pd.np.nan
return(new_cumulative)
def plot_comparrison(df_old, df_new, data_col_name, label_old='original', label_new='new'):
ax=df_old[data_col_name].plot(label=label_old, title=df_old[data_col_name].name, color='red')
df_new[data_col_name].plot(color='blue', ax=ax, label=label_new)
plt.legend()
#def calculate_cumulative(cumulative_vals_orig, incremental_vals):
def vector_average_wind_direction(WS, WD):
'''
Calculate vector-average wind direction from wind direction (0-360) and wind speed.
WS - wind speed in m/s
WD - vector of wind direction in degrees (0-360)
Should only be used if instrument not already recording vector-average wind direction
Output is a single number - vector averagae wind direction during the period of input data
'''
#Calculate Vector Mean Wind Direction
WS=WS.astype(np.float64)
WD=WD.astype(np.float64)
V_east = np.mean(WS * np.sin(WD * (np.pi/180)))
V_north = np.mean(WS * np.cos(WD * (np.pi/180)))
mean_WD = np.arctan2(V_east, V_north) * (180/np.pi)
#Translate output range from -180 to +180 to 0-360.
if mean_WD<0:
mean_WD=mean_WD+360
return(mean_WD)
def vector_average_wind_direction_individual_timestep(WS, WD):
'''
Calculate vector-average wind direction from wind direction (0-360) and wind speed.
WS - wind speed in m/s
WD - vector of wind direction in degrees (0-360)
Should only be used if instrument not already recording vector-average wind direction
Output is a single number - vector averagae wind direction during the period of input data
'''
#Calculate Vector Mean Wind Direction
WS=WS.astype(np.float64)
WD=WD.astype(np.float64)
V_east = WS * np.sin(WD * (np.pi/180))
V_north = WS * np.cos(WD * (np.pi/180))
mean_WD = np.arctan2(V_east, V_north) * (180/np.pi)
#Translate output range from -180 to +180 to 0-360.
mean_WD[mean_WD<0]=mean_WD[mean_WD<0]+360
return(mean_WD)
|
dd00c8b9af5e888b729c73c36526977d389712d2 | woojay/100-days-of-code | /46/game_of_life.py | 9,087 | 3.890625 | 4 | '''
Game of Life CLI version
by wp
6/13/18
Objective:
You'll implement Conway's Game of Life (https://en.wikipedia.org/wiki/Conway's_Game_of_Life) as a CLI tool.
Criteria:
Conway's Game of Life is displayed in the terminal.
Conway's Game of Life plays indefinitely until a user terminates.
Users may pick a number of starting states(seeds) or enter their own.
Users may define the appearance of live and dead cells.
Instruction:
- Setup
0. '(sudo) pip install curses' if needed
1. 'python game_of_life.py' in either python 3.6.4 or 2.7.14 (linux only)
- Game Play
0. I used pyenv to test py 3.6.4 and py 2.7.14 environements, FYI
1. Enter a single character to represent a live cell. Any alpha-numeric is great.
2. Enter a single character to represent a dead cell. '.' works well.
3. Highly recommend to enter '0' to select manually. Selecting between 1-9 is highly likely to all die in the
first round.
4. 10x40 grid will show up, which is the 'universe.' You can move around the position w/ a, d, w, and x keys.
5. Once located, enter 's' to place a seed. Do as many as you like, and enter 'q' to exit the set up mode.
6. Once exited, the each round is run after a single keyboard input other than 'x'. Each key press will represent
a single round.
7. If all the cells die, 'game over' message will show, but will not exit unless a single 'x' is entered.
8. 'x' will always exit the simulation rounds.
9. In case of a 'still life,' no special message will show even though each round will return a same outcome.
10. Hope this makes sense to you. Thank you so much.
'''
import curses
import curses.ascii
import time
import random
import logging
# User selectable live / dead cell symbols
live = 'O'
dead = '.'
# global screen size of cell universe
height=10
width=40
# game space (universe for the cell population
universe = [[0 for y in range(width)] for x in range(height)]
next_universe = [[0 for y in range(width)] for x in range(height)]
def main(stdscr):
global live, dead
logging.basicConfig(filename='log.log', level=logging.DEBUG)
curses.cbreak()
curses.noecho()
stdscr.addstr(0, 0, '---------------------------')
stdscr.addstr(1, 0, ' Game of life')
stdscr.addstr(2, 0, '---------------------------')
# Users may define the live and dead cells
get_symbol(stdscr, 'live', 3)
get_symbol(stdscr, 'dead', 5)
init_universe(universe)
# Users may pick a number of seeds or their own
get_seeds(stdscr)
stdscr.refresh()
time.sleep(1)
# GOL is displayed on the terminal
while True:
stdscr.clear()
show_universe(stdscr)
stdscr.addstr(height+2, 0, 'Enter x to exit. Enter any other key to continue to next round')
# GOL goes on
propagate(stdscr)
key = chr(stdscr.getch())
if (key == 'x'): # 'x' exits the game
exit()
else:
# elif (key == curses.ascii.SP): # next round
continue
def propagate(stdscr):
global universe, next_universe
cell_count = 0
init_universe(next_universe)
for i in range(height):
for j in range(width):
# stdscr.addstr(i, j, universe[i][j])
# Count number of neighbors
neighbors = count_neighbors(universe, i, j, stdscr)
# If live, and;
if universe[i][j] == live:
# Starvation
if neighbors < 2:
next_universe[i][j] = dead
# Move on but stay the same
elif neighbors == 2 or neighbors == 3:
next_universe[i][j] = live
cell_count += 1
# Overpopulation
elif neighbors > 3:
next_universe[i][j] = dead
logging.debug('{}->{}'.format(universe[i][j], next_universe[i][j]))
# if Dead
elif universe[i][j] == dead:
# Reproduction
if neighbors == 3:
next_universe[i][j] = live
cell_count += 1
logging.debug('{}->{}'.format(universe[i][j], next_universe[i][j]))
# copy over
for i in range(height):
for j in range(width):
universe[i][j] = next_universe[i][j]
if cell_count == 0:
stdscr.addstr(17, 0, 'game over')
def count_neighbors(univ, y, x, stdscr):
global height, width
# Y Minimum
if y <= 1:
y_min = 0
else:
y_min = y - 1
# Y Maximum
if y >= height - 2:
y_max = height - 1
else:
y_max = y + 1
# X Minimum
if x <= 1:
x_min = 0
else:
x_min = x - 1
# X Maximum
if x >= width - 2:
x_max = width - 1
else:
x_max = x + 1
neighbor_count = 0
for i in range(y_min, y_max+1):
for j in range(x_min, x_max+1):
if i == y and j == x:
continue
if univ[i][j] == live:
neighbor_count += 1
# if univ[i][j] == live:
# neighbor_count -= 1
# stdscr.addstr(19, 0, str(neighbor_count))
if neighbor_count:
message = '@ {}-{}-{}:{}-{}-{} count {}'.format(y_min, y, y_max, x_min, x, x_max, neighbor_count)
logging.debug(message)
return neighbor_count
def get_manual_seeds(stdscr):
global height, width
show_universe(stdscr)
stdscr.addstr(height + 2, 0, 'Use keyboard to move. Enter s to place a seed. Enter q to exit. ')
stdscr.addstr(height + 3, 0, 'a / d for left / right, w / x for up / down.')
x = 0
y = 0
key = ''
while key != 'q':
key = chr(stdscr.getch())
if key == 'q': # Finish
stdscr.clear()
return
elif key == 'a': # Left
if x == 0:
x = width - 1
else:
x = x - 1
elif key == 'd': # Right
if x >= width-1:
x = 0
else:
x = x + 1
elif key == 'w': # Up
if y == 0:
y = height - 1
else:
y = y - 1
elif key == 'x': # Down
if y >= height-1:
y = 0
else:
y = y + 1
# curses.setsyx(y, x)
if key == 's': # Place Seed
stdscr.addstr(y, x, live)
stdscr.addstr(y, x, '') # Moves back the cursor after write
universe[y][x] = live
else:
stdscr.addstr(y, x, '')
stdscr.refresh()
def get_seeds(stdscr):
'''
Initial setup for seed placement in the game space (universe)
:param stdscr: screen
'''
stdscr.addstr(7, 0, 'How many seeds would you like to randomly place?')
stdscr.addstr(8, 0, 'Enter a number between 1 and 9 or 0 for manual placement: ')
seeds = stdscr.getch()
stdscr.clear()
if curses.ascii.isdigit(seeds):
stdscr.refresh()
if seeds >= 49 and seeds <= 57:
stdscr.addstr(9, 0, 'Randomly placing {} seeds'.format(seeds-48))
random_seeds(seeds-48)
elif seeds == 48:
stdscr.addstr(9, 0, 'Manual input selected')
get_manual_seeds(stdscr)
else:
stdscr.addstr(9, 0, 'Sorry, wrong input')
exit()
stdscr.clear()
def clear_display(stdscr):
'''
Clears display window
\ '''
height, width = stdscr.getmaxyx()
blankline = ' ' * (width-1)
for line in range(height):
stdscr.addstr(line, 0, blankline)
def init_universe(univ):
'''
Clears universe data for live and dead cells
'''
for i in range(height):
for j in range(width):
univ[i][j] = dead
def random_seeds(seeds):
'''
Adds a few random seeds based on input
:param seeds: number of seeds to add
'''
for seed in range(seeds):
rand_y = random.randint(0, height-1)
rand_x = random.randint(0, width-1)
while (universe[rand_y][rand_x] != dead):
rand_y = random.randint(0, height-1)
rand_x = random.randint(0, width-1)
universe[rand_y][rand_x] = live
def show_universe(stdscr):
'''
Displays the game space (universe)
:param stdscr:
'''
for i in range(height):
for j in range(width):
stdscr.addstr(i, j, universe[i][j])
def get_symbol(stdscr, target, y):
'''
Gets user customized symbols for either live or dead cells for display
:param stdscr: screen
:param target: live or dead cell
:param y: display height for screen
'''
global dead, live
stdscr.addstr(y, 0, 'Enter a symbol for a {} cell: '.format(target))
c = stdscr.getch()
if curses.ascii.isalnum(c):
stdscr.addstr(y+1, 0, chr(c))
if target == 'live':
live = chr(c)
elif target == 'dead':
dead = chr(c)
if __name__ == '__main__':
curses.wrapper(main) |
ef1520b4209a98fa42bd663bfe526368c36f26c3 | zuohd/python-excise | /regexpression/multipleCharacters.py | 675 | 3.796875 | 4 | import re
r'''
(xyz) match "xyz" as the whole part
x? match zero or one x
x* match any number x
x+ match at least one x
x{n} match n number x
x{n,} match at least n number x
x{n,m} match at least n number and max number is m (n<=m)
x|y match x or y
'''
print(re.findall(r"(soderberg)","soderbergberg is soderberg man"))
print(re.findall(r"s?","ssoderbergberg is sssoderberg man"))
print(re.findall(r"s*","ssoderbergberg is sssoderberg man"))
print(re.findall(r"s+","ssoderbergberg is sssoderberg man"))
print(re.findall(r"a{3}","aaaabbaa"))
print(re.findall(r"a{3,}","aaaabbaaa"))
print(re.findall(r"a{3,5}","aaaabbaaa"))
print(re.findall(r"a|A","aaaabbAAA"))
|
4f5027e3f93050d0bb8b538c15be78f472a03e2a | sebnapo/Python | /TP2/championnat.py | 456 | 3.5625 | 4 |
def championnat(N,J,M):
if(N%2 == 0):
N1 = N
else: N1 = N+1
print("Il y aura" + str(N1-1) + "jours de championnat et " + str(N1/2) + " match par jour")
if(M == 1):
if(N%2 == 0): domicile = N1
if(M > 1):
domicile = ((J + M-2)%(N1 - 1)) + 1
deplacement = (((J - M +N1 -1)%(N1 - 1))+1)
if(domicile):
print("Equipe à domicile: " + str(domicile) + "equipe en déplacement: " + str(deplacement))
|
d1ca146064cb498b3e3158ee8e04a7fe0636467d | vasanth8455/python27 | /sample.py | 365 | 3.609375 | 4 | '''
def vasanth(x,y):
return x*y,x+y,x%y
print vasanth(11,20)
#local variable
def get(x=10,y=30):
return x+y,x*y,x%y
print get()
#global variable
x = 'sekhar'
y = 'reddy'
def sam():
global x,y
x=30
return x+y
print sam()
'''
#revers of the string
s=raw_input('Enter your stirng :')
s1=''
for x in s:
s1=x+s1
print s1
|
6dfffea67ad4a7e06ff1a33392314090fba5bed1 | aguscoppe/ejercicios-python | /TP_6_Listas/TP6_EJ12.py | 1,619 | 3.625 | 4 | def leerLista():
n = int(input("Ingrese un número para agregar a la lista o -1 para finalizar: "))
lista = []
while n != -1:
lista.append(n)
n = int(input("Ingrese un número para agregar a la lista o -1 para finalizar: "))
return lista
def calcularProducto(lista):
producto = 1
sumaImpares = 0
for i in range (len(lista)):
if i % 2 == 0:
producto = producto * lista[i]
else:
sumaImpares = sumaImpares + lista[i]
print()
print("Lista leída:", lista)
if sumaImpares == 0:
print("Error: no puede realizarse la división")
else:
print("Producto de pares dividido por suma de impares:", producto / sumaImpares)
def sumarExtremos(lista):
i = 0
j = len(lista) - 1
nuevaLista = []
while i <= j:
if lista[i] != lista[j]:
suma = lista[i] + lista[j]
else:
suma = lista[i]
nuevaLista.append(suma)
j = j - 1
i = i + 1
print("Nueva lista con las sumas de los números en extremos opuestos:", nuevaLista)
def compararLaterales(lista):
nuevaLista = []
for i in range (len(lista)):
if (i + 1) >= len(lista):
if lista[i] == lista[i - 1] and lista[i] == lista[0]:
nuevaLista.append(lista[i])
else:
if lista[i] == lista[i - 1] and lista[i] == lista[i + 1]:
nuevaLista.append(lista[i])
print("Lista con elementos laterales iguales:", nuevaLista)
v = leerLista()
calcularProducto(v)
sumarExtremos(v)
compararLaterales(v) |
11d929178bcde78efaf29a07dbb0fbdbf46507aa | Mayank-141-Shaw/Python-Repo | /Upload/miniMaxSum.py | 543 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 9 12:09:04 2020
@author: MAYANK SHAW
"""
import sys
def miniMaxSum(arr):
ct = 0
maxval,minval,maxsum,minsum = 0,sys.maxsize,0,0
while ct != len(arr):
for i in range(len(arr)):
if i != ct:
maxsum += arr[i]
minsum += arr[i]
if maxsum > maxval :
maxval = maxsum
if minsum < minval:
minval = minsum
ct += 1
maxsum,minsum = 0,0
print(f'{minval} {maxval}')
|
c00ca104df59635b5b6ed81e0f6192cb10019421 | codewithmodi/Python_Projects | /P0002.py | 254 | 4.125 | 4 | name = input("Enter your name ")
age = input("What is your age " + name + "? ")
print(name + " your age is " + age)
# print(age)
if int(age) >= 18:
print("you are valid to Vote")
else:
print("Please comeback in {0} years".format(18 - int(age)))
|
42ecf77e90630734e195eb2025fafeacf0ae5478 | ioannaili/Python-projects | /ergasies/maxsub.py | 735 | 4.1875 | 4 | """
This is a function called maxSequence that takes a list as input and returns the sublist (consecutive items in the list) that has the maximum sum.
Example: maxSequence ([- 2, 1, -3, 4, -1, 2, 1, -5, 4]) returns 6: [4, -1, 2, 1]
"""
def maxSequence(a,size):
max_s = 0
max_e = 0
for i in range(0, size):
max_e = max_e + a[i]
if max_e < 0:
max_e = 0
elif (max_s < max_e):
max_s = max_e
return max_s
a=[]
size =int(input("Enter list length:"))
print("Enter numbers:")
for i in range(size):
data=int(input())
a.append(data)
maxs=maxSequence(a,size)
print(maxs)
|
bcdf24aff9fd94b9e49f14175ede5dd11e78751f | Asr1aan/hw3 | /hw3.py | 2,180 | 3.53125 | 4 | # Salaries
# num_1 = int(input())
# num_2 = int(input())
# num_3 = int(input())
# l = [num_1, num_2, num_3]
# print(max(l) - min(l))
# Boring number
# num = set(input())
# if len(num) == 1:
# print("Boring")
# else:
# print("Interesting")
# Largest Number
# num = int(input())
# lst = []
# while num != 0:
# a = num % 10
# lst.append(a)
# num //= 10
# lst.reverse()
# lst_sorted = lst.copy()
# lst_sorted.sort(reverse = True)
# if lst_sorted == lst:
# print("No")
# else:
# print("Yes")
# Line segment intersection
# a1 = float(input())
# b1 = float(input())
# a2 = float(input())
# b2 = float(input())
# if a1 > b1:
# a1, b1 = b1, a1
# if a2 > b2:
# a2, b2 = b2, a2
# if a2 > a1 and a2 < b1 and b2 > b1:
# print(b1- a2)
# if a2 > a1 and a2 > b1:
# print("0")
# if a2 > a1 and a2 < b1 and b2 > a1 and b2 < b1:
# print(b2 - a2)
# Number of Divisors
# x = int(input())
# n = 0
# for a in range(1,x+1):
# if x % a == 0:
# n += 1
# print(n)
#Quadratic Equation
# from cmath import sqrt
# #bx = -c
# a = float(input())
# b = float(input())
# c = float(input())
# D = b * b - 4 * a * c
# armat = sqrt(D).real
# if a == 0 and b == 0 and c == 0:
# print("Non-quadratic equation")
# print("Infinite solutions")
# if a == 0 and b == 0 and c != 0:
# print("Non-quadratic equation")
# print("No solution")
# if a == 0 and b != 0:
# x = -c / b
# print("Non-quadratic equation")
# print("One solution:", x)
# if a != 0:
# print("Quadratic equation")
# print("Discriminant:", D)
# if int(armat) != 0:
# if (armat // int(armat)) == 1.0:
# x1 = -b + armat / (2 * a)
# x2 = -b - armat / (2 * a)
# print("Two solutions:", x1, x2)
# else:
# print("No solution")
# else:
# print("No solution")
# list1
# lst = ["a", "b", "c", "d"]
# print(lst[0] + lst[1] + lst[2] + lst[3]
#list2
# x = int(input())
# lst = []
# for _ in range(x):
# lst.append(int(input()))
# lst = set(lst)
# lst.remove(min(lst))
# print(min(lst))
|
f55083b2c2a9e36ecccf91c0b08615df739427e6 | DanielCastelo/Manipulacao-de-Strings | /regex.py | 770 | 3.6875 | 4 | import re #re é a biblioteca que lida com expressões regulares
email1 = "Meu número é 9848-3865"
email2 = "o em 99848-3865 fale comigesse é meu número"
email3 = "9948-3865 é o meu celulare"
email4 = "afhshfshf 99845-3596 ajfjhfhsd 48579-2585 ahfhafjhdhfj 85595-8957"
#padrao = "[0-9][0-9][0-9][0-9][-][0-9][0-9][0-9][0-9]"
padrao2 = "[0-9]{4,5}[-]*[0-9]{4}"
#retorno = re.search(padrao2,email2) #metodo serch recebe o padrao procurado e onde ele deve buscar a ocorrência
#print(retorno.group())
retorno = re.findall(padrao2,email4) #metodo findall encontra todas as ocorrencias que se encaixam no padrão, diferente do search que para após encontrar a primeira
#findall retorna em forma de lista
print(retorno) #findall nao necessita do group() |
88ce7043a1bff459c3bdfc504d3ab9acedf040b8 | ithaquaKr/MLBasic | /MLBasic/exercise1.py | 304 | 3.875 | 4 | def evenDigitsNumber(arr):
result = 0
for a in arr:
count = 0
mark = a
while mark > 0:
mark /= 10
count += 1
if count % 2 == 0:
result += 1
return result
arr = [12,345,2,6,7869]
print(evenDigitsNumber(arr))
|
be85aa3aed6add562b5298ecac3c492088ba48fa | mayamessinger/LinguisticDB-database | /dbLoadFiles/sequences.py | 4,163 | 3.5 | 4 |
# -*- coding: utf-8 -*-
"""
@author: Ryan Piersma
"""
from nltk.tokenize import RegexpTokenizer
import os, fnmatch
#Some code from:
#https://stackoverflow.com/questions/15547409/how-to-get-rid-of-punctuation-using-nltk-tokenizer
#data structure for holding sequences:
# Dictionary where key = a word, value = a pair consisting of
# a word that follows it and the number of times that it has
# occurred after that word
def createWordSequences(corpus):
seqDict = {}
startRead = False
tokenizer = RegexpTokenizer(r'\w+')
lastWordLastLine = "dummyword"
for line in corpus.readlines():
if line.find("FOOTNOTES") != -1:
break
if startRead:
tokenized = tokenizer.tokenize(line)
words = [w.lower() for w in tokenized]
#Handle the sequence between last word of one line and first word
#of next line
if len(words) > 0:
firstWordCurLine = words[0]
if not lastWordLastLine == "dummyword":
if lastWordLastLine in seqDict:
if not any(firstWordCurLine in d for d in seqDict[lastWordLastLine]):
seqDict[lastWordLastLine].append({firstWordCurLine : 1})
else:
wordIndex = -1
for d in seqDict[lastWordLastLine]:
if firstWordCurLine in d:
wordIndex = seqDict[lastWordLastLine].index(d)
seqDict[lastWordLastLine][wordIndex][firstWordCurLine] += 1
else:
seqDict[lastWordLastLine] = [{firstWordCurLine : 1}]
#Handle sequences that happen on a single line
for i in range(len(words) - 1):
if words[i] in seqDict:
if not any(words[i+1] in d for d in seqDict[words[i]]):
seqDict[words[i]].append({words[i+1] : 1})
else:
wordIndex = -1
for d in seqDict[words[i]]:
if words[i+1] in d:
wordIndex = seqDict[words[i]].index(d)
seqDict[words[i]][wordIndex][words[i+1]] += 1
else:
seqDict[words[i]] = [{words[i+1] : 1}]
#Store the last word on the line
if (len(words) > 0):
lastWordLastLine = words[len(words) - 1]
if line.find("START OF THE PROJECT GUTENBERG EBOOK"):
startRead = True
#print(seqDict)
return seqDict
#Source for this function: https://stackoverflow.com/questions/13299731/python-need-to-loop-through-directories-looking-for-txt-files
def findFiles (path, filter):
for root, dirs, files in os.walk(path):
for file in fnmatch.filter(files, filter):
yield os.path.join(root, file)
def convertToList(listDict, bookID):
listTuples = []
beforeWord = ""
for key,dictList in listDict.items():
beforeWord = key
for dict in dictList:
for afterWord,timesFound in dict.items():
listTuples.append(tuple([beforeWord, bookID, afterWord, timesFound]))
return listTuples
def main():
tupleLists = []
csvWrite = open("sequences.csv","w+")
#put path here
directory = "C:/Users/ryanp/Desktop/Duke/Fall 2018/CS 316- Databases/Final Project/LingusticDB-database/books/books"
for filename in findFiles(directory, "[0-9]*.txt"):
print(filename)
filenamePartition = filename.rsplit("\\") #change for Linux I think
bookId = filenamePartition[-1][:-4]
f = open(filename,"r",encoding = "ISO-8859-1")
createSequences = createWordSequences(f)
addThisToTupleList = convertToList(createSequences, bookId)
for tuple in addThisToTupleList:
csvWrite.write(tuple[0] + "|" + tuple[1] + "|" + tuple[2] + "|" + str(tuple[3]) + "\n")
csvWrite.close()
return tupleLists
main() |
7625b2c42de5d225f78ae060c0a427e3dedb6624 | xiashiwendao/leecode | /leecode/785_is-graph-bipartite.py | 1,496 | 3.515625 | 4 | class Solution(object):
def isBipartite(self, graph):
# 节点着色记录
color = {}
# 遍历图节点,注意图在这里是通过二维数组形式进行存储
# 数组的索引代表了节点索引,数组索引所对应元素(N个数)
# 代表了和这个节点有连线关系的节点(索引)
for node in range(len(graph)):
print(node)
# 如果当前节点并没有着过色,设置初始化颜色(0),放入堆栈中,这里有一个堆栈对象
# 用于存放已经着色的节点
if node not in color:
stack = [node]
color[node] = 0
# 遍历堆栈
while stack:
node = stack.pop()
# 遍历一下graph里面的节点,用于和堆栈中元素进行比较,如果相等
# 说明了这个图不是二部图,因为不满足节点首尾可以划分为两个集合
for nei in graph[node]:
if nei not in color:
stack.append(nei)
color[nei] = color[node] ^ 1
elif color[nei] == color[node]:
return False
return True
if __name__ == "__main__":
s = Solution()
graph = [[1,3], [0,2], [1,3], [0,2]]
rev = s.isBipartite(graph)
print(rev)
# s = Solution()
# print(dir(s)) |
20c4e6a9e5e00328c9d6e473c56471e5c669d002 | rohanhg91/017-sort-dict-by-value | /build.py | 572 | 3.796875 | 4 | import operator
def solution_asc(dic):
'''
Enter your code here
'''
op = []
for i in range (0, len(dic)):
for k, v in dic.iteritems():
output = (k,v)
op.append(output)
return op
def solution_desc(dic):
'''
Enter your code here
'''
op = []
for i in range (0, len(dic)):
for k, v in dic.iteritems():
output = (k,v)
op.append(output)
op1 = op[::-1]
return op1
'''
dic = {2: 21, 1: 11, 0: 12, 9: 211, 4: 55}
a = solution_desc(dic)
print a
'''
|
059453aee1f86bac6a39301f15b24348ac223986 | Allegheny-Computer-Science-102-F2020/cs102-F2020-slides | /src/finiteset-operations.py | 258 | 3.75 | 4 | from sympy import FiniteSet
set_one = FiniteSet(1, 2, 3)
set_two = FiniteSet(1, 2, 3, 4)
union = set_one.union(set_two)
print("Union:")
print(union)
print()
intersection = set_one.intersection(set_two)
print("Intersection:")
print(intersection)
print()
|
92095818bba09a2b68fa3f0f341b99115703e13f | lfeng99/Competitive-Programming | /General/3n+1.py | 118 | 3.71875 | 4 | n=int(input())
num=0
while n!=1:
if n%2==0:
n=n/2
elif n%2==1:
n=n*3+1
num+=1
print(num)
|
6e66884b1d166bd55554b094574bb1680dbb18f0 | AusCommsteam/Algorithm-and-Data-Structures-and-Coding-Challenges | /Challenges/braceExpansion.py | 1,298 | 4.375 | 4 | """
Brace Expansion
A string S represents a list of words.
Each letter in the word has 1 or more options. If there is one option, the letter is represented as is. If there is more than one option, then curly braces delimit the options. For example, "{a,b,c}" represents options ["a", "b", "c"].
For example, "{a,b,c}d{e,f}" represents the list ["ade", "adf", "bde", "bdf", "cde", "cdf"].
Return all words that can be formed in this manner, in lexicographical order.
Example 1:
Input: "{a,b}c{d,e}f"
Output: ["acdf","acef","bcdf","bcef"]
Example 2:
Input: "abcd"
Output: ["abcd"]
Note:
1 <= S.length <= 50
There are no nested curly brackets.
All characters inside a pair of consecutive opening and ending curly brackets are different.
"""
"""
Backtracking
Time: 2^N
"""
class Solution:
def expand(self, S: str) -> List[str]:
self.res = []
def helper(s, word):
if not s:
self.res.append(word)
else:
if s[0] == '{':
i = s.find('}')
for letter in s[1:i].split(','):
helper(s[i+1:], word+letter)
else:
helper(s[1:], word + s[0])
helper(S, '')
self.res.sort()
return self.res
|
e7dde24b28f5aa61f2facc90459f3a3e0fe75428 | mdhvkothari/Python-Program | /data structure/search_in_binary_tree.py | 1,168 | 3.984375 | 4 | class Node:
def __init__(self,data):
self.data = data
self.left = None
self.right = None
def insert(self,data):
if self.data:
if self.data>data:
if self.left is None:
self.left = Node(data)
else:
self.left.insert(data)
elif self.data<data:
if self.right is None:
self.right = Node(data)
else:
self.right.insert(data)
else:
self.data = data
def find(self,data):
if data<self.data:
if self.left is None:
return "Not found"
return self.left.find(data)
elif data>self.data:
if self.right is None:
return "Not found"
return self.right.find(data)
else:
return "Found!!"
def print(self):
if self.left:
self.left.print()
print(self.data)
if self.right:
self.right.print()
node = Node(10)
node.insert(5)
node.insert(50)
node.insert(30)
node.print()
print(node.find(500))
|
d33cdf99116c4283275163a99668591fdca0f630 | nkhanhng/nkhanh | /chaper3/month.py | 117 | 3.875 | 4 | month = ["January", "Febr", "March", "April","May"]
for i in month:
print("One of the months of the year is", i)
|
5ffe8f8e7fc80e893109ffbffcd2e6f2eaffdaea | karimm25/Karim | /TSIS 2/Lecture6/14.py | 178 | 3.859375 | 4 | # check whether a string is a pangram or not
import string, sys
def pan(str_):
alphaset = set(string.ascii_lowercase)
return alphaset <= set(str_)
print(pan(input())) |
27b656e17b4bb1531e0c5dd9fa0519841eb27f12 | DiegoDenzer/exercicios | /src/diversos/funcoes_uteis.py | 116 | 3.53125 | 4 |
lista = [1, 2, 3, 0, 2, 1]
print(all(lista)) # Todos devem ser true
print(any(lista)) # Se um elemento ser True
|
28b0889a729769b7450fb81d44f19d5a899ccc7b | xiaoyeren/python_high_performance | /JIT_tools/jit_custom_class.py | 2,236 | 3.6875 | 4 | # -*- coding: utf-8 -*-
'''
Created on 2019年5月2日 下午7:28:23
Zhukun Luo
Jiangxi University of Finance and Economics
'''
#JI类
#自定义Node类
import numba as nb
class Node:
def __init__(self,value):
self.next=None
self.value=value
class LinkedList:#实现链表
def __init__(self):
self.head=None
def push_front(self,value):
if self.head==None:
self.head=Node(value)
else:
#替换链表头
new_head=Node(value)
new_head.next=self.head
self.head=new_head
def show(self):
node=self.head
while node is not None:
print(node.value)
node=node.next
lst=LinkedList()
lst.push_front(1)
lst.push_front(2)
lst.push_front(3)
lst.show()#321
@nb.jit
def sum_list(lst):
result=0
node=lst.head
while node is not None:
result+=node.value
node=node.next
return result
lst1=LinkedList()
[lst1.push_front(i) for i in range(1000)]
# print(sum_list(lst1))#无法推断类型
#可使用装饰器nb.jitclass 来编译Node和LinkedList类,装饰器接受一个参数,其中包含被装饰类的属性的类型。
#首先必须先声明属性,在定义类,使用nb.deferred_type()函数,其次属性next可以使NOne,也可以是一个Node实例,这被称为可选类型,nb.optional
node_type=nb.deferred_type()
node_spec=[('next',nb.optional(node_type)),('value',nb.int64)]
@nb.jitclass(node_spec)
class Node1:
def __init__(self,value):
self.next=None
self.value=value
node_type.define(Node.class_type.instance_type)
ll_spec=[('head',nb.optional(Node.class_type.instance_type))]
@nb.jitclass(ll_spec)
class LinkedList1:#实现链表
def __init__(self):
self.head=None
def push_front(self,value):
if self.head==None:
self.head=Node(value)
else:
#替换链表头
new_head=Node(value)
new_head.next=self.head
self.head=new_head
def show(self):
node=self.head
while node is not None:
print(node.value)
node=node.next
lst2=LinkedList1()
[lst2.push_front(i) for i in range(1000)]
#性能很大提升 |
367ca4ec225aaffffa19ad38df191fa5e56c7cd4 | SnyderMbishai/Numpy | /concatenation_splitting.py | 1,007 | 3.5 | 4 | import numpy as np
# Concatenate two arrays
a = np.array([1,2,3])
b = np.array([3,2,1])
np.concatenate([a,b])
print(np.concatenate([a,b]))
# Concatenate more than two arrays
c = np.array([7,7,7])
print(np.concatenate([a,b,c]))
# Multi-dimensional
grid = np.array([
[1,2,3],
[4,5,6]
])
print(grid)
np.concatenate([grid,grid]) # along first axis
print(np.concatenate([grid,grid]))
np.concatenate([grid,grid], axis=1) # along second axis
print(np.concatenate([grid,grid], axis=1))
""" mixed dimensions """
mx1 = np.array([1,2,3])
mx2 = np.array([
[9,8,7],
[6,5,4]
])
# Vertical stack
v = np.vstack([mx1, mx2])
print(v)
# Horizontal stack
mx3 = np.array([
[88],
[77]
])
h = np.hstack([mx2,mx3])
print(h)
"""
Splitting
"""
# np.split, np.vsplit, np.hsplit
x = [1, 2, 3, 99, 99, 3, 2, 1]
x1,x2,x3 = np.split(x,(3,5))
print(x1,x2,x3)
s = np.arange(16).reshape(4,4)
print(s)
upper, lower = np.vsplit(s,[2])
print(upper, lower)
left,right = np.hsplit(s,[2])
print(left,right)
|
32859640cad6333470d8437b85e6290cef7c8b51 | pu-ray/python | /basic ,,,quiz.py | 2,263 | 3.609375 | 4 | Python 3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> print("Twinkle, twinkle, little star\n\t How i wonder what you are!\n\t\t Up above the world is so high \n\t\t Like a diamond in the sky\n Twinkle,twinkle little star\n\t How i wonder what yyou are.")
Twinkle, twinkle, little star
How i wonder what you are!
Up above the world is so high
Like a diamond in the sky
Twinkle,twinkle little star
How i wonder what yyou are.
>>> import sys.
>>> import sys
>>> print("python," "\n\t", sys.version, "\n", "version info\n\t",sys.version_info)
python,
3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)]
version info
sys.version_info(major=3, minor=7, micro=2, releaselevel='final', serial=0)
>>> import daytime
>>> import datetime
>>> print(datetime.datetime.now())
2019-03-07 22:37:31.464480
>>> import math
>>> r=1.1
>>> print(math p*r**2)
>>> import math
>>> r=1.1
>>> print(math pi*r**2)
>>> print(math.pi*r**2)
3.8013271108436504
>>> print("Hello{1}{0}".format (input("mbugua:"),input("purity:")))
mbugua:
purity:
Hello
>>> nested =[[1,2,3],[4,5,6],[7,8,9]]
>>> sum (nested,[])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> nested=[[1,2,3],[4,5,6],[7,8,9]]
>>> nested=[]
>>> list =([1,2,3,4,5,6,7,8,9])
>>> for items in nested:
for items in list:
flat.append(items)
>>> list
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y=[x**2 for x in list]
>>> y
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> color_list=["red","green","white","black"]
>>> color_list=list [0]
>>> color_list[0]
>>> color_list[0]
>>> color_list=["red","green","white","black"]
>>> print(color_list[0],color_list[3])
red black
>>> from datatime import date
>>> from datetime import date
>>> d1=date(2014,7,2)
>>> d2=date(2014,7,11)
>>> print((d2-d1).days)
9
>>> from math import pi
>>> r=6.0
>>> v=4/3*pi*r**3
>>> v
904.7786842338603
>>> def dif(n):
if n<=17:
return 17-n
>>> print(dif(n))
>>> return
>>> ddif dif(n):
>>> def dif(n):
if n <=17:
return 17-n
else:
n=int(input("17"))
>>> print(dif(n))
>>> n=int(input("3"))
3
>>> n =int(input("3")
if(n>17):
>>> def dif(n):
if n <=17:
return 17-n
>>>
|
0f0a61f12c274b5a2753f8afd5d52957b436463c | corvolino/estudo-de-python | /Atividades-Estrutura-De-Decisao/atividade08.py | 615 | 4.25 | 4 | '''
Faça um programa que pergunte o preço de três produtos e informe qual produto você deve comprar,
sabendo que a decisão é sempre pelo mais barato.
'''
produto1 = float(input("Informe valor do Primeiro produto: "))
produto2 = float(input("Informe valor do Segundo produto: "))
produto3 = float(input("Informe valor do Terceiro produto: "))
if produto1 < produto2 and produto1 < produto3:
print("\nVocê deve comprar o Primeiro produto!")
elif produto2 < produto1 and produto2 < produto3:
print("\nVocê deve comprar o Segundo produto!")
else:
print("\nVocê deve comprar o Terceiro produto!")
|
a446f4efc4fb2eb26530f11d8ccc685118d8e78c | SharonFei/python | /test_filter.py | 99 | 3.546875 | 4 | def _odd_iter(): #从3开始的奇数序列
n=1
while True:
n=n+2
yield n
|
8031414f08d7fbc1142eeb6c7c94afeeebccbbbd | knoppanthony/advent-2020 | /7/7.py | 1,190 | 3.625 | 4 | import networkx as nx
def main():
input = open("input", "r")
luggage_list = input.read().splitlines()
partOne(luggage_list)
def partOne(luggage_list):
G = nx.DiGraph()
for luggage in luggage_list:
#get the bag and a string of the contains
bag,contains = luggage.strip().rstrip(".").split(" bags contain ")
print(bag)
print(contains)
#this is a single bag, likely a solo node or the end of the graph
if contains == "no other bags":
continue
for other in contains.split(", "):
count = int(other[0])
other = other[2:].rstrip("bags").strip()
G.add_edge(bag, other, count=count)
# stole this from reddit, im not smart enough for graphs.
print("Part 1:", len(list(nx.dfs_postorder_nodes(G.reverse(), "shiny gold"))) - 1)
for node in nx.dfs_postorder_nodes(G, "shiny gold"):
G.nodes[node]["count"] = sum((G.nodes[n]["count"] + 1) * v["count"] for (n, v) in G[node].items())
print("Part 2:", G.nodes["shiny gold"]["count"])
class LuggageNode:
def __init__(self, name):
self.name = name
if __name__ == "__main__":
main()
|
aac69b675143abef640c691ecbf8c52d0d66ebbd | 2099454967/wbx | /03day/3-老王开枪/7-子弹杀人.py | 1,837 | 3.65625 | 4 | #人类
class Person():
def __init__(self,name):
self.name = name
self.gun = None #默认没有枪
self.hp = 100 #默认有100滴血
def zhuangzidan(self,danjia,bullet):#装子弹
danjia.addBullet(bullet)
def zhuangdanjia(self,gun,danjia):#装弹夹
gun.addDanJia(danjia)
def takeGun(self,gun):#老王拿枪
self.gun = gun
def openGun(self,diren):#老王开枪
#拿到一发子弹
zidan = self.gun.popGunBullet()#告诉枪给我一发子弹
zidan.kill(diren)#子弹杀人
#枪类
class Gun():
def __init__(self,name):
self.name = name
self.danjia = None
#装弹夹
def addDanJia(self,danjia):
self.danjia = danjia
def popGunBullet(self):
return self.danjia.popBullet()
#弹夹
class DanJia():
def __init__(self,size):
self.size = size
self.bullet_list = []
def addBullet(self,bullet):
self.bullet_list.append(bullet)#加子弹
def popBullet(self):
return self.bullet_list.pop()#弹出子弹
#子弹
class Bullet():
def __init__(self):
self.weili = 5
#子弹杀人
def kill(self,diren):
diren.hp -= self.weili#减去子弹的威力
print("剩余血量%d"%diren.hp)
laowang = Person("老王")#创建老王对象
ak47 = Gun("ak47")#创建一把枪
danjia = DanJia(20)#可以放20颗子弹
for i in range(10):#创建20发子弹
bullet = Bullet()
laowang.zhuangzidan(danjia,bullet)#装子弹
laowang.zhuangdanjia(ak47,danjia)#装弹夹
laosong = Person("老宋")#创建一个人
laowang.takeGun(ak47)#老王拿枪
laowang.openGun(laosong)
laowang.openGun(laosong)
laowang.openGun(laosong)
laowang.openGun(laosong)
laowang.openGun(laosong)
laowang.openGun(laosong)
laowang.openGun(laosong)
laowang.openGun(laosong)
laowang.openGun(laosong)
laowang.openGun(laosong)
laowang.openGun(laosong)
laowang.openGun(laosong)
laowang.openGun(laosong)
laowang.openGun(laosong)
|
783cf69b2b7e26105582e53163c5dfa915c239e1 | xaviBlue/curso_python | /conditionals.py | 471 | 3.9375 | 4 | x=10
if x < 30 :
print("x es menor que 30")
else:
print("x es mayor que 20")
color ='blue'
if color=='red':
print('El color es rojo')
elif color == 'blue':
print('The color is blue')
else:
print('es mi color')
name = 'Xavier'
lastame='Arcia'
if name=='Xavier':
if lastame=='Arcia':
print('Tu eres: '+name+' '+lastame)
else:
print('Tu no eres Xavier')
if x>2 and x<=10:
print('X es nayor a 2 y menor o igual que 10')
|
746b2e91ae2650b115321be199a0470e16b78f39 | BarrySunderland/code_snippets | /load_csv_as_np_array.py | 586 | 3.5 | 4 |
def load_csv_as_array(fpath, datatype=np.int0, skip_header=True):
"""
load a csv file and return as a numpy array
faster than loading using pandas but all cols must be same datatype
skips first row by default
"""
with open(fpath,'r') as dest_f:
data_reader = csv.reader(dest_f,
delimiter = ',',
quotechar = '"')
if skip_header:
next(data_reader) #skips the header/first line
data = [data for data in data_reader]
return np.asarray(data, datatype)
|
333ef316794c7fec0c21daad0d18a16289f0b925 | Eltotino/holbertonschool-higher_level_programming | /0x06-python-classes/5-square.py | 1,482 | 4.625 | 5 | #!/usr/bin/python3
"""Square class with size"""
class Square():
"""Square defines the square of a given value
Attributes:
size: size of the square
"""
def __init__(self, size=0):
"""
Init method is a constructor for Square class
Args:
size (int): the size of the square
Raises:
TypeError: if size is not an integer
ValueError: if size is less than 0
"""
self.size = size
@property
def size(self):
"""
A Getter of the instance attributes
"""
return self._size
@size.setter
def size(self, value):
"""
Setter of instance attributes
Args:
value (int): a value for the square
Raises:
TypeError: size is not an int
ValueError: size is less than 0
"""
if not type(value) is int:
raise TypeError('size must be an integer')
if value < 0:
raise ValueError("size must be >= 0")
else:
self.__size = value
def area(self):
""" Public Method that returns the current square area"""
return (self.__size) * (self.__size)
def my_print(self):
"""
Prints thevalue of square formed by "#""
"""
if self.__size == 0:
print()
else:
for i in range(0, self.__size):
print('#' * self.__size)
|
410437c2fd94b67fdf2b1147fc2bcd38dcc7d002 | AniketGurav/PyTorch-learning | /Official/Getting_Started/A_60_Minute_Blitz/PyTorch_getstarted_1_60minBlitz_3_NeuralNetwork.py | 3,972 | 3.75 | 4 | """
Title: PyTorch/ Get Started/ a 60-min Blitz/ Neural Network
Main Author: PyTorch
Editor: Shengjie Xiu
Time: 2019/3/20
Purpose: PyTorch learning
Environment: python3.5.6 pytorch1.0.1 cuda9.0
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
# 1.Define the network
# region Description
print('\nDefine the network\n')
class Net(nn.Module): # Net继承了nn.Module类
def __init__(self): # 构造函数,在类的一个对象被建立时,马上运行
super(Net, self).__init__() # super也是一个定义好的类
# 1 input image channel, 6 output channels, 5x5 square convolution
# kernel
self.conv1 = nn.Conv2d(1, 6, 5) # con1/conv2...都是类的attribute
self.conv2 = nn.Conv2d(6, 16, 5)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x): # 成员函数与一般函数区别是多了self
# Max pooling over a (2, 2) window
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
# If the size is a square you can only specify a single number
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = x.view(-1, self.num_flat_features(x))
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
def num_flat_features(self, x):
size = x.size()[1:] # all dimensions except the batch dimension
num_features = 1
for s in size:
num_features *= s
return num_features
net = Net() # 创建Net类对象
print(net)
# 有10个params:5个权重+5个输出特征数(conv2d的filters数/fc的输出神经元个数)
params = list(net.parameters()) # parameters是Module类的关键attribute
print(len(params))
print(params[0].size()) # conv1's .weight
input = torch.randn(1, 1, 32, 32)
out = net(input)
print(out)
# Zero the gradient buffers of all parameters
net.zero_grad()
# backprops with random gradients
out.backward(torch.randn(1, 10))
'''
You need to clear the existing gradients though, else gradients will be accumulated to existing gradients.
'''
'''
# Recap:
# torch.Tensor - A multi-dimensional array with support for autograd operations like backward(). Also holds the gradient w.r.t. the tensor.
# nn.Module - Neural network module. Convenient way of encapsulating parameters, with helpers for moving them to GPU, exporting, loading, etc.
# nn.Parameter - A kind of Tensor, that is automatically registered as a parameter when assigned as an attribute to a Module.
# autograd.Function - Implements forward and backward definitions of an autograd operation. Every Tensor operation creates at least a single Function node that connects to functions that created a Tensor and encodes its history.
'''
# endregion
# 2. Loss Function
# region Description
print('\nLoss Function\n')
output = net(input)
target = torch.randn(10)
target = target.view(1, -1)
criterion = nn.MSELoss()
loss = criterion(output, target)
print(loss)
# 此时我们的BP可以从loss的值开始,而不是任意定义的了
print(loss.grad_fn)
print(loss.grad_fn.next_functions[0][0])
print(loss.grad_fn.next_functions[0][0].next_functions[0][0])
# endregion
# 3. Backprop
# region Description
print('\nBackprop\n')
net.zero_grad() # zeroes the gradient buffers of all parameters
print('conv1.bias.grad before backward')
print(net.conv1.bias.grad)
loss.backward() # Backprop
print('conv1.bias.grad after backward')
print(net.conv1.bias.grad)
# endregion
# 4. update the weights
# region Description
print('\nupdate the weights\n')
# create your optimizer
optimizer = optim.SGD(net.parameters(), lr=0.01)
# in your training loop:
optimizer.zero_grad() # zero the gradient buffers
output = net(input)
loss = criterion(output, target)
loss.backward()
optimizer.step() # Does the update
# endregion
|
6dcb47bff6308b00c9b2c9db200d3d2a495095fd | Maxence-Labesse/AutoMxL | /build/lib/AutoMxL/Preprocessing/Outliers.py | 11,249 | 3.515625 | 4 | """ Outliers handling functions
- OutliersEncoding (class) : identify and replace outliers
- get_cat_outliers (funct): identify categorical features containing outliers
- get_num_outliers (func): identify numerical features containing outliers
- replace_category (func): replace categories of a categorical variable
- replace_extreme_values (func): replace extreme values (oh!)
"""
import pandas as pd
import numpy as np
from AutoMxL.Utils.Display import *
class OutliersEncoder(object):
"""Identify et replace outliers for categorical dang numerical features
- num : x outlier <=> abs(x - mean) > xstd * var
- cat : x outlier category <=> with frequency <x% (Default 5%)
Parameters
----------
cat_threshold : float (default 0.02)
Minimum modality frequency
num_xstd : int (Default : 3)
Variance gap coef
"""
def __init__(self,
cat_threshold=0.02,
num_xstd=4
):
self.cat_threshold = cat_threshold,
self.num_xstd = num_xstd
self.is_fitted = False
self.l_var_num = []
self.l_var_cat = []
self.d_num_outliers = {}
self.d_cat_outliers = {}
"""
----------------------------------------------------------------------------------------------
"""
def fit(self, df, l_var, verbose=False):
"""Fit encoder
Parameters
----------
df : DataFrame
input dataset
l_var : list
features to encode.
If None, all features
verbose : boolean (Default False)
Get logging information
"""
# get num and cat features
l_num = [col for col in df.columns.tolist() if df[col].dtype != 'object']
l_str = [col for col in df.columns.tolist() if df[col].dtype == 'object']
# get valid values (not boolean)
if l_var is None:
self.l_var_cat = [col for col in l_str if df[col].nunique() > 2]
self.l_var_num = [col for col in l_num if df[col].nunique() > 2]
else:
self.l_var_cat = [col for col in l_var if col in l_str and df[col].nunique() > 2]
self.l_var_num = [col for col in l_var if col in l_num and df[col].nunique() > 2]
# cat outliers
if len(self.l_var_cat) > 0:
self.d_cat_outliers = get_cat_outliers(df, l_var=self.l_var_cat, threshold=self.cat_threshold,
verbose=False)
# num outliers
if len(self.l_var_num) > 0:
self.d_num_outliers = get_num_outliers(df, l_var=self.l_var_num, xstd=self.num_xstd, verbose=False)
# Fitted !
self.is_fitted = True
# verbose
if verbose:
print(" **method cat: frequency<" + str(self.cat_threshold)
+ " / num:( x: |x - mean| > " + str(self.num_xstd) + "* var)")
print(" >", len(self.d_cat_outliers.keys()) + len(self.d_num_outliers.keys()), "features with outliers")
if len(self.d_cat_outliers.keys()) > 0:
print(" - cat", list(self.d_cat_outliers.keys()))
if len(self.d_num_outliers.keys()) > 0:
print(" - num", list(self.d_num_outliers.keys()))
"""
----------------------------------------------------------------------------------------------
"""
def transform(self, df, verbose=False):
"""Transform dataset features using the encoder.
Can be done only if encoder has been fitted
Parameters
----------
df : DataFrame
dataset to transform
verbose : boolean (Default False)
Get logging information
"""
assert self.is_fitted, 'fit the encoding first using .fit method'
df_local = df.copy()
# cat features
if len(list(self.d_cat_outliers.keys())) > 0:
if verbose:
print(" - cat aggregated values:")
for col in self.d_cat_outliers.keys():
df_local = replace_category(df_local, col, self.d_cat_outliers[col], replace_with='outliers',
verbose=verbose)
# num features
if len(list(self.d_num_outliers.keys())) > 0:
if verbose:
print(" - num values replaces:")
for col in self.d_num_outliers.keys():
df_local = replace_extreme_values(df_local, col, self.d_num_outliers[col][0],
self.d_num_outliers[col][1], verbose=verbose)
# if no features with outliers
if len(list(self.d_cat_outliers.keys())) + len(list(self.d_num_outliers.keys())) == 0:
print(" > no outlier to replace")
return df_local
"""
----------------------------------------------------------------------------------------------
"""
def fit_transform(self, df, l_var=None, verbose=False):
"""Fit and transform dataset with encoder
Parameters
----------
df : DataFrame
input dataset
l_var : list
features to encode.
If None, all features identified as dates (see Features_Type module)
verbose : boolean (Default False)
Get logging information
"""
df_local = df.copy()
# fit
self.fit(df_local, l_var=l_var, verbose=False)
# transform
df_local = self.transform(df_local, verbose=verbose)
return df_local
"""
----------------------------------------------------------------------------------------------
"""
def get_cat_outliers(df, l_var=None, threshold=0.05, verbose=False):
"""Outliers detection for selected/all categorical features.
Method : Modalities with frequency <x% (Default 5%)
Parameters
----------
df : DataFrame
Input dataset
l_var : list (Default : None)
Names of the features
If None, all the categorical features
threshold : float (Default : 0.05)
Minimum modality frequency
verbose : boolean (Default False)
Get logging information
Returns
-------
dict
{variable : list of categories considered as outliers}
"""
# if var_list = None, get all categorical features
# else, remove features from var_list whose type is not categorical
l_cat = [col for col in df.columns.tolist() if df[col].dtype == 'object']
if l_var is None:
l_var = l_cat
else:
l_var = [col for col in l_var if col in l_cat]
df_local = df[l_var].copy()
# dict containing value_counts for each variable
d_freq = {col: pd.value_counts(df[col], dropna=False, normalize=True) for col in l_var}
# if features contain at least 1 outlier category (frequency <threshold)
# store outliers categories in dict
d_outliers = {k: v[v < threshold].index.tolist()
for k, v in d_freq.items()
if len(v[v < threshold]) > 1}
if verbose:
color_print('cat features outliers identification (frequency<' + str(threshold) + ')')
print(' > features : ', df_local.columns, )
print(" > containing outliers", list(d_outliers.keys()))
return d_outliers
"""
-------------------------------------------------------------------------------------------------------------------------
"""
def get_num_outliers(df, l_var=None, xstd=3, verbose=False):
"""Outliers detection for selected/all numerical features.
Method : x outlier <=> abs(x - mean) > xstd * var
Parameters
----------
df : DataFrame
Input dataset
l_var : list (Default : None)
Names of the features
If None, all the num features
xstd : int (Default : 3)
Variance gap coef
verbose : boolean (Default False)
Get logging information
Returns
-------
dict
{variable : [lower_limit, upper_limit]}
"""
# if var_list = None, get all num features
# else, remove features from var_list whose type is not num
l_num = df._get_numeric_data().columns.tolist()
if l_var is None:
l_var = l_num
else:
l_var = [col for col in l_var if col in l_num]
df_local = df[l_var].copy()
# compute features upper and lower limit (abs(x - mean) > xstd * var (x=3 by default))
data_std = np.std(df_local)
data_mean = np.mean(df_local)
anomaly_cut_off = data_std * xstd
lower_limit = data_mean - anomaly_cut_off
upper_limit = data_mean + anomaly_cut_off
data_min = np.min(df_local)
data_max = np.max(df_local)
# store variables and lower/upper limits
d_outliers = {col: [lower_limit[col], upper_limit[col]]
for col in df_local.columns.tolist()
if (data_min[col] < lower_limit[col] or data_max[col] > upper_limit[col])}
if verbose:
color_print('num features outliers identification ( x: |x - mean| > ' + str(xstd) + ' * var)')
print(' > features : ', l_var)
print(" > containing outliers", list(d_outliers.keys()))
return d_outliers
"""
-------------------------------------------------------------------------------------------------------------------------
"""
def replace_category(df, var, categories, replace_with='outliers', verbose=False):
"""Replace categories of a categorical variable
Parameters
----------
df : DataFrame
Input dataset
var : string
variable to modify
categories : list(string)
categories to replace
replace_with : string (Default : 'outliers')
word to replace categories with
verbose : boolean (Default False)
Get logging information
Returns
-------
DataFrame
Modified dataset
"""
df_local = df.copy()
# replace categories
df_local.loc[df_local[var].isin(categories), var] = replace_with
if verbose:
print(' > ' + var + ' ', categories)
return df_local
"""
-------------------------------------------------------------------------------------------------------------------------
"""
def replace_extreme_values(df, var, lower_th=None, upper_th=None, verbose=False):
"""Replace extrem values : > upper threshold or < lower threshold
Parameters
----------
df : DataFrame
Input dataset
var : string
variable to modify
lower_th : int/float (Default=None)
lower threshold
upper_th : int/float (Default=None)
upper threshold
verbose : boolean (Default False)
Get logging information
Returns
-------
DataFrame
Modified dataset
"""
assert (lower_th is not None or upper_th is not None), 'specify at least one limit value'
df_local = df.copy()
# replace values with upper_limit and lower_limit
if upper_th is not None:
df_local.loc[df_local[var] > upper_th, var] = upper_th
if lower_th is not None:
df_local.loc[df_local[var] < lower_th, var] = lower_th
if verbose:
print(' > ' + var + ' < ' + str(round(lower_th, 4)) + ' or > ' + str(
round(upper_th, 4)))
return df_local
|
6f7e40a56336b882d6f0df2667af83041edfa598 | peterlevi/euler | /066.py | 799 | 3.765625 | 4 | #!/usr/bin/python3
# Pell's equation x^2 - Dy^2 = 1
# Solution is given by some hi, ki, where hi/ki are the convergents of the continued fraction for sqrt(D)
import math
def nextFrac(a, b, c):
x = math.sqrt(a)
d = math.floor((x + b) / c)
b1 = d*c - b
c1 = (a - b1**2) / c
return (d, a, b1, c1)
def frac(a):
b = 0
c = 1
while True:
(d, a, b, c) = nextFrac(a, b, c)
yield d
def okPell(D, x, y):
return x**2 - D*y**2 == 1
def solve(d):
h1 = 1
h2 = 0
k1 = 0
k2 = 1
for a in frac(d):
h = a*h1 + h2
k = a*k1 + k2
if okPell(d, h, k):
return (h, k)
h2 = h1
h1 = h
k2 = k1
k1 = k
print(max((solve(d), d) for d in range(2, 1001) if d != round(math.sqrt(d))**2))
|
bfecd012728cc9ff1296d0ba19a6508f2326958e | GabrielNew/Python3-Basics | /World 1/ex003.py | 343 | 4.21875 | 4 | # -*- coding: utf-8 -*-
#ex003 -> Crie um programa que leia dois valores e mostre a soma entre eles.
num1 = int(input('Digite um número: '))
num2 = int(input('Digite outro número: '))
soma = num1 + num2
print(f'A soma entre {num1} e {num2} é {soma}')
# print(f'A soma entre {num1} e {num2} é {num1+num2}') Sem utilizar a variável soma
|
e64c12df13f43383892f8d584030da638c997a9c | carlypalicz/Twitter-Search | /twitter_data.py | 4,649 | 3.609375 | 4 | # Author: Carly Palicz
# I pledge my honor that I have abided by the Stevens Honor System
# twitter_data.py searches Twitter for tweets matching a search term,
# up to a maximun number, and sorts them in order of date posted
###### user must supply authentication keys where indicated
# to run from terminal window:
#python3 twitter_data.py --search_term mysearch --search_max mymaxresults --search_sort mysort
# where: mysearch is the term the user wants to search for; default = music
# and: mymaxresults is the maximum number of resulta; default = 30
# and: mysort is the data item the user wants to sort the output by
# other options used in the search: lang = "en" (English language tweets)
# and result_type = "popular" (asks for most popular rather than most recent tweets)
# The program uses the TextBlob sentiment property to analyze the tweet for:
# polarity (range -1 to 1) and
# subjectivity (range 0 to 1 where 0 is objective and 1 is subjective)
# The program creates a .csv output file with a line for each tweet
# including tweet data items and the sentiment information
from textblob import TextBlob # needed to analyze text for sentiment
import argparse # for parsing the arguments in the command line
import csv # for creating output .csv file
import tweepy # Python twitter API package
import unidecode # for processing text fields in the search results
from operator import itemgetter #added in order to sort results
### PUT AUTHENTICATOIN KEYS HERE ###
CONSUMER_KEY = "BV2o0tJwnIYVgcXLBlI9hDCzw"
CONSUMER_KEY_SECRET = "865FxSTD8RA5J6cTdxICfzY4T5Z1L7RKWJyjBgsCk0Dqzcs6ED"
ACCESS_TOKEN = "703304163-9q0TeYNworht8GF3AcMi4InArehHOxiqHTVUzwKm"
ACCESS_TOKEN_SECRET = "jtZKQmq43p8gLEvD30XB5lQAifyp9XlZVYy3EqbN4wUT0"
# AUTHENTICATION (OAuth)
authenticate = tweepy.auth.OAuthHandler(CONSUMER_KEY, CONSUMER_KEY_SECRET)
authenticate.set_access_token(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)
api = tweepy.API(authenticate)
# Get the input arguments - search_term and search_max
parser = argparse.ArgumentParser(description='Twitter Search')
parser.add_argument("--search_term", action='store', dest='search_term', default="music")
parser.add_argument("--search_max", action='store', dest='search_max', default=30)
#added a third argument so the user could select how to sort the results
parser.add_argument("--search_sort", action='store', dest='sort_by', default="created")
args = parser.parse_args()
search_term = args.search_term
search_max = int(args.search_max)
sort_by = args.sort_by
# create a .csv file to hold the results, and write the header line
csvFile = open('twitter_results.csv','w')
csvWriter = csv.writer(csvFile)
csvWriter.writerow(["username","userid","created", "text", "retweets", "followers",
"friends","polarity","subjectivity"])
#added code: made a list of dictionaries for the results so they could be sorted before written
results = []
# do the twitter search
for tweet in tweepy.Cursor(api.search, q = search_term, lang = "en",
result_type = "popular").items(search_max):
created = tweet.created_at # date created
text = tweet.text # text of the tweet
text = unidecode.unidecode(text)
retweets = tweet.retweet_count # number of retweets
username = tweet.user.name # user name
userid = tweet.user.id # userid
followers = tweet.user.followers_count # number of user followers
friends = tweet.user.friends_count # number of user friends
# use TextBlob to determine polarity and subjectivity of tweet
text_blob = TextBlob(text)
polarity = text_blob.polarity
subjectivity = text_blob.subjectivity
#adds the dictionary item
results.append({"username": username, "userid": userid, "created": created, "text": text, "retweets": retweets, "followers": followers,
"friends": friends, "polarity": polarity, "subjectivity": subjectivity})
#sorts the list of dictionaries by tweet field specified
if sort_by == "created":
results_sorted = sorted(results, key=itemgetter('created'), reverse=True)
elif sort_by == "retweets":
results_sorted = sorted(results, key=itemgetter('retweets'), reverse=True)
elif sort_by == "followers":
results_sorted = sorted(results, key=itemgetter('followers'), reverse=True)
#throws an error if the tweet field specific isnt valid
else:
print("ERROR: sort_by argument must be 'retweets', 'followers', or 'created'. Note that 'created' is the default value.")
exit()
for result in results_sorted:
csvWriter.writerow([result["username"], result["userid"], result["created"], result["text"], result["retweets"], result["followers"],
result["friends"], result["polarity"], result["subjectivity"]])
csvFile.close()
|
dbdc0f29bd7a6c8f1f9a80e871e9abb447857568 | Joe2357/Baekjoon | /Python/Code/2900/2908 - 상수.py | 209 | 3.65625 | 4 | a, b = input().split()
for i in range(2, -1, -1):
if a[i] > b[i]:
for j in range(2, -1, -1):
print(a[j], end = "")
break
elif a[i] < b[i]:
for j in range(2, -1, -1):
print(b[j], end = "")
break |
7b813071498ef79396b24eac3c4f9304bb0c3ec6 | a2606844292/vs-code | /test2/列表/1.py | 1,234 | 4.09375 | 4 | #列表索引
A_list_of_things=['Hello',1,2,3,4,0,5.0,6.0,True,False]
#找到列表中索引值为0的值
print(A_list_of_things[0])
#找到倒数最后一个,从-1开始
print(A_list_of_things[-1])
print(len(A_list_of_things))
print(A_list_of_things[len(A_list_of_things)-1])
#列表切片
#从1开始切到2结束
print(A_list_of_things[1:3])
#从1开始切到3结束
print(A_list_of_things[1:4])
#从0开始切到7结束
print(A_list_of_things[0:7])
print(A_list_of_things[:7])
#从7开始到结尾
print(A_list_of_things[7:])
#列表和字符串的可变性
Hello='Hello hi~'
print(Hello[1])
list1=[1,2,3,4,5,6]
print(list1[1])
#修改列表里面第一个值
list1[0]='one'
print(list1)
Hello='Mello hi'
print(Hello)
#列表和字符串的可变性2
#xiaobai_said复制给xiaohei_said
xiaobai_said='Hello ,my name is xiaobai'
xiaohei_said=xiaobai_said
print(xiaohei_said)
#xiaobai_said修改值并不影响赋值内容
xiaobai_said='Hello ,my name is dabai'
print(xiaohei_said)
print(xiaobai_said)
#列表和字符串的可变性3
#列表赋值会跟随原值变化
score_card=['B','A','D','A','B','C']
score_card2=score_card
score_card[0]='C'
print(score_card)
print(score_card2) |
aefe651205ac1c8ac71b3e1490886ee56e59c4ea | saetar/pyEuler | /done/py/euler_102.py | 1,253 | 4.125 | 4 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# Jesse Rubin - project Euler
"""
Triangle containment
Problem 102
Three distinct from_points are plotted at random on a Cartesian plane, for
which -1000 ≤ x, y ≤ 1000, such that a triangle is formed.
Consider the following two triangles:
A(-340,495), B(-153,-910), C(835,-947)
X(-175,41), Y(-421,-714), Z(574,-645)
It can be verified that triangle ABC contains the origin, whereas triangle XYZ
does not.
Using triangles.txt (right click and 'Save Link/Target As...'), a 27K text file
containing the co-ordinates of one thousand "random" triangles, find the number
of triangles for which the interior contains the origin.
NOTE: The first two examples in the file represent the triangles in the example
given above.
"""
from bib.maths import Trigon
def p102():
# open file and put into list
with open(r'../txt_files/p102_triangles.txt') as f:
triangles = [tuple(map(int, j.split(',')))
for j in [i.strip('\n') for i in f.readlines()]]
# check if (0, 0) in triangle for triangle in the list
return sum(1 for tri in triangles if (0, 0) in Trigon.from_points(tri))
if __name__ == '__main__':
ANSWER = p102()
print("# triangles: {}".format(ANSWER)) |
130a534c86a1726c411c3de1c6df5ce11a87aae9 | rafaelperazzo/programacao-web | /moodledata/vpl_data/480/usersdata/311/111140/submittedfiles/Av2_Parte2.py | 114 | 3.96875 | 4 | # -*- coding: utf-8 -*-
a=int(input('Digite o numero: '))
c=0
while a>0 :
c=c+(a%10)
a=a//10
print(c)
|
96103fc6765e633a6b4046f8b2091edd7d805e0d | f1uk3r/Daily-Programmer | /Problem-12/Easy/string-permutations.py | 517 | 4.4375 | 4 | # python 3
# string-permutation.py # take a string and returns all the permutation
# Write a small program that can take a string: "hi!"
# and print all the possible permutations of the string:
from itertools import permutations
import sys
if __name__ == '__main__':
if len(sys.argv) > 1:
string_to_permutation = str(sys.argv[1])
else:
string_to_permutation = str(input("Enter a String: "))
permutations = [''.join(p) for p in permutations(string_to_permutation)]
for each in permutations:
print(each) |
163291585f47743ab15baaefcfccd9b02e71f1df | gitoffdabus/inf1340_2015_asst1 | /exercise1.py | 1,295 | 3.796875 | 4 | #!/usr/bin/env python
""" Assignment 1, Exercise 1, INF1340, Fall, 2014. Grade to gpa conversion
This module prints the amount of money that Lakshmi has remaining
after the stock transactions
"""
__author__ = 'Susan Sim'
__email__ = "ses@drsusansim.org"
__copyright__ = "2015 Susan Sim"
__license__ = "MIT License"
#calculate cost of total shares
#calculate commission costs
#deduct the amount she paid her stockbroker
number_of_shares = 2000
initial_share = 900
sales_share = 942.75
commission_percentage = .03
# Commission paid to the broker for purchasing the shares
initial_commission = (number_of_shares * initial_share) * commission_percentage
# Total cost of purchasing the shares
initial_cost = (number_of_shares * initial_share) + initial_commission
# Commission paid to the broker for selling the shares
sales_commission = (number_of_shares * sales_share) * commission_percentage
# Total cost of selling the shares
sales_price = (number_of_shares * sales_share) - sales_commission
# Calculation of money left with Lakshmi
money = sales_price - initial_cost
print ("Lakshmi is at a balance of %d after selling her stock and paying her broker twice" %money)
print("Thus, Lakshmi suffered a loss")
"""
Test Case 1
no input required
expected output:-25065
actual output: -25065
Error: None
""" |
9c55a22ed6b935f9e3c7aa987c2a348824c1150d | robbyakakom/20191 | /dataengineering_si_2/prg_09.py | 342 | 3.84375 | 4 | isi = "YA"
total = 0
while isi == "YA" :
kode = input("Kode Barang : ")
nama = input("Nama Barang : ")
harga = int(input("Harga Beli : "))
total = total + harga
print("----------------------------------")
isi = input("Isi data lagi? (YA/TIDAK) ")
print("----------------------------------")
print("Total Harga : " , total)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.