blob_id
stringlengths 40
40
| repo_name
stringlengths 5
119
| path
stringlengths 2
424
| length_bytes
int64 36
888k
| score
float64 3.5
5.22
| int_score
int64 4
5
| text
stringlengths 27
888k
|
---|---|---|---|---|---|---|
842a0e1ba6bbd01a986e816b3a1c479d4f59fff5 | CreatorGhost/HackerRank | /2D Array DS | 1,163 | 3.96875 | 4 | #!/bin/python3
import math
import os
import random
import re
import sys
def findIt(u,p,a): #function just to add every single hourglass
an=0 #to add every elements
for i in range (u,u+3): #this function neds to sole for 3x3 so start and end with 3
for j in range (p,p+3):
if i!=u+1:
an=a[i][j]+an #add all three when its not the secound row
if i==u+1:
if j==p+1:
an=a[i][j]+an #add only the second element of sceond row
return an #retunig the result of added 3x3 matrics
def hourglassSum(a):
s=[] #list to append all the adition of values
for i in range(len(a)-2): #loop will
for j in range(len(a)-2):
k=findIt(i,j,a) #appending all the possible output
s.append(k)
return max(s) #returning the max element
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
arr = []
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
result = hourglassSum(arr)
fptr.write(str(result) + '\n')
fptr.close()
|
421da4356fe1c641216ff34810950572251f4ada | alisatsar/itstep | /Python/HomeWork/04.04.2017.py | 1,723 | 4.1875 | 4 | """Напишите программу, запрашивающую у пользователя ввод числа. Если число принадлежит диапазону от -100 до 100,
то создается объект одного класса, во всех остальных случаях создается объект другого класса.
В обоих классах должен быть метод-конструктор __init__, который в первом классе возводит число в квадрат,
а во-втором - умножает на два."""
class UnRange:
def __init__ (self, number):
self.result = number * 2
print(self.result)
class InRange:
def __init__ (self, number):
self.result = number ** 2
print(self.result)
userNumber = int(input("Enter your number: "))
if userNumber >= -100 and userNumber <= 100:
userNumber = InRange(userNumber)
else:
userNumber = UnRange(userNumber)
#Напишите программу, высчитывающую площадь оклейки обоями комнаты. Объектами являются: стены, потолки, окна и двери.
class Wallpaper:
def __init__(self, width, height, length):
self.width = width
self.height = height
self.length = length
self.square = 2 * self.height * (self.width + self.length)
return s
width = int(input("Enter the width of wall your room: "))
height = int(input("Enter the height of wall your room: "))
length = int(input("Enter the length of your room: "))
wallpaper = Wallpaper(width, height, length)
squareWithoutDoorsAndWindows =
|
95d31d2b7728c6977bab65d0f27d02bbd6ed22e6 | fy88fy/studyPython | /study_example/2018.01.26/Hanshu.py | 467 | 3.765625 | 4 | #/usr/bin/env python
# -*- coding:utf-8 -*-
# @time :2018/1/26 21:37
# @Author :FengXiaoqing
# @file :Hanshu.py
def add(args):
total = 0
for i in args:
total += i
return total
def main():
number = list()
s = input("Please input some number add (a + b + c ..):")
print(s)
for num in s.split("+"):
number.append(int(num.strip("+")))
print(add(number))
if __name__ == '__main__':
main() |
01f44499d127d555c84c1411f6486eb95bbbcb8b | m4mayank/ComplexAlgos | /subsets.py | 874 | 3.71875 | 4 | # Given an integer array nums of unique elements, return all possible subsets (the power set).
# The solution set must not contain duplicate subsets. Return the solution in any order.
# Example 1:
# Input: nums = [1,2,3]
# Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
# Example 2:
# Input: nums = [0]
# Output: [[],[0]]
# Constraints:
# 1 <= nums.length <= 10
# -10 <= nums[i] <= 10
# All the numbers of nums are unique.
class Solution:
def subset(self, result, nums):
length = len(result)
subset = []
for i in range(0, length):
temp = result.pop()
subset.append(temp)
subset.append(temp+[nums])
return subset
def subsets(self, nums: List[int]) -> List[List[int]]:
result = [[]]
for i in nums:
result = self.subset(result, i)
return result |
513c3de6fc20fbebbeccca06ca9ca0a77b955a04 | SimZhou/algorithm014-algorithm014 | /Week_03/98. 验证二叉搜索树.py | 1,124 | 3.921875 | 4 | # https://leetcode-cn.com/problems/validate-binary-search-tree/
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isValidBST(self, root: TreeNode) -> bool:
# '''递归'''
# lb, rb = float("-inf"), float("inf")
# def dfs(root, lb, rb):
# if not root: return True
# left = dfs(root.left, lb, root.val)
# right = dfs(root.right, root.val, rb)
# # 当前节点是否有效,取决于左右子树是否有效,以及当前节点是否有效
# if left and right and lb < root.val < rb: return True
# else: return False
# return dfs(root, lb, rb)
'''中序遍历'''
pre = float("-inf")
def inorder(root):
nonlocal pre
if not root: return True
if not inorder(root.left): return False
if root.val <= pre: return False
pre = root.val
return inorder(root.right)
return inorder(root) |
a3ce138c0a54571d22232429b9283b0d45e92b96 | elefert400/Class_Work | /Algorithms/HW2/scc_e330l807.py | 3,387 | 3.53125 | 4 | from __future__ import print_function
import fileinput
import sys
class Graph:
def __init__(self,v):
self.Vertices = v
self.graph = {new_list: [] for new_list in range(self.Vertices)}
self.sorted = [[] for x in range(self.Vertices)]
self.counter = 0
#adds an edge to the graph
def addEdge(self,u,v):
self.graph[u].append(v)
#DFS that finds all the strongly connected components
def DFSSCC(self,v,visited):
visited[v] = True
self.sorted[self.counter].append(v + 1)
for i in self.graph[v]:
if visited[i] == False:
self.DFSSCC(i, visited)
#fill the stack
def fillStack(self,v,visited, stack):
visited[v] = True
for i in self.graph[v]:
#print(i)
if visited[i] == False:
self.fillStack(i, visited, stack)
stack = stack.append(v)
#get a graph that is the transpose of the graph
def getTranspose(self):
g = Graph(self.Vertices)
for i in self.graph:
for j in self.graph[i]:
g.addEdge(j, i)
return g
def SCC(self):
#declare the stack and initialize the visited array
stack = []
visited = [False] * (self.Vertices)
#fill the stack using DFS
for i in range(self.Vertices):
if visited[i] == False:
self.fillStack(i, visited, stack)
#get the transpose of the graph and reset up the visited array
gr = self.getTranspose()
visited = [False] * (self.Vertices)
#recursing down the stack that was generated
while stack:
i = stack.pop()
if visited[i] == False:
gr.DFSSCC(i, visited)
gr.counter += 1
#sort the lists
for x in range(len(self.sorted)):
gr.sorted[x].sort()
gr.sorted.sort()
#printing the lists
for y in range(len(self.sorted)):
for z in range(len(gr.sorted[y])):
if(len(gr.sorted[y]) == 0):
pass
elif gr.sorted[y][z] == gr.sorted[y][-1]:
print ("{}".format(gr.sorted[y][z]), end = '')
else:
print ("{} ".format(gr.sorted[y][z]), end = '')
if(len(gr.sorted[y]) == 0):
pass
elif gr.sorted[y] == gr.sorted[-1]:
pass
else:
print("")
def main():
in_file = open(sys.argv[1], "r")
#reading the first two lines
num_nodes = in_file.readline()
num_nodes = num_nodes.strip("\t\n\r")
num_nodes = int(num_nodes)
empty = in_file.readline()
edge_list = in_file.readlines()
in_file.close()
grap = Graph(num_nodes)
#stripping all useless characters
helper1 = 0
for x in edge_list:
edge_list[helper1] = edge_list[helper1].strip("\t\n\r")
helper1 += 1
#add all edges to the graph
helper2 = -1
for y in edge_list:
helper2 += 1
for chay in y:
if chay == ' ':
pass
else:
grap.addEdge(helper2, (int(chay) - 1))
#run algorithm and print
grap.SCC()
main() |
ac19f9a5a561cb3a5fefd54248352fc3bd19f9d0 | twhit223/fundraising_simulation | /simulate_dynamic.py | 7,578 | 3.8125 | 4 | from startup import Startup
from definitions import STARTUP_STATES
from statistics import mean, stdev
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from wat import wat
# This is the main function that runs the simulation of the startup. It takes in an initialized Startup object and performs various operations on it as specified by the model. The updated Startup object will either have raised a Series A or failed.
def simulate(startup):
# Check if either of the end conditions are met. If so, return the startup. Otherwise, move the startup forward in the simulation.
# print('The startup was initialized with control pref {} and quality {}. The initial value is {}. The initial round is {}. The funding history is below. {}'.format(startup.control_pref, startup.quality, startup.value, startup.round, startup.funding_history))
while not (startup.state == 'series_a-success' or startup.state == 'die'):
# wat()
startup.advance()
# print('The startup is in state {}. It has value {}. The current funding round is {} and it has raised a total of {}'.format(startup.state, startup.value, startup.round, startup.amt_raised))
# print('The startup finished in state {}. It has value {}, and it has raised a total of {}. The funding history is below. {}'.format(startup.state, startup.value, startup.amt_raised, startup.funding_history))
return startup
# This function creates a matrix of startups and simulates them. For each value of control_preference and quality (as specified by increment), the matrix contains a list of simulated startups (as specified by number_of_startups). It then returns the matrix of simulated startups.
def initialize_startup_matrix(increment, number_of_startups):
print("Initializing the startup matrix...")
# Check that an integer mutliple of the increment equals 1.0
# Create the startup matrix as a list of list of lists.
data = []
for quality in np.arange(0.0, 1.0+increment, increment):
row = []
for control_preference in np.arange(0.0, 1.0+increment, increment):
cell = []
for k in range(number_of_startups):
cell.append(Startup(control_preference, quality))
row.append(cell)
data.append(row)
print("Simulating startups...")
# Simulate the startups in the list
[[[simulate(s) for s in column] for column in row] for row in data]
print("Startups simulated!")
return data
# This function performs an analysis of the startups that have been simulated and returns a matrix containing a list of tuples for each combination of quality and control preference. The list is structured as follows: [(avg. value, 10th percentile, 90th percentile), (avg. ownership %, 10th percentile, 90th percentile), (avg. time to series A, 10th percentile, 90th percentile), % survived to series a]
def simulation_analysis(startup_matrix):
analysis = []
for i in range(0, len(startup_matrix)):
row = []
for j in range(0, len(startup_matrix[i])):
cell =[]
# For a certain quality and control pref, get all of the startups that were simulated
startups = startup_matrix[i][j]
# For those startups, calculate the following
value = [s.value if s.state == STARTUP_STATES[8] else 0 for s in startups]
ownership = [s.ownership_history[-1] for s in startups]
time = [s.age for s in startups]
survival = [1 if s.state == STARTUP_STATES[8] else 0 for s in startups]
# Create a tuple based on the lists
avg_value = (mean(value), stdev(value))
avg_ownership = (mean(ownership), stdev(ownership))
avg_time = (mean(time), stdev(time))
survival_pct = mean(survival)
# Append the results to the cell
cell.append(avg_value)
cell.append(avg_ownership)
cell.append(avg_time)
cell.append(survival_pct)
row.append(cell)
analysis.append(row)
return analysis
def plot_analysis(increment, analysis):
fig, axes = plt.subplots(nrows=2, ncols=2, sharex=True)
x = np.arange(0.0 ,1.0 + increment, increment)
# Get the values and the stdev
# The first row of the analysis is quality = 0
# Plot the Value vs. Control Pref
ax = axes[0,0]
# For each level of quality, get the series to plot
for i in range(0, len(x)):
row = analysis[i]
values = [data[0][0] for data in row]
stdevs = [data[0][1] for data in row]
ax.errorbar(x = x, y = values, yerr = None, label = "{0:.1f}".format(x[i]))
ax.legend(title = 'Quality', loc='upper left', ncol=1)
ax.set_title('Avg. Value vs. Control Preference')
# Plot the Ownership vs. Control Pref
ax = axes[0,1]
# For each level of quality, get the series to plot
for i in range(0, len(x)):
row = analysis[i]
values = [data[1][0] for data in row]
stdevs = [data[1][1] for data in row]
ax.errorbar(x = x, y = values, yerr = None, label = "{0:.1f}".format(x[i]))
ax.legend(title = 'Quality', loc='upper left', ncol=1)
ax.set_title('Avg. Ownership % vs. Control Preference')
# Plot the Time to Series A vs. Control Pref
ax = axes[1,0]
# For each level of quality, get the series to plot
for i in range(0, len(x)):
row = analysis[i]
values = [data[2][0] for data in row]
stdevs = [data[2][1] for data in row]
ax.errorbar(x = x, y = values, yerr = None, label = "{0:.1f}".format(x[i]))
ax.legend(title = 'Quality', loc='upper left', ncol=1)
ax.set_title('Avg. Age vs. Control Preference')
# Plot the Probability of Survival to Series A vs. Control Pref
ax = axes[1,1]
# For each level of quality, get the series to plot
for i in range(0, len(x)):
row = analysis[i]
values = [data[3] for data in row]
ax.errorbar(x = x, y = values, yerr = None, label = "{0:.1f}".format(x[i]))
ax.legend(title = 'Quality', loc='upper left', ncol=1)
ax.set_title('P(Survival to Series A) vs. Control Preference')
plt.show()
wat()
# Split the data up between the four plots we want: value, ownership, time, and prob survival
""" How do we conduct actual analysis:
--> The output I want from a simulation is a dataframe with control preference on one axes, quality on the other, and at each cell a list that contains N startups that have been simulated with those parameters.
--> From this output, I will calculate the following: avg. value, avg. control, avg. time to series age, and probability of reaching series a (all with variances except the probability). This should be inserted into a dataframe with the same structure as the output from the simulation
--> Once I have these calculations, the idea will be to plot the following:
1.) X-axis: Control Preference, Y-axis: Avg. Value + error bars, plot a line for each level of quality (e.g. quality = 0.2, quality = 0.4, etc.)
2.) X-axis: Control Preference, Y-axis: Avg. Control + error bars, plot a line for each level of quality (e.g. quality = 0.2, quality = 0.4, etc.)
3.) X-axis: Control Preference, Y-axis: Avg. Time to Series A + error bars, plot a line for each level of quality (e.g. quality = 0.2, quality = 0.4, etc.).
4.) X-axis: Control Preference, Y-axis: Probability of successfully raising series A, plot a line for each level of quality (e.g. quality = 0.2, quality = 0.4, etc.).
--> To get to the final output, I need to have a dataframe with
"""
increment = 0.2
startup_matrix = initialize_startup_matrix(increment, 20)
analysis = simulation_analysis(startup_matrix)
plot_analysis(increment, analysis)
wat()
test = Startup(0.8,0.6)
simulate(test)
test.plot()
# wat()
|
678cfbbc306b5c22f718d7f0378bc8a5b22323c9 | kaushal6038/ajax | /admin_test_pro/pro/testfile.py | 276 | 3.546875 | 4 | import datetime
seconds = datetime.datetime.now()
print(seconds.minute)
import time
time.sleep(4)
# with open("/checkfile.txt", "w") as f:
# f.write("Hello World form")
file = open("checkfile.txt", "a")
file.write("Your text goes here "+ str(seconds))
file.close()
|
b3b441ce41915714ae067851b2c2aa7b20c8c909 | sofiamalpique/fcup-programacao-01 | /3.6.py | 255 | 3.546875 | 4 | from turtle import*
def triangulo(lado):
for i in range(3):
forward(lado)
left(120)
def triforce(lado):
triangulo(2*lado)
penup()
forward(lado)
pendown()
left(60)
triangulo(lado)
|
833898a98dc90002e36939a5f923b441affa64b0 | benscruton/python_fundamentals | /coding_dojo_assignments/fundamentals/make_dictionary.py | 962 | 3.78125 | 4 | def make_dict_orig(list1, list2):
new_dict = {}
inverted = len(list2) > len(list1)
keys = list2 if inverted else list1
values = list1 if inverted else list2
for i in range(len(values)):
new_dict[keys[i]] = values[i]
return new_dict
def make_dict(list1, list2):
zipped = zip(list2, list1) if len(list2) > len(list1) else zip(list1, list2)
return dict(zipped)
name_eq = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar"]
favorite_animal_eq = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas"]
name_longer = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oksana", "Oscar"]
favorite_animal_shorter = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "sable"]
d1 = make_dict(name_eq, favorite_animal_eq)
d2 = make_dict(name_longer, favorite_animal_shorter)
d3 = make_dict(favorite_animal_shorter, name_longer)
print(d1)
print("*"*30)
print(d2)
print("*"*30)
print(d3) |
001c8f38937c2676dd7b0c4a9c58ee136e3b1a90 | Yaswanthbobbu/IQuestions_Python | /Questions/21. Reverse string.py | 162 | 3.96875 | 4 | str = input("Welcome to programming :")
words = str.split()
print(words)
words.reverse()
#words[-1::-1]
print(words)
outputstr=' '.join(words)
print(outputstr) |
439dad735e97009088f24b7c657a33c56a66ea6e | huangqiank/Algorithm | /leetcode/two_Pointer/p.py | 20,008 | 3.5 | 4 | def three_sum_smaller(nums, k):
nums = sorted(nums)
count = 0
for i in range(len(nums)):
l = i + 1
r = len(nums) - 1
while l < r:
if nums[l] + nums[r] + nums[i] == k:
tmp = nums[r]
while l < r and tmp == nums[r]:
r -= 1
if nums[l] + nums[r] + nums[i] < k:
count += r - l
l += 1
else:
tmp = nums[r]
while l < r and tmp == nums[r]:
r -= 1
return count
def three_sum(nums):
nums = sorted(nums)
res = []
if not nums or len(nums) < 3:
return res
for i in range(len(nums)):
if nums[i] > 0:
return res
if i != 0 and nums[i] == nums[i - 1]:
continue
l = i + 1
r = len(nums) - 1
while l < r:
if nums[i] + nums[l] + nums[r] == 0:
res.append([i, l, r])
tmp = nums[l]
while nums[l] == tmp and l < r:
l += 1
tmp = nums[r]
while nums[r] == tmp and l < r:
r -= 1
continue
if nums[i] + nums[l] + nums[r] < 0:
tmp = nums[l]
while l < r and tmp == nums[l]:
l += 1
continue
if nums[i] + nums[l] + nums[r] > 0:
tmp = nums[r]
while l < r and tmp == nums[r]:
r -= 1
continue
return res
def three_sum_smaller(nums, target):
nums = sorted(nums)
res = []
count = 0
if not nums or len(nums) < 3:
return res
for i in range(len(nums)):
l = i + 1
r = len(nums) - 1
while l < r:
if nums[i] + nums[l] + nums[r] < target:
count = count + r - l
l += 1
continue
if nums[i] + nums[l] + nums[r] >= target:
tmp = nums[r]
while l < r and tmp == nums[r]:
r -= 1
continue
return count
def three_sum_closed(nums, target):
nums = sorted(nums)
res = []
dif = float("inf")
for i in range(len(nums)):
l = i + 1
r = len(nums) - 1
while l < r:
if nums[i] + nums[l] + nums[r] == target:
return [i, l, r]
if abs(nums[i] + nums[l] + nums[r] - target) < dif:
res = [i, l, r]
if nums[i] + nums[l] + nums[r] < target:
tmp = nums[l]
while l < r and tmp == nums[l]:
l += 1
continue
if nums[i] + nums[l] + nums[r] > target:
tmp = nums[r]
while l < r and tmp == nums[r]:
r -= 1
continue
return res
def threeSumClosest(nums, target):
dif = float('inf')
nums = sorted(nums)
n = len(nums)
res = []
if not nums or len(nums) < 3:
return res
for i in range(n):
l = i + 1
r = n - 1
while l < r:
total = nums[i] + nums[l] + nums[r]
if total == target:
return [nums[i], nums[l], nums[r]]
if total < target:
tmp = nums[l]
if abs(target - total) < dif:
dif = abs(target - total)
res = [nums[i], nums[l], nums[r]]
while nums[l] == tmp and l < r:
l += 1
continue
if total > target:
tmp = nums[r]
if abs(target - total) < dif:
dif = abs(target - total)
res = [nums[i], nums[l], nums[r]]
while nums[r] == tmp and l < r:
r -= 1
continue
return res
## n -1 , n-2, n-3
def four_sum_target(nums, target):
res = []
if not nums or len(nums) < 4:
return
nums = sorted(nums)
n = len(nums)
for i in range(0, n - 3):
if nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target:
break
if nums[i] + nums[n - 3] + nums[n - 2] + nums[n - 1] < target:
continue
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n - 2):
if nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target:
break
if nums[i] + nums[j] + nums[n - 1] + nums[n - 2] < target:
continue
if j > 0 and nums[j] == nums[j - 1]:
continue
total = nums[i] + nums[j]
l = j + 1
r = n - 1
while l < r:
if nums[l] + nums[r] + total == target:
res.append((i, j, l, r))
tmp = nums[l]
while l < r and tmp == nums[l]:
l += 1
tmp = nums[r]
while l < r and tmp == nums[r]:
r -= 1
continue
if nums[l] + nums[r] + total < target:
tmp = nums[l]
while l < r and tmp == nums[l]:
l += 1
else:
tmp = nums[r]
while l < r and tmp == nums[r]:
r -= 1
return res
def four_sum(nums, target):
res = []
if not nums or len(nums) < 4:
return res
n = len(nums)
nums = sorted(nums)
for i in range(n - 3):
if nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target:
break
if nums[i] + nums[n - 1] + nums[n - 2] + nums[n - 3] < target:
continue
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n - 2):
if nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target:
break
if nums[i] + nums[j] + nums[n - 1] + nums[n - 2] < target:
continue
if j - i > 1 and nums[j] == nums[j - 1]:
continue
l = j + 1
r = n - 1
total = nums[i] + nums[j]
while l < r:
if total + nums[l] + nums[r] == target:
print(l)
print(r)
print("\n")
res.append([nums[i], nums[j], nums[l], nums[r]])
while l < r and nums[l + 1] == nums[l]:
l += 1
while l < r and nums[r] == nums[r - 1]:
r -= 1
l += 1
r -= 1
elif total + nums[l] + nums[r] < target:
l += 1
else:
r -= 1
return res
##n-4,n-3,n-2,n-1
def four_sum(nums, target):
if not nums or len(nums) < 4:
return
res = []
n = len(nums)
for i in range(0, n - 3):
if nums[i] + nums[i + 1] + nums[i + 2] + nums[i + 3] > target:
break
if nums[i] + nums[n - 3] + nums[n - 2] + nums[n - 1] < target:
continue
if i > 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, n - 2):
if nums[i] + nums[j] + nums[j + 1] + nums[j + 2] > target:
break
if nums[i] + nums[j] + nums[n - 2] + nums[n - 1] < target:
continue
if j > 0 and nums[j] == nums[j - 1]:
continue
l = j + 1
r = n - 1
while l < r:
if nums[i] + nums[j] + nums[l] + nums[r] == target:
res.append((nums[i], nums[j], nums[l], nums[r]))
tmp1 = nums[l]
while tmp1 == nums[l] and l < r:
l += 1
tmp2 = nums[r]
while l < r and tmp2 == nums[r]:
r -= 1
continue
if nums[i] + nums[j] + nums[l] + nums[r] < target:
tmp1 = nums[l]
while tmp1 == nums[l] and l < r:
l += 1
continue
if nums[i] + nums[j] + nums[l] + nums[r] > target:
tmp1 = nums[r]
while tmp1 == nums[r] and l < r:
r -= 1
continue
return res
def merge_sorted_array(nums1, m, nums2, n):
nums_copy = nums1[:m]
i = 0
j = 0
k = 0
while i < m and j < n:
if nums_copy[i] <= nums2[j]:
nums1[k] = nums_copy[i]
i += 1
k += 1
else:
nums1[k] = nums2[j]
j += 1
k += 1
if i < m:
nums1[k:m + n] = nums1[i:m]
if j < n:
nums1[k:m + n] = nums2[j:n]
return nums1
def implement_str(haystack, needle):
i = 0
m = len(haystack)
n = len(needle)
while i < m - n + 1:
if haystack[i:i + n] == needle:
return i
i += 1
return -1
def linked_list_cycle(head):
slow = head
fast = head
if not head:
return False
while fast != None and fast.next != None and fast.next.next != None:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False
def linked_list_cycle(head):
slow = head
fast = head
if not head:
return False
while fast != None and fast.next != None and fast.next.next != None:
slow = slow.next
fast = fast.next.next
if slow == fast:
break
new = head
while slow and slow.next:
new = new.next
slow = slow.next
if slow == new:
return slow
return -1
def backspace_compare(s, t):
i = len(s) - 1
j = len(t) - 1
m = 0
n = 0
while i >= 0 and j >= 0:
while i >= 0 and (s[i] == "#" or m > 0):
if s[i] == "#":
m += 1
else:
m -= 1
i -= 1
while j >= 0 and (t[j] == "#" or n > 0):
if t[i] == "#":
n += 1
else:
n -= 1
j -= 1
if i < 0 or j < 0:
break
if s[i] != t[j]:
return False
i -= 1
j -= 1
while i >= 0 and (s[i] == "#" or m > 0):
if s[i] == "#":
m += 1
else:
m -= 1
i -= 1
if i >= 0 and s[i] != "#":
return False
while j >= 0 and (t[j] == "#" or n > 0):
if t[i] == "#":
n += 1
else:
n -= 1
j -= 1
if j >= 0 and t[j] != "#":
return False
return True
def max_area(heights):
area = 0
tmp = 0
i = 0
if heights is None or len(heights) < 2:
return -1
while i < len(heights):
if heights[i] <= tmp:
i += 1
continue
j = i + 1
while j < len(height):
height = max(heights[i], heights[j])
width = j - i
area = max(area, width * height)
j += 1
tmp = heights[i]
i += 1
return area
def implement_str(haystack, needle):
n = len(haystack)
m = len(needle)
if n < m:
return -1
for i in range(n - m + 1):
if haystack[i:i + m] == needle:
return i
return -1
def move_zero(nums):
n = len(nums)
i = 0
j = 0
while i < n:
if nums[i] == 0:
i += 1
else:
nums[j] = nums[i]
i += 1
j += 1
for t in range(j, len(nums)):
nums[t] = 0
return nums
def k_diff_pairs_in_an_array(nums, k):
if not nums:
return
nums = sorted(nums)
n = len(nums)
count = 0
for i in range(0, n, 1):
if i > 0 and nums[i] == nums[i - 1]:
continue
j = i + 1
while j < n:
if nums[j] - nums[i] == k:
count += 1
break
if nums[j] - nums[i] < k:
j += 1
if nums[j] - nums[i] > k:
break
return count
def find(s, d):
d = sorted(d, key=lambda x: (-len(d), x))
for word in d:
if check(s, word):
return word
return -1
def check(s, word):
j = 0
for i in range(len(word)):
k = s.find(word[i], j)
if k == -1:
return False
j = k + 1
return True
def max_consecutive_one(nums):
if not nums or len(nums) == 0:
return 0
left = 0
right = 0
nums_dict = {0: 0, 1: 0}
max_length = 0
n = len(nums)
if len(nums) == 1:
return 1
while right < n:
nums_dict[nums[right]] += 1
right += 1
if nums_dict[0] >= 1:
while nums_dict[0] > 0:
nums_dict[nums[left]] -= 1
left += 1
max_length = max(max_length, right - left)
return max_length
# r
# [0,0,0,0,1]
def length_longest_substring_two_distinct(nums):
left = 0
right = 0
max_length = 0
nums_dict = {}
n = len(nums)
if n < 3:
return n
while right < n:
if nums[right] not in nums_dict:
nums_dict[nums[right]] = 1
else:
nums_dict[nums[right]] += 1
right += 1
while len(nums_dict) >= 3:
nums_dict[nums[left]] -= 1
if nums_dict[nums[left]] == 0:
del nums_dict[nums[left]]
left += 1
max_length = max(max_length, right - left)
return max_length
def palindrome_num(num):
num = str(num)
x = ''
for i in range(len(num) - 1, -1, -1):
x += num[i]
return x == num
def k_diff_pairs_in_an_array(nums, k):
if not nums or len(nums) < 2:
return -1
nums = sorted(nums)
n = len(nums)
count = 0
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i - 1]:
continue
j = i + 1
while j < n:
if nums[j] - nums[i] == k:
j += 1
count += 1
continue
if nums[j] - nums[i] > k:
break
if nums[j] - nums[i] < k:
j += 1
continue
return count
def max_consecutive_ones(nums):
left = 0
right = 0
n = len(nums)
nums_dict = {0: 0, 1: 0}
length = 0
while right < n:
nums_dict[nums[right]] += 1
right += 1
if nums_dict[0] > 0:
while nums_dict[0] > 0:
nums_dict[nums[left]] -= 1
left += 1
length = max(length, right - left)
return length
def length_longest_two_distinct_nums(nums):
max_length = 0
left = 0
right = 0
nums_dict = {}
n = len(nums)
while right < n:
if nums[right] not in nums_dict:
nums_dict[nums[right]] = 1
else:
nums_dict[nums[right]] += 1
right += 1
if len(nums_dict) > 2:
while len(nums_dict) > 2:
nums_dict[nums[left]] -= 1
if nums_dict[nums[left]] == 0:
del nums_dict[nums[left]]
left += 1
max_length = max(max_length, right - left)
return nums_dict
def palindrome_linked_list(head):
slow = head
fast = head
pre = None
mid = None
while fast and fast.next:
mid = slow
slow = slow.next
fast = fast.next.next
mid.next = pre
pre = mid
if fast != None:
slow = slow.next
while slow and pre:
if slow.value != mid.value:
return False
slow = slow.next
mid = mid.next
return True
def partition(head, x):
if not head:
return
small = node(0)
large = node(2)
tmp1 = small
tmp2 = large
while head:
if head.value < x:
tmp1.next = head
tmp1 = tmp1.next
else:
tmp2.next = head
tmp2 = tmp2.next
head = head.next
tmp1.next = large.next
return small.next
def palindrom_num(x):
x = str(x)
y = ""
for i in range(len(x) - 1, -1, -1):
y += x[i]
return x == y
def longest_word_in_dictionary(s, d):
d = sorted(d, key=lambda x: (-len(x), x))
for word in d:
if check(s, word):
return word
return
def check(s, word):
j = 0
for i in range(len(word)):
k = s.find(word[i], j)
if k == -1:
return -1
j = k + 1
return 1
def max_consecutive_one2(nums):
if not nums or len(nums) == 0:
return
nums_dict = {0: 0, 1: 0}
left = 0
right = 0
max_length = 0
while right < len(nums):
nums_dict[nums[right]] += 1
right += 1
while nums_dict[0] > 1:
nums_dict[nums[left]] -= 1
left += 1
max_length = max(max_length, right - left)
return max_length
def reverse_str(s):
i = 0
j = len(s) - 1
mid = int(len(s) / 2)
t = 0
while t < mid:
s[i], s[j] = s[j], s[i]
i += 1
j += 1
t += 1
return s
def remove_element(nums, a)
i = 0
j = 0
n = len(nums)
while j < n:
if nums[j] == a:
j += 1
else:
nums[i] = nums[j]
i += 1
j += 1
return i
def reverse_vowels_of_a_str(s):
s = [s[i] for i in range(len(s))]
vowel_set = set()
vowel_list = ["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"]
for vowel in vowel_list:
vowel_set.add(vowel)
i = 0
j = len(s) - 1
while i < j:
while i < j and s[i] not in vowel_set:
i += 1
while i < j and s[j] not in vowel_set:
j -= 1
if i < j and s[i] in vowel_set and s[j] in vowel_set:
s[i], s[j] = s[j], s[i]
i += 1
j -= 1
return s
##
# 1->2->3->4
def remove_nth_node(head, n):
slow = node(0)
fast = node(0)
slow.next = head
fast.next = head
i = 0
j = 0
while fast.next != None:
if j < n:
fast = fast.next
j += 1
else:
i += 1
slow = slow.next
fast = fast.next
slow.next = slow.next.next
if i == 0:
return head.next
return head
def is_palindrome(s):
s = filter(str.isalnum, s)
s = ''.join(list(s))
s = s.lower()
i = 0
j = len(s) - 1
n = len(s) - 1
while i <= n and j >= 0:
if s[i] != s[j]:
return False
i += 1
j -= 1
if j != 0 or i != n:
return False
return True
def subarray_product_less_than_k(nums, k):
left = 0
prod = 1
ans = 0
if k <= 1:
return 0
for right, val in enumerate(nums):
prod *= val
while prod >= k:
prod /= nums[left]
left += 1
ans += right - left + 1
return ans
def length_two_distinct_characters(s):
if not s:
return
s_dict = {}
left = 0
right = 0
max_length = 0
while right < len(s):
s_dict[s[right]] += 1
while len(s_dict) >= 3:
s_dict[s[left]] -= 1
if s_dict[s[left]] == 0:
del s_dict[s[left]]
left += 1
max_length = max(max_length, right - left)
right += 1
return max_length
def remove_duplicated_from_sorted_array(nums):
i = 0
j = 0
if not nums or len(nums) < 3:
return nums
while i < len(nums):
tmp = nums[i]
if j >= 2 and tmp == nums[j-1] and tmp == nums[j - 2]:
k = i
while k < len(nums) and nums[k] == tmp:
k += 1
i = k
if j < len(nums):
nums[j] = nums[i]
i += 1
j += 1
return j
|
8715b54a3571ede0e7d088d1f8821a9491abb9ea | the-eric-kwok/Wudao-dict | /wudao-dict/dict/dict_pys/wd.py | 15,650 | 3.5 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import print_function
import re
tag_re = re.compile('^[a-z0-9]+$')
attribselect_re = re.compile(
r'^(?P<tag>\w+)?\[(?P<attribute>[\w-]+)(?P<operator>[=~\|\^\$\*]?)' +
r'=?"?(?P<value>[^\]"]*)"?\]$'
)
# /^(\w+)\[([\w-]+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
# \---/ \---/\-------------/ \-------/
# | | | |
# | | | The value
# | | ~,|,^,$,* or =
# | Attribute
# Tag
def attribute_checker(operator, attribute, value=''):
"""
Takes an operator, attribute and optional value; returns a function that
will return True for elements that match that combination.
"""
return {
'=': lambda el: el.get(attribute) == value,
# attribute includes value as one of a set of space separated tokens
'~': lambda el: value in el.get(attribute, '').split(),
# attribute starts with value
'^': lambda el: el.get(attribute, '').startswith(value),
# attribute ends with value
'$': lambda el: el.get(attribute, '').endswith(value),
# attribute contains value
'*': lambda el: value in el.get(attribute, ''),
# attribute is either exactly value or starts with value-
'|': lambda el: el.get(attribute, '') == value \
or el.get(attribute, '').startswith('%s-' % value),
}.get(operator, lambda el: el.has_key(attribute))
def ss(soup, selector):
"""
soup should be a BeautifulSoup instance; selector is a CSS selector
specifying the elements you want to retrieve.
"""
tokens = selector.split()
current_context = [soup]
for index, token in enumerate(tokens):
if tokens[index - 1] == '>':
# already found direct descendants in last step
continue
m = attribselect_re.match(token)
if m:
# Attribute selector
tag, attribute, operator, value = m.groups()
if not tag:
tag = True
checker = attribute_checker(operator, attribute, value)
found = []
for context in current_context:
found.extend([el for el in context.findAll(tag) if checker(el)])
current_context = found
continue
if '#' in token:
# ID selector
tag, id = token.split('#', 1)
if not tag:
tag = True
el = current_context[0].find(tag, {'id': id})
if not el:
return [] # No match
current_context = [el]
continue
if '.' in token:
# Class selector
tag, klass = token.split('.', 1)
if not tag:
tag = True
classes = set(klass.split('.'))
found = []
for context in current_context:
found.extend(
context.findAll(tag,
{'class': lambda attr:
attr and classes.issubset(attr.split())}
)
)
current_context = found
continue
if token == '*':
# Star selector
found = []
for context in current_context:
found.extend(context.findAll(True))
current_context = found
continue
if token == '>':
# Child selector
tag = tokens[index + 1]
if not tag:
tag = True
found = []
for context in current_context:
found.extend(context.findAll(tag, recursive=False))
current_context = found
continue
# Here we should just have a regular tag
if not tag_re.match(token):
return []
found = []
for context in current_context:
found.extend(context.findAll(token))
current_context = found
return current_context
def monkeypatch(BeautifulSoupClass=None):
"""
If you don't explicitly state the class to patch, defaults to the most
common import location for BeautifulSoup.
"""
if not BeautifulSoupClass:
from BeautifulSoup import BeautifulSoup as BeautifulSoupClass
BeautifulSoupClass.findSelect = ss
def unmonkeypatch(BeautifulSoupClass=None):
if not BeautifulSoupClass:
from BeautifulSoup import BeautifulSoup as BeautifulSoupClass
delattr(BeautifulSoupClass, 'findSelect')
import bs4
from urllib.request import urlopen
from urllib.parse import urlparse
from urllib.parse import quote
def get_html(x):
x = quote(x)
url = urlparse('http://dict.youdao.com/search?q=%s' % x)
res = urlopen(url.geturl())
xml = res.read().decode('utf-8')
return xml
def multi_space_to_single(text):
cursor = 0
result = ""
while cursor < len(text):
if text[cursor] in ["\t", " ", "\n", "\r"]:
while text[cursor] in ["\t", " ", "\n", "\r"]:
cursor += 1
result += " "
else:
result += text[cursor]
cursor += 1
return result
# get word info online
def get_text(centent, word):
#content = get_html(word)
word_struct = {"raw_word": word}
root = bs4.BeautifulSoup(content, "lxml")
for v in root.select('h2 .keyword'):
word_struct['word'] = v.text
pron = {}
pron_fallback = False
for pron_item in ss(root, ".pronounce"):
pron_lang = None
pron_phonetic = None
for sub_item in pron_item.children:
if isinstance(sub_item, str) and pron_lang is None:
pron_lang = sub_item
continue
if isinstance(sub_item, bs4.Tag) and sub_item.name.lower() == "span" and sub_item.has_attr(
"class") and "phonetic" in sub_item.get("class"):
pron_phonetic = sub_item
continue
if pron_phonetic is None:
# raise SyntaxError("WHAT THE FUCK?")
pron_fallback = True
break
if pron_lang is None:
pron_lang = ""
pron_lang = pron_lang.strip()
pron_phonetic = pron_phonetic.text
pron[pron_lang] = pron_phonetic
if pron_fallback:
for item in ss(root, ".phonetic"):
if item.name.lower() == "span":
pron[""] = item.text
break
word_struct["pronunciation"] = pron
#
# <-- BASIC DESCRIPTION
#
nodes = ss(root, "#phrsListTab .trans-container ul")
basic_desc = []
if len(nodes) != 0:
ul = nodes[0]
for li in ul.children:
if not (isinstance(li, bs4.Tag) and li.name.lower() == "li"):
continue
basic_desc.append(li.text.strip())
word_struct["paraphrase"] = basic_desc
if not word_struct["paraphrase"]:
d = root.select(".wordGroup.def")
p = root.select(".wordGroup.pos")
ds = ""
dp = ""
if len(d) > 0:
ds = d[0].text.strip()
if len(p) > 0:
dp = p[0].text.strip()
word_struct["paraphrase"] = (dp + " " + ds).strip()
#
# -->
# <-- RANK
#
rank = ""
nodes = ss(root, ".rank")
if len(nodes) != 0:
rank = nodes[0].text.strip()
word_struct["rank"] = rank
#
# -->
# <-- PATTERN
#
# .collinsToggle .pattern
pattern = ""
nodes = ss(root, ".collinsToggle .pattern")
if len(nodes) != 0:
# pattern = nodes[0].text.strip().replace(" ", "").replace("\t", "").replace("\n", "").replace("\r", "")
pattern = multi_space_to_single(nodes[0].text.strip())
word_struct["pattern"] = pattern
#
# -->
# <-- VERY COMPLEX
#
word_struct["sentence"] = []
for child in ss(root, ".collinsToggle .ol li"):
p = ss(child, "p")
if len(p) == 0:
continue
p = p[0]
desc = ""
cx = ""
for node in p.children:
if isinstance(node, str):
desc += node
elif isinstance(node, bs4.Tag) and node.name.lower() == "b" and node.children:
for x in node.children:
if isinstance(x, str):
desc += x
elif isinstance(node, bs4.Tag) and node.name.lower() == "span":
cx = node.text
desc = multi_space_to_single(desc.strip())
examples = []
for el in ss(child, ".exampleLists"):
examp = []
for p in ss(el, ".examples p"):
examp.append(p.text.strip())
examples.append(examp)
word_struct["sentence"].append([desc, cx, examples])
# 21 new year
if not word_struct["sentence"]:
for v in root.select("#bilingual ul li"):
p = ss(v, "p")
ll = []
for p in ss(v, "p"):
if len(p) == 0:
continue
if 'class' not in p.attrs:
ll.append(p.text.strip())
if len(ll) != 0:
word_struct["sentence"].append(ll)
# -->
return word_struct
def get_zh_text(word):
content = get_html(word)
word_struct = {"word": word}
root = bs4.BeautifulSoup(content, "lxml")
# pronunciation
pron = ''
for item in ss(root, ".phonetic"):
if item.name.lower() == "span":
pron = item.text
break
word_struct["pronunciation"] = pron
# <-- BASIC DESCRIPTION
nodes = ss(root, "#phrsListTab .trans-container ul p")
basic_desc = []
if len(nodes) != 0:
for li in nodes:
basic_desc.append(li.text.strip().replace('\n', ' '))
word_struct["paraphrase"] = basic_desc
# DESC
desc = []
for child in ss(root, '#authDictTrans ul li ul li'):
single = []
sp = ss(child, 'span')
if sp:
span = sp[0].text.strip().replace(':', '')
if span:
single.append(span)
ps = []
for p in ss(child, 'p'):
ps.append(p.text.strip())
if ps:
single.append(ps)
desc.append(single)
word_struct["desc"] = desc
# <-- VERY COMPLEX
word_struct["sentence"] = []
# 21 new year
for v in root.select("#bilingual ul li"):
p = ss(v, "p")
ll = []
for p in ss(v, "p"):
if len(p) == 0:
continue
if 'class' not in p.attrs:
ll.append(p.text.strip())
if len(ll) != 0:
word_struct["sentence"].append(ll)
return word_struct
def is_alphabet(uchar):
if (u'\u0041' <= uchar <= u'\u005a') or \
(u'\u0061' <= uchar <= u'\u007a') or uchar == '\'':
return True
else:
return False
RED_PATTERN = '\033[31m%s\033[0m'
GREEN_PATTERN = '\033[32m%s\033[0m'
BLUE_PATTERN = '\033[34m%s\033[0m'
PEP_PATTERN = '\033[36m%s\033[0m'
BROWN_PATTERN = '\033[33m%s\033[0m'
def draw_text(word, conf):
# Word
print(RED_PATTERN % word['word'])
# pronunciation
if word['pronunciation']:
uncommit = ''
if '英' in word['pronunciation']:
uncommit += u'英 ' + PEP_PATTERN % word['pronunciation']['英'] + ' '
if '美' in word['pronunciation']:
uncommit += u'美 ' + PEP_PATTERN % word['pronunciation']['美']
if '' in word['pronunciation']:
uncommit = u'英/美 ' + PEP_PATTERN % word['pronunciation']['']
print(uncommit)
# paraphrase
for v in word['paraphrase']:
print(BLUE_PATTERN % v)
# short desc
if word['rank']:
print(RED_PATTERN % word['rank'], end=' ')
if word['pattern']:
print(RED_PATTERN % word['pattern'].strip())
# sentence
if conf:
count = 1
if word['sentence']:
print('')
if len(word['sentence'][0]) == 2:
collins_flag = False
else:
collins_flag = True
else:
return
for v in word['sentence']:
if collins_flag:
# collins dict
if len(v) != 3:
continue
if v[1] == '' or len(v[2]) == 0:
continue
if v[1].startswith('['):
print(str(count) + '. ' + GREEN_PATTERN % (v[1]), end=' ')
else:
print(str(count) + '. ' + GREEN_PATTERN % ('[' + v[1] + ']'), end=' ')
print(v[0])
for sv in v[2]:
print(GREEN_PATTERN % u' 例: ' + BROWN_PATTERN % (sv[0] + sv[1]))
count += 1
print('')
else:
# 21 new year dict
if len(v) != 2:
continue
print(str(count) + '. ' + GREEN_PATTERN % '[例]', end=' ')
print(v[0], end=' ')
print(BROWN_PATTERN % v[1])
count += 1
else:
print('')
def draw_zh_text(word, conf):
# Word
print(RED_PATTERN % word['word'])
# pronunciation
if word['pronunciation']:
print(PEP_PATTERN % word['pronunciation'])
# paraphrase
if word['paraphrase']:
for v in word['paraphrase']:
v = v.replace(' ; ', ', ')
print(BLUE_PATTERN % v)
# complex
if conf:
# description
count = 1
if word["desc"]:
print('')
for v in word['desc']:
if not v:
continue
# sub title
print(str(count) + '. ', end='')
v[0] = v[0].replace(';', ',')
print(GREEN_PATTERN % v[0])
# sub example
sub_count = 0
if len(v) == 2:
for e in v[1]:
if sub_count % 2 == 0:
e = e.strip().replace(';', '')
print(BROWN_PATTERN % (' ' + e + ' '), end='')
else:
print(e)
sub_count += 1
count += 1
# example
if word['sentence']:
count = 1
print(RED_PATTERN % '\n例句:')
for v in word['sentence']:
if len(v) == 2:
print('')
print(str(count) + '. ' + BROWN_PATTERN % v[0] + ' ' + v[1])
count += 1
def param_parse(param_list, word):
if 'h' in param_list or '-help' in param_list:
print('Usage: wd [OPTION]... [WORD]')
print('Youdao is wudao, A powerful dict.')
print('-h, --help display this help and exit')
print('-s, --short-desc show description without the sentence')
exit(0)
# short conf
if 's' in param_list or '-short-desc' in param_list:
conf = False
else:
conf = True
if not word:
print('Usage: wdd [OPTION]... [WORD]')
exit(0)
return conf
import sys
if __name__ == '__main__':
word = ''
param_list = []
for v in sys.argv[1:]:
if v.startswith('-'):
param_list.append(v[1:])
else:
word += ' ' + v
word = word.strip()
conf = param_parse(param_list, word)
xml = get_html(word)
if is_alphabet(word):
info = get_text(word)
draw_text(info, conf)
else:
info = get_zh_text(word)
draw_zh_text(info, conf)
|
f40f9d9d96754c56f9a159c50cebe59932a50172 | HJSang/leetcode | /code/py/bfs/lc_207_Course_Schedule.py | 1,985 | 3.84375 | 4 | # 207. Course Schedule
# There are a total of numCourses courses you have to take
# labeled from 0 to numCourses-1.
# Some courses may have prerequisites
# for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
# Given the total number of courses and a list of prerequisite pairs, is it possible for you to finish all courses?
# Example 1:
# Input: numCourses = 2, prerequisites = [[1,0]]
# Output: true
# Explanation: There are a total of 2 courses to take.
# To take course 1 you should have finished course 0. So it is possible.
# Example 2:
# Input: numCourses = 2, prerequisites = [[1,0],[0,1]]
# Output: false
# Explanation: There are a total of 2 courses to take.
# To take course 1 you should have finished course 0, and to take course 0 you should
# also have finished course 1. So it is impossible.
# Constraints:
# The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read more about how a graph is represented.
# You may assume that there are no duplicate edges in the input prerequisites.
# 1 <= numCourses <= 10^5
class Solution:
def canFinish(self, numCourses, prerequirites):
graph = [[] for _ in range(numCourses)]
visited = [0 for _ in range(numCourses)]
# Create graph
for x,y in prerequisites:
graph[x].append(y)
# visit each node
for i in range(numCourses):
if not self.dfs(graph, visited,i):
return False
return True
def dfs(self,graph, visited,i):
# if ith node is marked as being visited, then a cycle is found
if visited[i] == -1:
return False
# if it is visited, then do not visit again
if visited[i] == 1:
return True
# mark as being visited
visited[i] = -1
for j in graph[i]:
if not self.dfs(graph,visited,j):
return False
# after visit all the neighbours, mark it as done visited
visited[i]=1
return True
|
7055d2e590c97790eadb061c37e45ac91e9ed57d | OlexandraSydorova/lab_works | /labaratory1/task2.py | 389 | 3.8125 | 4 | """Обчислення конкретної функції, в залежності від введеного значення х"""
from math import sin
import re
from validators.validators_library import validator
from validators.validators_library import re_float
x = float(validator(re_float,"Введіть х "))
if x<=3:
print( x**2 +3*x+9)
else:
print(sin(x)/(x**2-9))
|
6fa8a226cd1cbe56d99e17e1c63cbbc4c7eb8821 | zadfab/Backup | /Voodo_Prime.py | 566 | 3.9375 | 4 | user_input = int(input("enter the number :"))
def prime(number):
for i in range(2,number):
if number%i == 0:
print("not a prime")
break
else:
print("proceeding...")
return True
return False
if prime(user_input):
reciprocal = str(1/user_input)
if str(user_input) in reciprocal:
print(user_input,"present in ",reciprocal,"this is a Voodo prime number")
else:
print("Not a voodo prime number")
else:
print("try with prime number this time") |
069750d16a682f72735962d42e5d3d749f5b7cdc | raghubegur/PythonLearning | /0_tkinter/buttons.py | 252 | 3.90625 | 4 | from tkinter import *
root = Tk()
def myClick():
myLabel = Label(root, text='I clicked a button')
myLabel.pack()
myButton = Button(root, text='Click Me', command=myClick, fg='blue', bg='white')
myButton.pack()
root.mainloop()
|
bed46a8f641a535bc5c1ae71c9bf12a9f8d44a47 | yonglin/thinkPy | /Tree.py | 1,744 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Jan 13 15:37:14 2013
@author: yuege
"""
class Tree:
def __init__(self, cargo, left = None, right = None):
self.cargo = cargo
self.left = left
self.right = right
def __str__(self):
return str(self.cargo)
def printTreePostorder(tree):
if tree == None:
return
printTreePostorder(tree.left)
printTreePostorder(tree.right)
print tree.cargo,
def printTreeInorder(tree):
if tree == None:
return
printTreeInorder(tree.left)
print tree.cargo,
printTreeInorder(tree.right)
def printTreeIndented(tree, level = 0):
if tree == None:
return
printTreeIndented(tree.right, level+1)
print ' '*level + str(tree.cargo)
printTreeIndented(tree.left,level+1)
def getToken(tokenList, expected):
if tokenList[0] == expected:
del tokenList[0]
return True
else:
return False
def getNumber(tokenList):
if getToken(tokenList,'('):
x = getSum(tokenList)
if not getToken(tokenList,')'):
raise ValueError, 'missing parenthesis'
return x
else:
x = tokenList[0]
if not isinstance(x, int):
return None
# del tokenList[0]
tokenList[:1] = []
return Tree(x, None, None)
def getProduct(tokenList):
a = getNumber(tokenList)
if getToken(tokenList,'*'):
b = getProduct(tokenList)
return Tree('*',a,b)
else:
return a
def getSum(tokenList):
a = getProduct(tokenList)
if getToken(tokenList,'+'):
b = getSum(tokenList)
return Tree('+', a ,b)
else:
return a
|
a8fea4642764d65e6e067009d20da63bdc38a24f | adjeri/Data-Structures-And-Algorithms | /Arrays-HashTables/moveZeroes.py | 345 | 3.609375 | 4 | def moveZeroes(nums):
i = 0
while i < len(nums) - 1:
j = i+1
while j < len(nums):
if nums[i] == 0 and nums[j] != 0:
swap = nums[i]
nums[i] = nums[j]
nums[j] = swap
i += 1
j+= 1
i += 1
print(nums)
moveZeroes([0,1,0,3,12]) |
2a9aaf0f3116eb0bed882c431d4e3d9f26e3bd34 | juan7914/prueba1 | /ejercicios clase dos 2/caracteresAa.py | 337 | 3.921875 | 4 | print("programa que calcula la longitud de la cadena de texto y las veces que aparece la letra a")
cadena = input("ingresa tu cadena de texto o frace " )
largoCadena = len(cadena)
contarA= cadena.upper().count("A")
print("la longitud de tu cadena de texto es {}, y aparece la letra A en tu cadena {} veces.".format(largoCadena,contarA))
|
d0bb52faad6b72afc7c6058ad478fcb814d74e0b | TerryAg/code1161 | /Tblock.py | 1,005 | 3.8125 | 4 | import turtle
import random
# Describe this function...
def draw_T():
global x, y
turtle.goto(x,y)
turtle.pendown()
turtle.color('#%06x' % random.randint(0, 2**24 - 1))
draw_base()
turtle.right(90)
turtle.forward(100)
draw_top()
turtle.penup()
# Describe this function...
def draw_base():
turtle.begin_fill()
turtle.left(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(10)
turtle.right(90)
turtle.forward(100)
turtle.right(90)
turtle.forward(10)
turtle.end_fill()
# Describe this function...
def draw_top():
turtle.begin_fill()
turtle.right(90)
turtle.forward(75)
turtle.left(90)
turtle.forward(10)
turtle.left(90)
turtle.forward(140)
turtle.left(90)
turtle.forward(10)
turtle.left(90)
turtle.forward(65)
turtle.end_fill()
# Describe this function...
def move_cursor():
global x, y
x = random.randint(-200, 200)
y = random.randint(-200, 200)
x = 0
y = 0
turtle.speed(10)
for count in range(100):
draw_T()
move_cursor() |
914b31cebd8156783ca86e3cefd13f70f387e111 | nidiamarquez13/plataforma_digital | /PYTHON/ejercicio008.py | 777 | 4.34375 | 4 | """
STRING y mas!
"""
esto_es_una_string = "Hola"
esto_es_otra_string = "Mundo"
#Concatenar
print(esto_es_una_string +' '+ esto_es_otra_string)
#hola mundo
#MAYUS
print (esto_es_una_string.upper())
#minus
print (esto_es_una_string.lower())
#Primera Mayuscula
print (esto_es_una_string.capitalize())
#Poner mayuscula en cada palabra
print (esto_es_una_string.title())
#me dice la longitud
print(len(esto_es_una_string))
#buscar una caracter y muestra su ubicacion en indice
print(esto_es_una_string.find('l'))
#Imprimir solo la primera letra SLICE
print(esto_es_una_string[0:2]) # ho tu le dices que inicie en cero
print(esto_es_una_string[:2]) # ho asume que inicia en cero
print(esto_es_una_string[3:4]) #
#Radar poner al reves una palabra
print(esto_es_una_string[::-1])
|
6b0dc222dcb6815806c73f592b163f454d48619e | IlyaChebanu/machine-learning | /k-means-1.py | 867 | 3.609375 | 4 | import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
from sklearn.cluster import KMeans
style.use('ggplot')
# Some arbitrary points that can be easily formed into groups
X = np.array([[1, 2],
[1.5, 1.8],
[5, 8],
[8, 8],
[1, 0.6],
[9, 11]])
# Define the classifier to use
clf = KMeans(n_clusters=2)
# Train the classifier
clf.fit(X)
# Get the coordinates for the centroids
centroids = clf.cluster_centers_
# Get the label IDs for colouring
labels = clf.labels_
# List of colours
colors = ['g.', 'r.', 'c.', 'b.', 'k.']
# For each feature, plot the point and colour it with the label colour
for i in range(len(X)):
plt.plot(X[i][0], X[i][1], colors[labels[i]], markersize=25)
# Plot the centroids with an x
plt.scatter(centroids[:,0], centroids[:,1], marker='x', s=150, linewidths=5)
# Draw the plot
plt.show() |
9e6f5fc23518883a28137fd256dd0dd8837b541c | MarcosRibas/Projeto100Exercicios | /Python/ex081.py | 649 | 4.09375 | 4 | '''
Ex081 Crie um programa que vai ler vários números e colocar em uma lista. Depois disso mostre:
a) Quantos números foram digitados.
b) A lista de valores de forma decrescente.
c) Se o valor 5 foi digitado e está ou não na lista
'''
list = []
while True:
n = int(input('Digite um número: '))
list.append(n)
next = str(input('Quer continuar?[s/n] ')).lower().strip()
if next == 'n':
break
print(f'Sua lista tem {len(list)} itens')
list.sort(reverse=True)
print(f'Os númeroas listados em ordem decrescente: {list}')
if 5 in list:
print('O valor 5 está na lista')
else:
print('O valor 5 não está na lista') |
c24a1055bce8c053b4fb7c249a19d794c554009f | huisai/Learning-Data-Mining-with-Python | /流畅的Python/C2.4+5.py | 747 | 3.671875 | 4 | """
Created on Mon Apr 9 14:46:18 2018
<流畅的Python2.4+5>
@author: Ethan
"""
#1-切片和区间忽略最后一个元素:;
# 快速返回元素个数
range(3)
# 后一个坐标减去前一个坐标即为切片长度
len = stop - start
# 利用任意一个坐标将序列分为两个不相重叠的两部分
my_list[:x]
my_list[x:]
#2-对切片进行赋值
l = list(range(10))
l[2:5] = [20]
del l[5:7]
#报出异常,此处仅可以赋值可迭代对象
l[2:5] = 100
l[2:5] = [100]
#3-对列表使用+和*
#当操作对象的引用时,引起注意,以嵌套列表为例
#正常使用
board=[['_'] * 3 for i in range(3)]
board[1][2]='X'
#三个列表的最后一个元素均为'X'
weird_board = [['_']*3] * 3
weird_board[1][2] = 'X'
|
a914b1311076bc74f29049639af2e66bbdb8e88f | Eudasio-Rodrigues/Linguagem-de-programacao | /lista aula 07/questao 06.py | 298 | 4.125 | 4 | #Escreva uma função que receba como argumento uma lista e uma tupla
#e retorne um set composto pelas duas coleções.
lista = [x for x in range(0,11)]
tupla = ('eudasio',"mombaca",27)
def converte_set(lista,tupla):
a = set(lista)
b = set(tupla)
print(a|b)
converte_set(lista,tupla) |
315e4b278d7404e489330fc0ff1f401c0e36cc03 | DanielXuuuuu/AI_Principle | /hw2/Sudoku_Solver/BT.py | 1,035 | 3.609375 | 4 | # back-tracking (Constraint Satisfaction Problem, CSP)
def is_repeat(puzzle, row, col, num):
for i in range(9):
if puzzle[row][i] == num:
return True
for i in range(9):
if puzzle[i][col] == num:
return True
block_x = int(row / 3) * 3
block_y = int(col / 3) * 3
for i in range(block_x, block_x + 3):
for j in range(block_y, block_y + 3):
if puzzle[i][j] == num:
return True
return False
def solve_puzzle(puzzle, row, col):
if row > 8:
return True
if puzzle[row][col] == 0:
for i in range(1, 10):
if not is_repeat(puzzle, row, col, i):
puzzle[row][col] = i
if solve_puzzle(puzzle, int(row + (col + 1) / 9), (col + 1) % 9):
return True
puzzle[row][col] = 0
else:
if solve_puzzle(puzzle, int(row + (col + 1) / 9), (col + 1) % 9):
return True
return False |
b1accb3e1d2ec4593f5e1d65c5c403bdb28cb18e | Naysla/Machine_Learning | /1_Python_/Example_Comprehension_dictionary.py | 371 | 3.75 | 4 | #Practice from datacamp course: Phyton Data Science Tollbox
# Create a list of strings: fellowship
fellowship = ['hi', 'this', 'is', 'an', 'example']
# Create dict comprehension: new_fellowship
new_fellowship = {member:len(member) for member in fellowship}
# Print the new dictionary
print(new_fellowship)
#Result
#{'hi': 2, 'this': 4, 'is': 2, 'an': 2, 'example': 7} |
aabbb164733f55499d87ec9a03804e32b76c15e2 | anvarknian/preps | /Arrays/sorting/selection_sort.py | 377 | 3.921875 | 4 | value1 = 5
value2 = 7
array = [1, 2, 3, 4, 5, 6]
unsorted_array = [1, 2, 3, 4, 5, 6, 4, 3, 2, 6, 7, 8, 0]
def selection_sort(A):
for i in range(len(A)):
min_idx = i
for j in range(i + 1, len(A)):
if A[min_idx] > A[j]:
min_idx = j
A[i], A[min_idx] = A[min_idx], A[i]
return A
print(selection_sort(unsorted_array))
|
32cf300e0a5a4459051ba1b052258a07354a6b66 | casjunior93/Introdu--o-ao-Python---DIO | /aula4-for.py | 258 | 3.703125 | 4 | #numeros primos
#itera de 1 até 101
for num in range(101):
#verifica se o número é primo
div = 0
for x in range(1, num+1):
resto = num % x
if resto == 0:
div += 1
if div == 2:
print('{}'.format(num))
|
58f33eba851006188bba21a86bbf119d84569a4e | parayc/FaceTrack_UE4 | /pythonScripts/knn.py | 608 | 3.578125 | 4 |
from sklearn.neighbors import KNeighborsClassifier
import numpy as np
import pandas as pd
import csv as csv
def buildKNN(file,PCA=False):
df = pd.read_csv(file, header=0)
# Store the id column before dropping it
id_column =df["id"]
# Drop it from th
df = df.drop(["id"],axis=1)
# Convert to usable format
train_data = df.values
# Initialize KNN
neigh =KNeighborsClassifier()
neigh.fit(train_data[0::,1::],train_data[0::,0])
return neigh
def buildKNN_PCA():
""" This uses PCA to build KNN, after reading an article explaining
the pitfalls that larger values might cause."""
print "done" |
11c3081a6050aa729fd9d3d562bb63b423c68b8c | git-1024/Python | /Python/diffPythonHtml01.py | 918 | 3.53125 | 4 | #!/usr/local/env python
# -*- coding: utf-8 -*-
import difflib
import sys
try:
textfile1=sys.argv[1]
textfile2=sys.argv[2]
except Exceptions,e:
print "Error:"+str(e)
print "Usage:diffPythonHtml01.py filename1 filename2"
sys.exit()
def readfile(filename):
try:
fileHandle = open(filename,'rb')
text=fileHandle.read().splitlines() #读取后以行进行分隔
fileHandle.close()
return text
except IOError as error:
print('Read file Error:'+str(error))
sys.exit()
if textfile1=="" or textfile2=="":
print "Usage:diffPythonHtml01.py filename1 filename2"
sys.exit()
text1_lines = readfile(textfile1) #调用readfile函数,获取分隔后的字符串
text2_lines = readfile(textfile2)
d = difflib.HtmlDiff() #创建HtmlDiff()类对象
print d.make_file(text1_lines, text2_lines) #通过make_file方法输出html格式对比结果
|
519abf741da9d46e9c52a718bca6655831de1ad4 | DominikaJastrzebska/PyLadies-projects | /Volume of cuboid.py | 498 | 4.03125 | 4 | a = float(input('Enter the side a of the cuboid: '))
b = float(input('Enter the side b of the cuboid: '))
H = float(input('Enter the height H of the cuboid: '))
V = a*b*H
if a != b and a != H and b != H:
classification = ''
if (a == b and a != H) or (a == H and b != H) or (b == H and a != H):
classification = 'The base of cuboid is square.'
elif a == b and b == H and a == H:
classification = 'Cuboid is a cube'
print('Volume of cuboid is: ', str(V), classification)
|
34ba42316d825ba29f164f51d16c02cce47c77b0 | jorgeg73/PythonPro | /numeros al azar.py | 200 | 3.625 | 4 | import random
#numeros al azar
print "Numeros al Azar"
print random.random()
print "Da el rango:\n"
enum= input ("Primer rango\n")
enum1 = input ("Segundo Rango\n")
print random.randint(enum,enum1) |
c15ca359fa54695fd220d37ebba97db2c86ade69 | GavinAlison/python-learning | /06/consumer.py | 1,179 | 3.578125 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/1/2 21:31
# @Author : alison
# @File : consumer.py
# 协程
# 协程看上去也是子程序,但执行过程中,在子程序内部可中断,然后转而执行别的子程序,在适当的时候再返回来接着执行。
#
# 注意,在一个子程序中中断,去执行其他子程序,不是函数调用,有点类似CPU的中断。比如子程序A、B:
#
# 协程本质
# Python对协程的支持是通过generator实现的。
# 在generator中,我们不但可以通过for循环来迭代,还可以不断调用next()函数获取由yield语句返回的下一个值。
# 但是Python的yield不但可以返回一个值,它还可以接收调用者发出的参数。
def consumer():
r = ''
while True:
n = yield r
if not n:
return
print('[CONSUMER] Consuming %s...' % n)
r = '200 OK'
def produce(c):
c.send(None)
n = 0
while n < 5:
n = n + 1
print('[PRODUCER] Producing %s...' % n)
r = c.send(n)
print('[PRODUCER] Consumer return: %s' % r)
c.close()
c = consumer()
produce(c) |
af03b6cc9b6507c3f751a4aa18c8760e31e0ca26 | JoaoFiorelli/ExerciciosCV | /Ex003.py | 131 | 3.90625 | 4 | n1 = int(input('Digite um número: '))
n2 = int(input('Digite outro número: '))
n = n1 + n2
print('A soma desses número é ',n)
|
425b9277016f9297a02943ef3aa1ef9b55025572 | karanpathak/SPOJ | /CANDY3.py | 147 | 3.6875 | 4 | t=input()
for _ in xrange(t):
s=raw_input()
n=input()
sum=0
for _a in xrange(n):
sum+=input()
if sum%n==0:
print "YES"
else:
print "NO" |
82cc540a4314db5aa0f17a1b664936bb7390410b | Ranxf/laonanhai | /day3/3-11 func_demo2.py | 834 | 3.84375 | 4 | """
为什么要使用函数:减少重复代码;使程序变得可扩展;使程序变得易维护
日志文件处理(框架搭建必须有的)
"""
import time
def logger():
time_format = '%Y-%m-%d %X' # 年月日,时分秒
time_current = time.strftime(time_format)
with open('a.txt', 'a+') as f:
f.write('%s end action\n' % time_current) # 类似写日志文件
# 模拟一个功能,并将日志文件写入日志文件
def test1():
"""文档描述"""
print('in the test1') # 日志追加
logger() # 写入日志
# 模拟另外一个功能
def test2():
print('in the test2') # 日志描述
logger() # 写入日志
# 模拟第三个功能
def test3():
print('in the test3')
logger() # 写入日志
# 调用各个功能模块
test1()
test2()
test3()
|
b0e1aa14fb4b68f97b7d10ec15d402e985eb884f | dianafa/coding_tasks_python | /karate-chop/binary_search3.py | 1,054 | 3.515625 | 4 | import unittest
def search(x, tab):
return find(x, tab, 0, len(tab) - 1)
def find(x, tab, start, end):
if end < start:
return -1
if end == start:
if tab[end] == x:
return end
else:
return -1
pivot = (start + end) / 2
if x < tab[pivot]:
return find(x, tab, start, pivot)
if x > tab[pivot]:
return find(x, tab, pivot + 1, end)
return pivot
def test_search():
assert search(3, []) == -1
assert search(3, [1]) == -1
assert search(1, [1]) == 0
assert search(1, [1, 3, 5]) == 0
assert search(3, [1, 3, 5]) == 1
assert search(5, [1, 3, 5]) == 2
assert search(0, [1, 3, 5]) == -1
assert search(2, [1, 3, 5]) == -1
assert search(4, [1, 3, 5]) == -1
assert search(6, [1, 3, 5]) == -1
assert search(1, [1, 3, 5, 7]) == 0
assert search(3, [1, 3, 5, 7]) == 1
assert search(5, [1, 3, 5, 7]) == 2
assert search(7, [1, 3, 5, 7]) == 3
assert search(0, [1, 3, 5, 7]) == -1
assert search(2, [1, 3, 5, 7]) == -1
assert search(4, [1, 3, 5, 7]) == -1
assert search(6, [1, 3, 5, 7]) == -1
assert search(8, [1, 3, 5, 7]) == -1 |
388c3fadc989725441e616f78054122c34de9d85 | sujith1919/TCS-Python | /puzzle.py | 771 | 3.8125 | 4 | #puzzle
board=[3,5,4,1,0,2,6,7,8]
validmoves={0:(1,3),1:(0,2,4),2:(1,5),3:(0,4,6),
4:(1,3,5,7),5:(4,2,8),6:(3,7),7:(4,6,8),8:(5,7)}
def PrintBoard():
print board[0],board[1],board[2]
print board[3],board[4],board[5]
print board[6],board[7],board[8]
def GetMove():
return int(raw_input("\n Enter move : "))
def GetPosition(num):
return (board.index(num))
def solved():
if board==[1,2,3,4,5,6,7,8,0]:
return True
else:
return False
while True:
PrintBoard()
Move=GetMove()
MovePosition= GetPosition(Move)
ZeroPosition= GetPosition(0)
#check for valid move
if MovePosition in validmoves[ZeroPosition]:
#swap positions
board[ZeroPosition]=Move
board[MovePosition]=0
if solved():
print "Congratulations"
break
|
00b437101a71858975daabd4dad1ac867f1a0265 | nguyenphuclan/Sorting-and-Searching | /binarySearch.py | 535 | 3.84375 | 4 | def binary(myItem, mylist):
bot = 0
top = len(mylist) - 1
found = False
while bot <= top and not found:
middle = (bot + top) // 2
if mylist[middle] == myItem:
found = True
elif mylist[middle] < myItem:
bot = middle + 1
else:
top = middle -1
return found
if __name__ == "__main__":
numberList = [2, 5, 7, 9, 34, 76, 91, 186, 868]
item = int(input("Hay nhap so ban muon tim: "))
isFound = binary(item, numberList)
if isFound:
print("So cua ban co trong danh sach")
else:
print("So cua ban ko co trong ds") |
58b80867d306a44d223410adabdbec2ea91b2663 | WiPeK/python | /python_challenging/question11.py | 193 | 3.5625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#podzielne przez 5
inp = [x for x in input().split(",")]
res = []
for i in inp:
if int(i, 2) % 5 == 0:
res.append(str(i))
print (",".join(res)) |
ebff0801fcd35de67bfe2c78b1718011dc3381ed | namratab94/LeetCode | /reorder_log_files.py | 1,198 | 3.609375 | 4 | '''
Problem Number: 937
Difficulty level: Easy
Link: https://leetcode.com/problems/reorder-log-files/
Author: namratabilurkar
'''
'''
Input: ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"]
Output: ["g1 act car","a8 act zoo","ab1 off key dog","a1 9 2 3 1","zo4 4 7"]
'''
class Solution:
def reorderLogFiles(self, logs):
"""
:type logs: List[str]
:rtype: List[str]
"""
# Objective is to define a custom sorter.
'''
GIVEN SOLUTION:
def f(log):
id_, rest = log.split(" ", 1)
return (0, rest, id_) if rest[0].isalpha() else (1,)
return sorted(logs, key = f)
'''
digits = []
letters = []
# dividing the logs into two parts, one for digits and another for letters
for log in logs:
if log.split()[1].isdigit():
digits.append(log)
else:
letters.append(log)
letters.sort(key=lambda x: x.split()[0]) # Sort based on the identifier when there is a clash in the letters
letters.sort(key=lambda x: x.split()[1:])
result = letters + digits
return result |
756a094761a5c4bc91feca712e305a5d2051a2bd | mlmldata/raspi_tempProbe | /mug_temp.py | 1,319 | 4.28125 | 4 | '''
Write a program that measures and records temperature temperatures using the
raspberry pi and the attached temperature sensor.
'''
import tempProbe as tp # This is the library for the TempProbe class that we will use
import numpy as np
# This code will create and initialize an instance of an object called probe from the TempProbe class.
probe = tp.TempProbe()
# We will use the get_temp() function from the probe object to return a temperature
probe.get_temp()
# 1. Write a program that prints the current time and temperature together
# on one line
#
# hint: the following command will return the current time:
#
# np.datetime64('now')
# 2. Write a function that writes data to a text file that can be easily
# read later with pandas, including column headers.
#
# hint: the following code creates a text file that contains two lines.
#
# f = open('testfile.txt','w')
# f.write('a\nb')
# f.close()
# 3. Test the temperature sensor - place the temperature sensor in a cup
# of warm water and let it adjust to its surroundings. Then place the
# sensor in a cup of cold water. Record the data for a minute or two.
# 4. Analyze the data to estimate how long it takes to adjust. This can be
# done in a Jupyter Notebook on your own computer. Compare your estimate
# with another group.
|
68db3b7d4610eb3411f59271af19eca1722c74d5 | zuobing1995/tiantianguoyuan | /第一阶段/day02/exercise/birthday.py | 308 | 4.03125 | 4 | # 1. 今天是小明的20岁生日, 假设每年有365天,
# 计算它过了多少个星期天,余多少天(不要求精确)
# print('它过了', 20 * 365 // 7, '个星期天')
# print("余", 20 * 365 % 7, '天')
days = 20 * 365
print('它过了', days // 7, '个星期天')
print("余", days % 7, '天')
|
1cb4beb79b6a8cac38a4b8677200619d6f543751 | Banjiushi/wujiuDict | /wujiuDict.py | 1,196 | 3.75 | 4 | from tkinter import Tk, Button, Entry, Label, Text, END
from main import main, getInfo
class Application:
def __init__(self):
# 主窗口
self.window = Tk()
self.window.title('无咎词典')
self.window.geometry("280x350+500+200")
# 输入框
self.entry = Entry(self.window)
# pack grid place
self.entry.place(x=10, y=10, width=200, height=25)
# 查询按钮
self.submit_btn = Button(self.window, text='查询', command=self.submit)
self.submit_btn.place(x=220, y=10, width=50, height=25)
# 翻译标签
self.label = Label(self.window, text='翻译结果:')
self.label.place(x=10, y=40)
# 显示框
self.text = Text(self.window, background='#ccc')
self.text.place(x=10, y=65, width=260, height=275)
def run(self):
self.window.mainloop()
def submit(self):
content = self.entry.get() # 读取输入框中的数据
rs = main(content)
self.text.delete(1.0, END) # 清除输出框
self.text.insert(END, rs) # 在输出框中显示数据
if __name__ == '__main__':
app = Application()
app.run() |
12db01a1e965c3d0127dbfea941e2d8e03a8dd6d | abhishekkrsaw/Online-gas-booking-System | /register.py | 3,030 | 3.5 | 4 | from tkinter import *
from tkinter import messagebox
def back():
window.destroy()
import interface
def validation():
if v1.get()=='':
messagebox.showwarning('Error!!','Please enter your First Name!!')
elif v2.get()=='':
messagebox.showwarning('Error!!','Please enter your Last Name!!')
elif v3.get()=='':
messagebox.showwarning('Error!!','Please enter your Mobile Number!!')
elif len(v3.get())!=10:
messagebox.showwarning('Error!!','Please enter valid Mobile Number!!')
elif v4.get()=='':
messagebox.showwarning('Error!!','Please enter your Email Id!!')
elif '@' not in v4.get() or '.com' not in v4.get():
messagebox.showwarning('Error!!','Please enter valid Email Id!!')
else:
f=open('data.txt','a')
f.write('\n')
f.write(v1.get())
f.write(' ')
f.write(v2.get())
f.write(' ')
f.write(v3.get())
f.write(' ')
f.write(v4.get())
f.close()
f=open('show.txt','w')
f.write('\n')
f.write(v1.get())
f.write(' ')
f.write(v2.get())
f.write(' ')
f.write(v3.get())
f.write(' ')
f.write(v4.get())
f.close()
messagebox.showinfo('Thank You', 'You are now registered')
window.destroy()
import interface
window=Tk()
window['bg']='pink'
window.geometry('500x600')
frame=Frame(window,bg='pink')
frame.pack(pady=20)
head=Label(frame,text='New LPG Connection',font=('algerian',20,'underline','bold'),bg='pink',fg='dark blue')
head.grid()
frame0=Frame(window,bg='pink')
frame0.pack()
j=PhotoImage(file='LPG.png')
j=j.subsample(5)
image1=Label(frame0,image=j)
image1.grid(row=1)
frame1=Frame(window,bg='pink')
frame1.pack()
l1=Label(frame1,text="First Name",bg='pink',font=('calibri',12,'bold'))
l1.grid(row=2,pady=10)
v1=StringVar()
e1=Entry(frame1,textvariable=v1)
e1.grid(row=3,ipadx=20)
l2=Label(frame1,text="Last Name",bg='pink',font=('calibri',12,'bold'))
l2.grid(row=4,pady=10)
v2=StringVar()
e2=Entry(frame1,textvariable=v2)
e2.grid(row=5,ipadx=20)
l3=Label(frame1,text="Mobile Number",bg='pink',font=('calibri',12,'bold'))
l3.grid(row=6,pady=10)
v3=StringVar()
e3=Entry(frame1,textvariable=v3)
e3.grid(row=7,ipadx=20)
l4=Label(frame1,text="Email",bg='pink',font=('calibri',12,'bold'))
l4.grid(row=8,pady=10)
v4=StringVar()
e4=Entry(frame1,textvariable=v4)
e4.grid(row=9,ipadx=20)
frame5=Frame(window,bg='pink')
frame5.pack(ipady=10)
button=Button(frame5,text="Register",font=('arial',16,'bold'),activebackground='red',
bg='light blue',command=validation,cursor='hand2')
button.grid(row=1,column=2,ipadx=30,ipady=8,pady=50,padx=10)
button1=Button(frame5,text="Back",font=('arial',16,'bold'),activebackground='red',
bg='light blue',command=back,cursor='hand2')
button1.grid(row=1,column=1,ipadx=40,ipady=8,pady=50,padx=30)
|
d9a85c435ad766b2bccb3e523e0cc4ebae22141e | Tanmay53/cohort_3 | /submissions/sm_103_apoorva/week_13/day_4/count_vowels.py | 255 | 3.765625 | 4 | userInput = list(input("Enter values of list with space between: ").split())
print(userInput)
vowels = ["A","E","I","O","U","a","e","i","o","u"]
count = 0
for i in userInput:
for j in i:
if j in vowels:
count += 1
print(count)
|
9746c4f6b92251f42c09eb39a72b0ae207be31f7 | sunxinzhao/LeetCode_subject | /simple/number/202.py | 1,362 | 4.03125 | 4 | # coding=utf-8
'''
编写一个算法来判断一个数是不是“快乐数”。
一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。
示例:
输入: 19
输出: true
解释:
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/happy-number
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
'''
class Solution(object):
def isHappy(self, n):
"""
:type n: int
:rtype: bool
"""
list_data = []
while n != 1:
num = 0 # 记录当前数按位平方和之后的值
num1 = n # 分解num1求和是的值
while num1:
num += (num1 % 10) * (num1 % 10)
num1 = num1 / 10
n = num
print(n)
if n not in list_data:
list_data.append(n)
else:
return False
return True
if __name__ == '__main__':
print(Solution().isHappy(999999999))
|
755c53f29d56f0cf9645229d3dd2689f81c1cef1 | SureshUppelli/Python-Scripts | /test.py | 142 | 4.1875 | 4 | val = input ("Enter String: ")
rev = val [::-1]
if val == rev:
print ("String is palindrome")
else:
print ("String is not Palindrome") |
a756a0ead6ef1dfd8d7c9a11845808faa886e348 | suyundukov/LIFAP1 | /TD/TD2/Code/Python/5.py | 375 | 3.953125 | 4 | #!/usr/bin/python
# Tester si un entier choisi par USER est multiple de 5 ou de 7
print('Donne moi une valeur : ', end='')
a = int(input())
if (a % 5 == 0) and (a % 7 == 0):
print('C\'est le multiple de 5 et de 7')
elif a % 5 == 0:
print('C\'est le multiple de 5')
elif a % 7 == 0:
print('C\'est le multiple de 7')
else:
print('C\'est ni l\'un ni l\'autre')
|
6958d64ab507252e7adbedec1dc11089a1b432ef | ShiftingNova/bars | /lab.py | 289 | 3.6875 | 4 | # Jordan Walker CSC110 this code takes an imput and creates a bar thing and puts # on the left side of the bar
code = str(input("Enter bar string:\n"))
print("+---------+")
i = 0
while i<len(code):
print("|"+ "#" * int(code[i]) + " " * (9-int(code[i])) + "|")
i = i +1
print("+---------+")
|
ff12a1c6756c31988c8f4d422e96086fc75ee8d2 | moneymashi/SVN_fr.class | /pythonexp/a01_start/a15_tuple.py | 654 | 3.65625 | 4 | '''
Created on 2017. 7. 19.
@author: kitcoop
Tuple : 읽기 전용 - 리스트 보다 속도 빠름.
'''
t1 = "a", "b", "c","a"
t2 = ("a", "b", "c","a")
t3 = (1, 2, 3,4)
print(t1,t2)
print(t1, t1*2, len(t1), t1.count("a"), t1.index("b"))
print(t3, t3*2, len(t3))
p =(1,2,3)
# p[1]=20 수정 불가
''' 튜플데이터를 list으로 변경'''
q=list(p)
print(q)
q[1] = 20
print(q)
''' 형변환 '''
p = tuple(q)
print(p)
from urllib.parse import urlparse
a = 'http://www.naver.com:80/index.html'
print(a)
re = urlparse(a)
print(re)
print(re.netloc)
from urllib.parse import urlunparse
re2 = urlunparse(re)
print(re2)
|
ebcaa344f5afd6b1482d8746d37bfc626737c352 | harrygraham/DeepLearning-CreditCardFraud | /simple_logistic_regression.py | 2,842 | 3.703125 | 4 | import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import itertools
def plot_confusion_matrix(cm, classes,
normalize=False,
title='Confusion matrix',
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=0)
plt.yticks(tick_marks, classes)
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
#print("Normalized confusion matrix")
else:
1#print('Confusion matrix, without normalization')
#print(cm)
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j],
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
data = pd.read_csv("creditcard.csv")
# Examine data
# print data.head()
# Print a plot of class balance
# classes = pd.value_counts(data['Class'], sort=True)
# classes.plot(kind = 'bar')
# plt.show()
# Normalise and reshape the Amount column, so it's values lie between -1 and 1
from sklearn.preprocessing import StandardScaler
data['norm_Amount'] = StandardScaler().fit_transform(data['Amount'].reshape(-1,1))
# Drop the old Amount column and also the Time column as we don't want to include this at this stage
data = data.drop(['Time', 'Amount'], axis=1)
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split, KFold, cross_val_score
from sklearn.metrics import confusion_matrix,precision_recall_curve,auc,roc_auc_score,roc_curve,recall_score,classification_report
# Call the logistic regression model with a certain C parameter
lr = LogisticRegression(C = 10)
# Assign variables x and y corresponding to row data and it's class value
X = data.ix[:, data.columns != 'Class']
y = data.ix[:, data.columns == 'Class']
# Whole dataset, training-test data splitting
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.3, random_state = 0)
# CROSS VALIDATION
scores = cross_val_score(lr, X_train, y_train, scoring='recall', cv=5)
print scores
print 'Recall mean = ', np.mean(scores)
lr.fit(X_train, y_train)
y_pred = lr.predict(X_test)
cm = confusion_matrix(y_test, y_pred)
class_names = [0,1]
plt.figure()
plot_confusion_matrix(cm, classes=class_names, title='Confusion matrix')
plt.show()
from sklearn.metrics import classification_report
print classification_report(y_test, y_pred)
|
08a8270831b2b6cf129fb2755338ceb84273eae7 | erikanni/physics-calc | /menudict.py | 497 | 3.609375 | 4 |
def func_a():
print("func a")
def func_b():
print("func b")
def func_c():
print("func c")
def func_d():
print("func d")
def main():
print('''
function a
function b
function c
function d
''')
menu_dict = {"a": func_a, "b": func_b, "c": func_c, "d": func_d}
answer = input("select function: ").lower()[0]
if answer in menu_dict:
menu_dict[answer]()
else:
print("No such function")
if __name__ == "__main__":
main() |
250a38503a3a3d55d4ca5098c1dca6d3d4c5f62b | MagicMoa/Learning-Python | /Dictionaries.py | 1,616 | 4.84375 | 5 | #Lesson 5: Dictionaries
#Dictionaries are groups of values that can be defined with key-value pairs
country = {'Name': 'Switzerland', 'Size': 'Small', 'Continent': 'Europe', 'Cities': ['Zurich', 'Basel']}
print (country)
print (country['Size']) #Can access the value for a specified key
print (country.get('Name')) #Alternative method, returns "none" for nonexistent key instead of error
print (country.get('Climate'))
print (country.get('Climate', 'Not Found')) #Specifies what to return for nonexistent key
#5.1: Adding and Updating Dictionary Entries
country['Climate'] = 'Temperate'
country['Name'] = 'Brazil'
print (country)
#As an alternative, update method allows us to change multiple entries at once
country.update({'Size':'Large', 'Continent':'South America', 'Cities':['Rio de Janeiro', 'Brasilia']})
print (country)
#5.2 Deleting Dictionary Entries
del country['Continent'] #Deletes a specific key
print(country)
brazilian_cities = country.pop('Cities') #Pops off specific value, which can then be assigned
print(brazilian_cities)
#5.3: Looping through Keys and Values in Dictionaries
country = {'Name': 'Switzerland', 'Size': 'Small', 'Continent': 'Europe', 'Cities': ['Zurich', 'Basel']}
print (len(country)) #Prints the dicitonary's length
print (country.keys()) #Prints the dictionary's keys
print (country.values()) #Prints the dictionary's values
print (country.items()) #Prints the dictionary's keys and values
for Item in country:
print (Item) #Without a method, a for loop will only print a dictionary's keys
for key, value in country.items():
print (key, value)
|
872a18feb16cd8cb315305fdb5aaffeca821d6b2 | dr-dos-ok/Code_Jam_Webscraper | /solutions_python/Problem_96/1877.py | 1,181 | 3.71875 | 4 | def should_add(s,p,ts):
if(p == 0):
return True,s
if(ts == 0):
return False,s
d = int(ts/3)
if(ts%3 == 0):
if(d >= p):
return True,s
elif (d+1 >= p) and (s>0):
return True,s-1
else:
return False,s
elif ((ts-1)%3 ==0):
if(d+1 >= p):
return True,s
else:
return False,s
else:
if(d+1 >= p):
return True,s
elif(d+2>=p) and (s>0):
return True,s-1
return False,s
def score_calc(n,s,p,ts):
sum = 0
for i in range(0,n):
flag,s = should_add( s, p, int(ts[i]) )
if(flag):sum=sum+1
return sum
file = open("b.txt","r")
raw = file.readlines()
final_score = ''
index = 0
for txt in raw:
if index==0:
nl = int(txt)
index=index+1
else:
result = txt.rstrip('\n').split(' ')
n = int(result[0])
s = int(result[1])
p = int(result[2])
ts = result[3:]
final_score = "Case #"+str(index)+": "+str(score_calc(n,s,p,ts))
print final_score
index = index+1 |
c216c5c95d36cee7842255a7e618d70856781a32 | ramson/randomImage | /LineCollection.py | 1,008 | 3.578125 | 4 | from Line import Line
from Point import Point
from random import randint
class LineCollection:
def __init__(self, max_lines, max_x, max_y):
self.__lines = []
self.__maximum_number_of_lines = max_lines
self.__max_x = max_x
self.__max_y = max_y
def get_lines(self):
return self.__lines
def add_line(self, point):
line = Line(point, self.__max_x, self.__max_y)
self.__lines.append(line)
def add_point_to_any_line(self):
size = len(self.__lines)
if size >= self.__maximum_number_of_lines:
size = size - 1
random = randint(0, size)
if random >= len(self.__lines):
# add point in new line
self.add_line(self.generate_random_point())
return
# add point to existing line
self.__lines[random].add_next_point()
def generate_random_point(self):
return Point.generate_random_point(self.__max_x, self.__max_y)
|
c5f71bbecb940ba9d2e3769e551877b99cf41e52 | VachaArraniry/python_portfolio | /inheritance.py | 888 | 3.84375 | 4 | class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def calculate_discount_price(self, discount):
return self.price - (self.price * (discount/100))
class Shoes(Product):
def __init__(self, name, price, brand, size, color):
Product.__init__(self, name, price)
self.brand = brand
self.size = size
self.color = color
class Book(Product):
def __init__(self, name, price, author, genre):
Product.__init__(self, name, price)
self.author = author
self.genre = genre
air_max = Shoes(name="Nike Air Max", price=4000000, brand="Nike", size=43, color="White")
python_book = Book(name="Python Book", price=2000, author="John", genre="Computer")
print(air_max.price)
print(python_book.author)
print(air_max.calculate_discount_price(50)) |
d98a58623db4f6883a06fde2cce02297a93cb650 | dahu1/core-scrapy-learning | /t1.py | 587 | 3.59375 | 4 | #!/usr/bin/python
#coding=utf-8
#author=dahu
import pprint,sys
reload(sys)
sys.setdefaultencoding('utf-8')
b='haha'
def file_size(name):
if name.endswith('g') or name.endswith("G"):
a=1000*1000*1000
elif name.endswith('m') or name.endswith("M"):
a=1000*1000
elif name.endswith('k') or name.endswith("K"):
a=1000
else:a=10
# b='lele'
print b
return float(name[:-1])*a
if __name__ == '__main__':
print file_size("150")
a=['hehe','haha']
print sum([len(i) for i in a])
a=['我爱你','hello']
print len("我爱你")
|
b093cd47bafb1651990639c5f71d521f64ab1fc9 | SongGithub/algorithm-data_structures | /tree.py | 6,793 | 4.09375 | 4 | """implementation of Binary Tree"""
class BinaryTreeNode(object):
def __init__(self, data, left=None, right=None, parent=None):
self.data = data
self.left = left
self.right = right
self.parent = parent
def __str__(self):
return str(self.data)
def get_data(self):
return self.data
def get_left(self):
return self.left
def get_right(self):
return self.right
def get_parent(self):
return self.parent
def set_left(self, left):
self.left = left
def set_right(self, right):
self.right = right
class BinaryTree(object):
"""implement a binary tree
Protocol:
any data has value less than value of its parent node
will be placed on the left child node. While the ones
greater, will be placed to the right child node
"""
def __init__(self):
self.root = None
self.tree_depth = int(0)
self.node_sum = int(0)
self.traverse_result = []
def insert(self, data):
new_node = BinaryTreeNode(data)
current_node = self.root
# print('begin inserting : ' + str(data))
if self.root:
# Determine left/right side should be chosen for the new node
fulfill_status = False
while not fulfill_status:
if data >= current_node.get_data():
if current_node.get_right():
# print('move to RIGHT, and dive to next level')
current_node = current_node.get_right()
else:
current_node.right = new_node
new_node.set_parent(current_node)
fulfill_status = True
else:
if current_node.get_left():
# print('move to LEFT, and dive to next level')
current_node = current_node.get_left()
else: # empty node slot found
current_node.left = new_node
new_node.set_parent(current_node)
fulfill_status = True
# 3. verify status on the current node
# print('Current parent node = ' + str(current_node.get_data()))
# print('Child status: '
# + 'left=' + str(current_node.get_left())
# + ' right=' + str(current_node.get_right()))
# print('new child\'s parent node is:' + str(new_node.get_parent()))
else:
# print('Building a new tree now, root = ' + str(data))
self.root = new_node
# print('Finishing inserting...' + '#' * 30)
def query_recursive(self, node, data):
# print ('beginning recursive querying data {}'.format(data))
found_status = False
if node:
if node.get_left():
self.query_recursive(node.get_left(), data)
if data == node.get_data():
found_status = True
print('Data Entry: {} is FOUND'.format(data))
if node.get_right():
self.query_recursive(node.get_right(), data)
return found_status or True
def delete(self, data):
"""there are 3 possible scenarios:
1. the node has no child
delete the node and mark its parent node that 'node.next = None'
2. the node has 1 child.
delete the node and re-connect its parent node with its child node
3. the node has 2 children
find the Smallest key in the node's Right sub-tree
replace the node with the Smallest key
"""
current_node = self.root
print('begin deleting data : {} '.format(data) + '#' * 50)
if self.root:
# Determine left/right side should be chosen for the new node
found_status = False
while not found_status:
if data == current_node.get_data():
parent_node_data = current_node.get_parent().get_data()
print('Parent Node is ' + str(parent_node_data))
current_node = current_node.get_parent()
if data >= parent_node_data:
current_node.set_right(None)
print ('removing RIGHT')
else:
current_node.set_left(None)
print('removing LEFT')
found_status = True
break
elif data > current_node.get_data():
if current_node.get_right():
# print('move to RIGHT, and dive to next level')
current_node = current_node.get_right()
else:
break # no existing node larger than the current node.
else:
if current_node.get_left():
# print('move to LEFT, and dive to next level')
current_node = current_node.get_left()
else:
break
if found_status:
print("The data entry: {} found and deleted ".format(str(data)) + '#' * 30)
# print('my parent node is ' + str(current_node.get_parent()))
else:
print("Attention! The data entry: {} is not found ".format(str(data)) + '#' * 30 + '\n')
return found_status
else:
print("Attention! The data entry: {} is not found because the tree doesn't exist ".format(str(data))
+ '#' * 30 + '\n')
return False
def traverse_inOrder(self, node):
result = []
def traverse_inOrder_worker(node):
"""Steps:
1 Go Left
2 Process current node
3 Go right"""
if node.get_data():
if node.get_left():
traverse_inOrder_worker(node.get_left())
# result.append(node.get_data())
result.append(node.get_data())
if node.get_right():
traverse_inOrder_worker(node.get_right())
traverse_inOrder_worker(node)
print(result)
if __name__ == '__main__':
INPUT_LIST = [50, 76, 21, 4, 32, 64, 15, 52, 14, 100, 83, 80, 2, 3, 70, 87]
b = BinaryTree()
for i in INPUT_LIST:
b.insert(i)
b.traverse_inOrder(b.root)
b.delete(3)
print(b.query_recursive(b.root, 4))
b.traverse_inOrder(b.root)
|
1402f9912860e1fbb84f1cde73c4d4283498f3e0 | SocioProphet/CodeGraph | /kaggle/python_files/sample851.py | 27,669 | 4.3125 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## How Autoencoders work - Understanding the math and implementation
#
# ### Contents
#
# <ul>
# <li>1. Introduction</li>
# <ul>
# <li>1.1 What are Autoencoders ? </li>
# <li>1.2 How Autoencoders Work ? </li>
# </ul>
# <li>2. Implementation and UseCases</li>
# <ul>
# <li>2.1 UseCase 1: Image Reconstruction </li>
# <li>2.2 UseCase 2: Noise Removal </li>
# <li>2.3 UseCase 3: Sequence to Sequence Prediction </li>
# </ul>
# </ul>
#
# <br>
#
# ## 1. Introduction
# ## 1.1 What are Autoencoders
#
# Autoencoders are a special type of neural network architectures in which the output is same as the input. Autoencoders are trained in an unsupervised manner in order to learn the exteremely low level repersentations of the input data. These low level features are then deformed back to project the actual data. An autoencoder is a regression task where the network is asked to predict its input (in other words, model the identity function). These networks has a tight bottleneck of a few neurons in the middle, forcing them to create effective representations that compress the input into a low-dimensional code that can be used by the decoder to reproduce the original input.
#
# A typical autoencoder architecture comprises of three main components:
#
# - **Encoding Architecture :** The encoder architecture comprises of series of layers with decreasing number of nodes and ultimately reduces to a latent view repersentation.
# - **Latent View Repersentation :** Latent view repersents the lowest level space in which the inputs are reduced and information is preserved.
# - **Decoding Architecture :** The decoding architecture is the mirro image of the encoding architecture but in which number of nodes in every layer increases and ultimately outputs the similar (almost) input.
#
# 
#
# A highly fine tuned autoencoder model should be able to reconstruct the same input which was passed in the first layer. In this kernel, I will walk you through the working of autoencoders and their implementation. Autoencoders are widly used with the image data and some of their use cases are:
#
# - Dimentionality Reduction
# - Image Compression
# - Image Denoising
# - Image Generation
# - Feature Extraction
#
#
#
# ## 1.2 How Autoencoders work
#
# Lets understand the mathematics behind autoencoders. The main idea behind autoencoders is to learn a low level repersenation of a high level dimentional data. Lets try to understand the encoding process with an example. Consider a data repersentation space (N dimentional space which is used to repersent the data) and consider the data points repersented by two variables : x1 and x2. Data Manifold is the space inside the data repersentation space in which the true data resides.
# In[ ]:
from plotly.offline import init_notebook_mode, iplot
import plotly.graph_objs as go
import numpy as np
init_notebook_mode(connected=True)
## generate random data
N = 50
random_x = np.linspace(2, 10, N)
random_y1 = np.linspace(2, 10, N)
random_y2 = np.linspace(2, 10, N)
trace1 = go.Scatter(x = random_x, y = random_y1, mode="markers", name="Actual Data")
trace2 = go.Scatter(x = random_x, y = random_y2, mode="lines", name="Model")
layout = go.Layout(title="2D Data Repersentation Space", xaxis=dict(title="x2", range=(0,12)),
yaxis=dict(title="x1", range=(0,12)), height=400,
annotations=[dict(x=5, y=5, xref='x', yref='y', text='This 1D line is the Data Manifold (where data resides)',
showarrow=True, align='center', arrowhead=2, arrowsize=1, arrowwidth=2, arrowcolor='#636363',
ax=-120, ay=-30, bordercolor='#c7c7c7', borderwidth=2, borderpad=4, bgcolor='orange', opacity=0.8)])
figure = go.Figure(data = [trace1], layout = layout)
iplot(figure)
# To repersent this data, we are currently using 2 dimensions - X and Y. But it is possible to reduce the dimensions of this space into lower dimensions ie. 1D. If we can define following :
#
# - Reference Point on the line : A
# - Angle L with a horizontal axis
#
# then any other point, say B, on line A can be repersented in terms of Distance "d" from A and angle L.
# In[ ]:
random_y3 = [2 for i in range(100)]
random_y4 = random_y2 + 1
trace4 = go.Scatter(x = random_x[4:24], y = random_y4[4:300], mode="lines")
trace3 = go.Scatter(x = random_x, y = random_y3, mode="lines")
trace1 = go.Scatter(x = random_x, y = random_y1, mode="markers")
trace2 = go.Scatter(x = random_x, y = random_y2, mode="lines")
layout = go.Layout(xaxis=dict(title="x1", range=(0,12)), yaxis=dict(title="x2", range=(0,12)), height=400,
annotations=[dict(x=2, y=2, xref='x', yref='y', text='A', showarrow=True, align='center', arrowhead=2, arrowsize=1, arrowwidth=2,
arrowcolor='#636363', ax=20, ay=-30, bordercolor='#c7c7c7', borderwidth=2, borderpad=4, bgcolor='orange', opacity=0.8),
dict(x=6, y=6, xref='x', yref='y', text='B', showarrow=True, align='center', arrowhead=2, arrowsize=1, arrowwidth=2, arrowcolor='#636363',
ax=20, ay=-30, bordercolor='#c7c7c7', borderwidth=2, borderpad=4, bgcolor='yellow', opacity=0.8), dict(
x=4, y=5, xref='x', yref='y',text='d', ay=-40),
dict(x=2, y=2, xref='x', yref='y', text='angle L', ax=80, ay=-10)], title="2D Data Repersentation Space", showlegend=False)
data = [trace1, trace2, trace3, trace4]
figure = go.Figure(data = data, layout = layout)
iplot(figure)
#################
random_y3 = [2 for i in range(100)]
random_y4 = random_y2 + 1
trace4 = go.Scatter(x = random_x[4:24], y = random_y4[4:300], mode="lines")
trace3 = go.Scatter(x = random_x, y = random_y3, mode="lines")
trace1 = go.Scatter(x = random_x, y = random_y1, mode="markers")
trace2 = go.Scatter(x = random_x, y = random_y2, mode="lines")
layout = go.Layout(xaxis=dict(title="u1", range=(1.5,12)), yaxis=dict(title="u2", range=(1.5,12)), height=400,
annotations=[dict(x=2, y=2, xref='x', yref='y', text='A', showarrow=True, align='center', arrowhead=2, arrowsize=1, arrowwidth=2,
arrowcolor='#636363', ax=20, ay=-30, bordercolor='#c7c7c7', borderwidth=2, borderpad=4, bgcolor='orange', opacity=0.8),
dict(x=6, y=6, xref='x', yref='y', text='B', showarrow=True, align='center', arrowhead=2, arrowsize=1, arrowwidth=2, arrowcolor='#636363',
ax=20, ay=-30, bordercolor='#c7c7c7', borderwidth=2, borderpad=4, bgcolor='yellow', opacity=0.8), dict(
x=4, y=5, xref='x', yref='y',text='d', ay=-40),
dict(x=2, y=2, xref='x', yref='y', text='angle L', ax=80, ay=-10)], title="Latent Distance View Space", showlegend=False)
data = [trace1, trace2, trace3, trace4]
figure = go.Figure(data = data, layout = layout)
iplot(figure)
# But the key question here is with what logic or rule, point B can be represented in terms of A and angle L. Or in other terms, what is the equation among B, A and L. The answer is straigtforward, there is no fixed equation but a best possible equation is obtained by the unsupervised learning process. In simple terms, the learning process can be defined as a rule / equation which converts B in the form of A and L. Lets understand this process from a autoencoder perspective.
#
# Consider the autoencoder with no hidden layers, the inputs x1 and x2 are encoded to lower repersentation d which is then further projected into x1 and x2.
#
# 
#
# <br>
# **Step1 : Repersent the points in Latent View Space**
#
# If the coordinates of point A and B in the data representation space are:
#
# - Point A : (x1A, x2A)
# - Point B : (x1B, x2B)
#
# then their coordinates in the latent view space will be:
#
# (x1A, x2A) ---> (0, 0)
# (x1B, x2B) ---> (u1B, u2B)
#
# - Point A : (0, 0)
# - Point B : (u1B, u2B)
#
# Where u1B and u2B can be represented in the form of distance between the point and the reference point
#
# u1B = x1B - x1A
# u2B = x2B - x2A
#
# **Step2 : Represent the points with distance d and angle L **
#
# Now, u1B and u2B can represented as a combination of distance d and angle L. And if we rotate this by angle L, towards the horizontal axis, L will become 0. ie.
#
# **=> (d, L)**
# **=> (d, 0)** (after rotation)
#
# This is the output of the encoding process and repersents our data in low dimensions. If we recall the fundamental equation of a neural network with weights and bias of every layer, then
#
# **=> (d, 0) = W. (u1B, u2B)**
# ==> (encoding)
#
# where W is the weight matrix of hidden layer. Since, we know that the decoding process is the mirror image of the encoding process.
#
# **=> (u1B, u2B) = Inverse (W) . (d, 0)**
# ==> (decoding)
#
# The reduced form of data (x1, x2) is (d, 0) in the latent view space which is obtained from the encoding architecture. Similarly, the decoding architecture converts back this representation to original form (u1B, u2B) and then (x1, x2). An important point is that Rules / Learning function / encoding-decoding equation will be different for different types of data. For example, consider the following data in 2dimentional space.
#
#
# ## Different Rules for Different data
#
# Same rules cannot be applied to all types of data. For example, in the previous example, we projected a linear data manifold in one dimention and eliminated the angle L. But what if the data manifold cannot be projected properly. For example consider the following data manifold view.
# In[ ]:
import matplotlib.pyplot as plt
import numpy as np
fs = 100 # sample rate
f = 2 # the frequency of the signal
x = np.arange(fs) # the points on the x axis for plotting
y = [ np.sin(2*np.pi*f * (i/fs)) for i in x]
plt.figure(figsize=(15,4))
plt.stem(x,y, 'r', );
plt.plot(x,y);
# In this type of data, the key problem will be to obtain the projection of data in single dimention without loosing information. When this type of data is projected in latent space, a lot of information is lost and it is almost impossible to deform and project it to the original shape. No matter how much shifts and rotation are applied, original data cannot be recovered.
#
# So how does neural networks solves this problem ? The intution is, In the manifold space, deep neural networks has the property to bend the space in order to obtain a linear data fold view. Autoencoder architectures applies this property in their hidden layers which allows them to learn low level representations in the latent view space.
#
# The following image describes this property:
#
# 
#
# Lets implement an autoencoder using keras that first learns the features from an image, and then tries to project the same image as the output.
#
# ## 2. Implementation
#
# ## 2.1 UseCase 1 : Image Reconstruction
#
# 1. Load the required libraries
#
# In[ ]:
## load the libraries
from keras.layers import Dense, Input, Conv2D, LSTM, MaxPool2D, UpSampling2D
from sklearn.model_selection import train_test_split
from keras.callbacks import EarlyStopping
from keras.utils import to_categorical
from numpy import argmax, array_equal
import matplotlib.pyplot as plt
from keras.models import Model
from imgaug import augmenters
from random import randint
import pandas as pd
import numpy as np
# ### 2. Dataset Prepration
#
# Load the dataset, separate predictors and target, normalize the inputs.
# In[ ]:
### read dataset
train = pd.read_csv("../input/fashion-mnist_train.csv")
train_x = train[list(train.columns)[1:]].values
train_y = train['label'].values
## normalize and reshape the predictors
train_x = train_x / 255
## create train and validation datasets
train_x, val_x, train_y, val_y = train_test_split(train_x, train_y, test_size=0.2)
## reshape the inputs
train_x = train_x.reshape(-1, 784)
val_x = val_x.reshape(-1, 784)
# ### 3. Create Autoencoder architecture
#
# In this section, lets create an autoencoder architecture. The encoding part comprises of three layers with 2000, 1200, and 500 nodes. Encoding architecture is connected to latent view space comprising of 10 nodes which is then connected to decoding architecture with 500, 1200, and 2000 nodes. The final layer comprises of exact number of nodes as the input layer.
# In[ ]:
## input layer
input_layer = Input(shape=(784,))
## encoding architecture
encode_layer1 = Dense(1500, activation='relu')(input_layer)
encode_layer2 = Dense(1000, activation='relu')(encode_layer1)
encode_layer3 = Dense(500, activation='relu')(encode_layer2)
## latent view
latent_view = Dense(10, activation='sigmoid')(encode_layer3)
## decoding architecture
decode_layer1 = Dense(500, activation='relu')(latent_view)
decode_layer2 = Dense(1000, activation='relu')(decode_layer1)
decode_layer3 = Dense(1500, activation='relu')(decode_layer2)
## output layer
output_layer = Dense(784)(decode_layer3)
model = Model(input_layer, output_layer)
# Here is the summary of our autoencoder architecture.
# In[ ]:
model.summary()
# Next, we will train the model with early stopping callback.
# In[ ]:
model.compile(optimizer='adam', loss='mse')
early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=1, mode='auto')
model.fit(train_x, train_x, epochs=20, batch_size=2048, validation_data=(val_x, val_x), callbacks=[early_stopping])
# Generate the predictions on validation data.
# In[ ]:
preds = model.predict(val_x)
# Lets plot the original and predicted image
#
# **Inputs: Actual Images**
# In[ ]:
from PIL import Image
f, ax = plt.subplots(1,5)
f.set_size_inches(80, 40)
for i in range(5):
ax[i].imshow(val_x[i].reshape(28, 28))
plt.show()
# **Predicted : Autoencoder Output**
# In[ ]:
f, ax = plt.subplots(1,5)
f.set_size_inches(80, 40)
for i in range(5):
ax[i].imshow(preds[i].reshape(28, 28))
plt.show()
# So we can see that an autoencoder trained with 20 epoochs is able to reconstruct the input images very well. Lets look at other use-case of autoencoders - Image denoising or removal of noise from the image.
#
# ## 2.2 UseCase 2 - Image Denoising
#
# Autoencoders are pretty useful, lets look at another application of autoencoders - Image denoising. Many a times input images contain noise in the data, autoencoders can be used to get rid of those images. Lets see it in action. First lets prepare the train_x and val_x data contianing the image pixels.
#
# 
# In[ ]:
## recreate the train_x array and val_x array
train_x = train[list(train.columns)[1:]].values
train_x, val_x = train_test_split(train_x, test_size=0.2)
## normalize and reshape
train_x = train_x/255.
val_x = val_x/255.
# In this autoencoder network, we will add convolutional layers because convolutional networks works really well with the image inputs. To apply convolutions on image data, we will reshape our inputs in the form of 28 * 28 matrix. For more information related to CNN, refer to my previous [kernel](https://www.kaggle.com/shivamb/a-very-comprehensive-tutorial-nn-cnn).
# In[ ]:
train_x = train_x.reshape(-1, 28, 28, 1)
val_x = val_x.reshape(-1, 28, 28, 1)
# ### Noisy Images
#
# We can intentionally introduce the noise in an image. I am using imaug package which can be used to augment the images with different variations. One such variation can be introduction of noise. Different types of noises can be added to the images. For example:
#
# - Salt and Pepper Noise
# - Gaussian Noise
# - Periodic Noise
# - Speckle Noise
#
# Lets introduce salt and pepper noise to our data which is also known as impulse noise. This noise introduces sharp and sudden disturbances in the image signal. It presents itself as sparsely occurring white and black pixels.
#
# Thanks to @ColinMorris for suggesting the correction in salt and pepper noise.
# In[ ]:
# Lets add sample noise - Salt and Pepper
noise = augmenters.SaltAndPepper(0.1)
seq_object = augmenters.Sequential([noise])
train_x_n = seq_object.augment_images(train_x * 255) / 255
val_x_n = seq_object.augment_images(val_x * 255) / 255
# Before adding noise
# In[ ]:
f, ax = plt.subplots(1,5)
f.set_size_inches(80, 40)
for i in range(5,10):
ax[i-5].imshow(train_x[i].reshape(28, 28))
plt.show()
# After adding noise
# In[ ]:
f, ax = plt.subplots(1,5)
f.set_size_inches(80, 40)
for i in range(5,10):
ax[i-5].imshow(train_x_n[i].reshape(28, 28))
plt.show()
# Lets now create the model architecture for the autoencoder. Lets understand what type of network needs to be created for this problem.
#
# **Encoding Architecture:**
#
# The encoding architure is composed of 3 Convolutional Layers and 3 Max Pooling Layers stacked one by one. Relu is used as the activation function in the convolution layers and padding is kept as "same". Role of max pooling layer is to downsample the image dimentions. This layer applies a max filter to non-overlapping subregions of the initial representation.
#
# **Decoding Architecture:**
#
# Similarly in decoding architecture, the convolution layers will be used having same dimentions (in reverse manner) as the encoding architecture. But instead of 3 maxpooling layers, we will be adding 3 upsampling layers. Again the activation function will be same (relu), and padding in convolution layers will be same as well. Role of upsampling layer is to upsample the dimentions of a input vector to a higher resolution / dimention. The max pooling operation is non-invertible, however an approximate inverse can be obtained by recording the locations of the maxima within each pooling region. Umsampling layers make use of this property to project the reconstructions from a low dimentional feature space.
#
#
# In[ ]:
# input layer
input_layer = Input(shape=(28, 28, 1))
# encoding architecture
encoded_layer1 = Conv2D(64, (3, 3), activation='relu', padding='same')(input_layer)
encoded_layer1 = MaxPool2D( (2, 2), padding='same')(encoded_layer1)
encoded_layer2 = Conv2D(32, (3, 3), activation='relu', padding='same')(encoded_layer1)
encoded_layer2 = MaxPool2D( (2, 2), padding='same')(encoded_layer2)
encoded_layer3 = Conv2D(16, (3, 3), activation='relu', padding='same')(encoded_layer2)
latent_view = MaxPool2D( (2, 2), padding='same')(encoded_layer3)
# decoding architecture
decoded_layer1 = Conv2D(16, (3, 3), activation='relu', padding='same')(latent_view)
decoded_layer1 = UpSampling2D((2, 2))(decoded_layer1)
decoded_layer2 = Conv2D(32, (3, 3), activation='relu', padding='same')(decoded_layer1)
decoded_layer2 = UpSampling2D((2, 2))(decoded_layer2)
decoded_layer3 = Conv2D(64, (3, 3), activation='relu')(decoded_layer2)
decoded_layer3 = UpSampling2D((2, 2))(decoded_layer3)
output_layer = Conv2D(1, (3, 3), padding='same')(decoded_layer3)
# compile the model
model_2 = Model(input_layer, output_layer)
model_2.compile(optimizer='adam', loss='mse')
# Here is the model summary
# In[ ]:
model_2.summary()
# Train the model with early stopping callback. Increase the number of epochs to a higher number for better results.
# In[ ]:
early_stopping = EarlyStopping(monitor='val_loss', min_delta=0, patience=10, verbose=5, mode='auto')
history = model_2.fit(train_x_n, train_x, epochs=10, batch_size=2048, validation_data=(val_x_n, val_x), callbacks=[early_stopping])
# Lets obtain the predictions of the model
# In[ ]:
preds = model_2.predict(val_x_n[:10])
f, ax = plt.subplots(1,5)
f.set_size_inches(80, 40)
for i in range(5,10):
ax[i-5].imshow(preds[i].reshape(28, 28))
plt.show()
# In this implementation, I have not traiened this network for longer epoochs, but for better predictions, you can train the network for larger number of epoochs say somewhere in the range of 500 - 1000.
#
# ## 2.3 UseCase 3: Sequence to Sequence Prediction using AutoEncoders
#
#
# Next use case is sequence to sequence prediction. In the previous example we input an image which was a basicaly a 2 dimentional data, in this example we will input a sequence data as the input which will be 1 dimentional. Example of sequence data are time series data and text data. This usecase can be applied in machine translation. Unlike CNNs in image example, in this use-case we will use LSTMs.
#
# Most of the code of this section is taken from the following reference shared by Jason Brownie in his blog post. Big Credits to him.
# - Reference : https://machinelearningmastery.com/develop-encoder-decoder-model-sequence-sequence-prediction-keras/
#
# #### Autoencoder Architecture
#
# The architecuture of this use case will contain an encoder to encode the source sequence and second to decode the encoded source sequence into the target sequence, called the decoder. First lets understand the internal working of LSTMs which will be used in this architecture.
#
# - The Long Short-Term Memory, or LSTM, is a recurrent neural network that is comprised of internal gates.
# - Unlike other recurrent neural networks, the network’s internal gates allow the model to be trained successfully using backpropagation through time, or BPTT, and avoid the vanishing gradients problem.
# - We can define the number of LSTM memory units in the LSTM layer, Each unit or cell within the layer has an internal memory / cell state, often abbreviated as “c“, and outputs a hidden state, often abbreviated as “h“.
# - By using Keras, we can access both output states of the LSTM layer as well as the current states of the LSTM layers.
#
# Lets now create an autoencoder architecutre for learning and producing sequences made up of LSTM layers. There are two components:
#
# - An encoder architecture which takes a sequence as input and returns the current state of LSTM as the output
# - A decoder architecture which takes the sequence and encoder LSTM states as input and returns the decoded output sequence
# - We are saving and accessing hidden and memory states of LSTM so that we can use them while generating predictions on unseen data.
#
# Lets first of all, generate a sequence dataset containing random sequences of fixed lengths. We will create a function to generate random sequences.
#
# - X1 repersents the input sequence containing random numbers
# - X2 repersents the padded sequence which is used as the seed to reproduce the other elements of the sequence
# - y repersents the target sequence or the actual sequence
#
# In[ ]:
def dataset_preparation(n_in, n_out, n_unique, n_samples):
X1, X2, y = [], [], []
for _ in range(n_samples):
## create random numbers sequence - input
inp_seq = [randint(1, n_unique-1) for _ in range(n_in)]
## create target sequence
target = inp_seq[:n_out]
## create padded sequence / seed sequence
target_seq = list(reversed(target))
seed_seq = [0] + target_seq[:-1]
# convert the elements to categorical using keras api
X1.append(to_categorical([inp_seq], num_classes=n_unique))
X2.append(to_categorical([seed_seq], num_classes=n_unique))
y.append(to_categorical([target_seq], num_classes=n_unique))
# remove unnecessary dimention
X1 = np.squeeze(np.array(X1), axis=1)
X2 = np.squeeze(np.array(X2), axis=1)
y = np.squeeze(np.array(y), axis=1)
return X1, X2, y
samples = 100000
features = 51
inp_size = 6
out_size = 3
inputs, seeds, outputs = dataset_preparation(inp_size, out_size, features, samples)
print("Shapes: ", inputs.shape, seeds.shape, outputs.shape)
print ("Here is first categorically encoded input sequence looks like: ", )
inputs[0][0]
# Next, lets create the architecture of our model in Keras.
# In[ ]:
def define_models(n_input, n_output):
## define the encoder architecture
## input : sequence
## output : encoder states
encoder_inputs = Input(shape=(None, n_input))
encoder = LSTM(128, return_state=True)
encoder_outputs, state_h, state_c = encoder(encoder_inputs)
encoder_states = [state_h, state_c]
## define the encoder-decoder architecture
## input : a seed sequence
## output : decoder states, decoded output
decoder_inputs = Input(shape=(None, n_output))
decoder_lstm = LSTM(128, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_inputs, initial_state=encoder_states)
decoder_dense = Dense(n_output, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
## define the decoder model
## input : current states + encoded sequence
## output : decoded sequence
encoder_model = Model(encoder_inputs, encoder_states)
decoder_state_input_h = Input(shape=(128,))
decoder_state_input_c = Input(shape=(128,))
decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]
decoder_outputs, state_h, state_c = decoder_lstm(decoder_inputs, initial_state=decoder_states_inputs)
decoder_states = [state_h, state_c]
decoder_outputs = decoder_dense(decoder_outputs)
decoder_model = Model([decoder_inputs] + decoder_states_inputs, [decoder_outputs] + decoder_states)
return model, encoder_model, decoder_model
autoencoder, encoder_model, decoder_model = define_models(features, features)
# Lets look at the model summaries
# In[ ]:
encoder_model.summary()
# In[ ]:
decoder_model.summary()
# In[ ]:
autoencoder.summary()
# Now, lets train the autoencoder model using Adam optimizer and Categorical Cross Entropy loss function
# In[ ]:
autoencoder.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['acc'])
autoencoder.fit([inputs, seeds], outputs, epochs=1)
# Lets write a function to predict the sequence based on input sequence
# In[ ]:
def reverse_onehot(encoded_seq):
return [argmax(vector) for vector in encoded_seq]
def predict_sequence(encoder, decoder, sequence):
output = []
target_seq = np.array([0.0 for _ in range(features)])
target_seq = target_seq.reshape(1, 1, features)
current_state = encoder.predict(sequence)
for t in range(out_size):
pred, h, c = decoder.predict([target_seq] + current_state)
output.append(pred[0, 0, :])
current_state = [h, c]
target_seq = pred
return np.array(output)
# Generate some predictions
# In[ ]:
for k in range(5):
X1, X2, y = dataset_preparation(inp_size, out_size, features, 1)
target = predict_sequence(encoder_model, decoder_model, X1)
print('\nInput Sequence=%s SeedSequence=%s, PredictedSequence=%s'
% (reverse_onehot(X1[0]), reverse_onehot(y[0]), reverse_onehot(target)))
#
# ### Excellent References
#
# 1. https://www.analyticsvidhya.com/blog/2018/06/unsupervised-deep-learning-computer-vision/
# 2. https://towardsdatascience.com/applied-deep-learning-part-3-autoencoders-1c083af4d798
# 3. https://blog.keras.io/building-autoencoders-in-keras.html
# 4. https://cs.stanford.edu/people/karpathy/convnetjs/demo/autoencoder.html
# 5. https://machinelearningmastery.com/develop-encoder-decoder-model-sequence-sequence-prediction-keras/
#
#
# Thanks for viewing the kernel, **please upvote** if you liked it.
|
ee3e5ca9844fad8882a966777f08b1ba880222ba | mohamed-elsayed/python-scratch | /Iterator-generator.py | 7,280 | 4.53125 | 5 | # =================================================
################ Iterator/generator ###########
# =================================================
# Objectives
# Define Iterator and Iterable
# Understand the iter() and next() methods
# Build our own for loop
# Define what generators are and how they can be used
# Compare generator functions and generator expressions
# Use generators to pause execution of expensive functions
# Iterators ? Iterables ?
# Iterator - an object that can be iterated upon .
# An object which returns data, one element at a time when next() is called on it
# Iterable - An object which will return an iterator when iter() is called on it
# "Hello" is an iterable , but it is not an iterator.
# iter("Hello") returns an iterator.
name = "Operah"
# next(name) # TypeError: 'str' object is not iterator.
iter(name) # return an Iterator
it = iter(name)
# for char in "Operah"
# for loop behind the scene call iter() on the string "Operah" that return an iterator then for loop go through each item in the iterator using the next()
# when next() is called on an iterator, the iterator returns the next item. It keeps doing so until it raises a StopIteration error
# these are standard protocol applied to any iterator from iteable.
# num = [1,2,3]
# next(num) # give TyperError as list object is not an iterator
# To make It Iterator, call iter(num) and then call next() over the Iterator
# custom for loop
# def my_for (iterable, func):
# iterator = iter(iterable)
# while True :
# try:
# thing = next(iterator)
# except StopIteration:
# break
# else:
# func(thing)
# def square(x):
# print(x*x)
# my_for("hello", print)
# my_for([1,2,3,4], square)
# Define our own Iterable and Iterator
# class Counter(object):
# def __init__(self, low, high):
# self.current = low
# self.high = high
# def __iter__(self):
# return self
# def __next__(self):
# if self.current < self.high:
# num = self.current
# self.current += 2
# return num
# raise StopIteration
# for x in Counter(0, 20):
# print(x)
from random import shuffle
class Card:
def __init__(self, suit, value):
self.suit = suit
self.value = value
def __repr__(self):
return f"{self.value} of {self.suit}"
class Deck:
def __init__(self):
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
self.cards = [Card(suit, value) for suit in suits for value in values]
def __repr__(self):
return f"Deck of {self.count()} cards."
def __iter__(self):
return iter(self.cards)
# VERSION USING A GENERATOR FUNCTION
# (covered in the next video)
# def __iter__(self):
# for card in self.cards:
# yield card
def reset(self):
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
self.cards = [Card(suit, value) for suit in suits for value in values]
return self
def count(self):
return len(self.cards)
def _deal(self, num):
"""
Return a list of cards dealt
"""
count = self.count()
actual = min([num, count]) # make sure we don't try to over-deal
if count == 0:
raise ValueError("All cards have been dealt")
if actual == 1:
return [self.cards.pop()]
cards = self.cards[-actual:] # slice off the end
self.cards = self.cards[:-actual] # adjust cards
return cards
def shuffle(self):
if self.count() < 52:
raise ValueError("Only full decks can be shuffled")
shuffle(self.cards)
return self
def deal_card(self):
"""
Returns a single Card
"""
return self._deal(1)[0]
def deal_hand(self, hand_size):
"""
Returns a list of Cards
"""
return self._deal(hand_size)
# my_deck = Deck()
# my_deck.shuffle()
# for card in my_deck:
# print(card)
# Generators
# Generators are iterators
# Generators can be created with generator functions
# Generator functions are thr yield keyword
# Generators can be created with generator expressions
# Functions vs Generator Functions
# use return use yield
# return once can yield multiple times
# when invoked, when invoked
# returns the returns a generator object
# return value
# our first generator
def count_up_to(max):
count =1
while count <= max:
yield count
count += 1
# count_up_to(5) # return a generator object
# counter = count_up_to(5)
# print(next(counter)) # we get one thing at a time., not go back
# for c in counter: # automatically catch StopIteration Error and break loop
# print(c)
# print(list(counter))
# generator is returned from a generator function
# It is a way for making an iterator quickly
# Never have to determine what happen when calling next
# We do not define next() or iter()
# We never are raising the StopIteration Error
# We just define a function call it whatever you want and yield
# wherever that yield is, it is going to stop immediately, return the value that we specify
# stop execution and just wait.
# counter= count_up_to(10)
# print(list(counter))
# Infinite generator
# let us say we are making a music application,
# def current_beat():
# function return 1, 2, 3, 4 or any pattern
# How could we have it return a single number. but every time return a different number then repeating. we can return one thing from a function ?
# max = 100
# nums = (1,2,3,4)
# i =0
# result = []
# while len(result) < max:
# if i >= len(nums): i =0
# result.append(nums[i])
# i+=1
# return result
# print(current_beat())
def current_beat():
nums = (1,2,3,4)
i=0
while True:
if i >= len(nums): i =0
yield nums[i]
i+=1
# for c in current_beat():
# print(c)
# Testing memory usage with generators
def fib_gen(max):
x=0
y=1
count =0
while count < max:
x,y = y,x+y
yield x
count +=1
def fib_list(max):
nums = []
a,b = 0,1
while len(nums) < max:
nums.append(b)
a,b = b,a+b
return nums
# print(fib_list(10))
# Cautious following command will hang your PC. Memory eater
# for n in fib_list(1000000):
# print(n)
# for n in fib_gen(1000000): # less memory footprint
# print(n)
# generator Expressions
# look like list comprehesion
# use () instead of []
# def nums():
# for num in range(1,10):
# yield num
# g= (num for num in range(1,10))
# l= [num for num in range(1,10)]
# sum([num for num in range (1,10)])
# sum(num for num in range(1,10))
# import time
# gen_start_time = time.time()
# print(sum(n for n in range(100000000)))
# gen_stop = time.time() - gen_start_time
# print (gen_stop)
# list_start_time = time.time()
# print(sum([n for n in range(100000000)]))
# list_stop = time.time() - list_start_time
# print(list_stop)
|
6fd24c90d8f11203073a20e92dc57a5d95e75aef | LinChiGong/Reinforcement-Learning-Racetrack-Problem | /src/racetrack.py | 5,631 | 3.90625 | 4 | #!/usr/bin/env python3
'''
This class stores the information about a racetrack on which the race car runs
'''
import numpy as np
class Racetrack():
def __init__(self, file):
self.file = file # Name of the racetrack file
# Stores the racetrack in a 2D list and remove the first line
self.track = []
for line in open(file):
line = line.rstrip()
lst = list(line)
self.track.append(lst)
self.track = self.track[1:]
self.start_locations = [] # Stores all start points
self.finish_locations = [] # Stores all finish points
self.track_locations = [] # Stores all track points
self.wall_locations = [] # Stores all wall points
for i, row in enumerate(self.track):
for j, val in enumerate(row):
if val == 'S':
self.start_locations.append((i, j))
elif val == 'F':
self.finish_locations.append((i, j))
elif val == '.':
self.track_locations.append((i, j))
elif val == '#':
self.wall_locations.append((i, j))
self.finish_line = self.draw_finish_line() # Position of finish line
def get_nearest_track(self, position):
'''
This method finds a nearest track point to a point in the racetrack
INPUT:
position(tuple): Coordinates of a specific point
OUTPUT:
tuple: Coordinates of the nearest track point
'''
position = np.array(position)
track_locations = np.array(self.track_locations)
distance = np.sum(np.square(track_locations - position), axis=1)
nearest = np.argmin(distance)
nearest_track = self.track_locations[nearest]
return nearest_track
def get_nearest_start(self, position):
'''
This method finds a nearest start point to a point in the racetrack
INPUT:
position(tuple): Coordinates of a specific point
OUTPUT:
tuple: Coordinates of the nearest start point
'''
position = np.array(position)
start_locations = np.array(self.start_locations)
distance = np.sum(np.square(start_locations - position), axis=1)
nearest = np.argmin(distance)
nearest_start = self.start_locations[nearest]
return nearest_start
def is_wall(self, position):
'''
This method determines whether a point is a wall point or not
INPUT:
position(tuple): Coordinates of a specific point
OUTPUT:
boolean: True if the point is a wall point, False otherwise
'''
if (position[0] > (len(self.track) - 1) or
position[1] > (len(self.track[0]) - 1)):
return True
elif self.track[position[0]][position[1]] == '#':
return True
elif position[0] < 0 or position[1] < 0:
return True
return False
def draw_finish_line(self):
'''
Find the direction and location of the finish line
OUTPUT:
boolean: True if the finish line is vertical, False if horizontal
tuple: Coordinates of the point on one end of the finish line
tuple: Coordinates of the point on the other end of the finish line
'''
max_distance = 0
best_end1 = None # Point on one end of the finish line
best_end2 = None # Point on the other end of the finish line
for i in range(len(self.finish_locations)):
end1 = np.array(self.finish_locations[i])
for j in range(len(self.finish_locations)):
end2 = np.array(self.finish_locations[j])
distance = np.sum(np.abs(end1 - end2))
if distance > max_distance:
best_end1 = end1
best_end2 = end2
max_distance = distance
is_vertical = True
if (best_end1 - best_end2)[0] == 0:
is_vertical = False
return (is_vertical, best_end1, best_end2)
def check_finish_line(self, position1, position2):
'''
This method checks if the car has passed the finish line
INPUT:
position1(tuple): Coordinates of the car's current position
position2(tuple): Coordinates of the car's next position
OUTPUT:
boolean: True if the car has passed the finish line
'''
across_line = False
within_ends = False
crossed = False
position1 = np.array(position1)
position2 = np.array(position2)
if self.finish_line[0]: # Finish line is vertical
line = self.finish_line[1][1]
if (line-position1[1]) * (line-position2[1]) <= 0:
across_line = True
end1 = self.finish_line[1][0]
end2 = self.finish_line[2][0]
if end1 <= position1[0] <= end2 or end2 <= position1[0] <= end1:
within_ends = True
if across_line and within_ends:
crossed = True
else: # Finish line is horizontal
line = self.finish_line[1][0]
if (line-position1[0]) * (line-position2[0]) <= 0:
across_line = True
end1 = self.finish_line[1][1]
end2 = self.finish_line[2][1]
if end1 <= position1[1] <= end2 or end2 <= position1[1] <= end1:
within_ends = True
if across_line and within_ends:
crossed = True
return crossed
|
6d958b209efb49ee3070ce8cca4171c708962a4b | DevYam/Python | /Ex3.py | 704 | 4.0625 | 4 | # Guess the number Game
key = 43
count = 10
print("Total guesses left = ", count)
while True:
guess = input("Enter a number to guess\n")
if not guess.isnumeric():
print("Enter a valid number")
continue
if int(guess) < key and count > 0:
print("you need to enter a higher value\n")
count = count - 1
print("Total guesses left = ", count)
elif int(guess) > key:
print("you need to enter a lower value\n")
count = count - 1
print("Total guesses left = ", count)
elif int(guess) == key:
print("Congratulations you guessed it right\n")
break
elif count == 0:
print("Game Over\n")
break
|
c238078f55464429915d9c9f7b8987336966c957 | hcs42/hcs-utils | /bin/Catless | 2,227 | 3.703125 | 4 | #!/usr/bin/python
# Prints the text from the standard input or the given files using `cat` or
# `less` depending on whether the text fits into the terminal
import optparse
import os.path
import subprocess
import sys
def parse_args():
usage = 'Usage: Catless [options] [FILENAME]...'
parser = optparse.OptionParser(usage=usage)
(cmdl_options, args) = parser.parse_args()
return cmdl_options, args
def cmd(args):
return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0]
def main(options, args):
terminal_height = int(cmd(["tput", "lines"]))
text = []
if len(args) == 0:
# Reading stdin
while True:
line = sys.stdin.readline()
if line == '':
break
text.append(line)
else:
filenames = args
# Checking whether all files exist and are regular
all_files_ok = True
for filename in filenames:
if not os.path.exists(filename):
print 'File not found: ', filename
all_files_ok=False
elif not os.path.isfile(filename):
print 'Not a regular file: ', filename
all_files_ok=False
if not all_files_ok:
sys.exit(0)
# Reading the content of all files
for filename in filenames:
f = open(filename, 'r')
while True:
line = f.readline()
if line == '':
break
text.append(line)
f.close()
# If the terminal is taller then the text, we print the text just like
# `cat`
if len(text) < terminal_height:
for line in text:
sys.stdout.write(line)
# Otherwise we use "less" to display it
else:
process = subprocess.Popen(["less"], stdin=subprocess.PIPE)
process.communicate(''.join(text))
if __name__ == '__main__':
try:
main(*parse_args())
except OSError:
# The user probably pressed CTRL-C before `less` could read all data.
# This is not an error.
pass
except KeyboardInterrupt:
# The user probably pressed CTRL-C while Catless was running.
pass
|
c24fdf73fee84a9be9b3eee03e9fc3889aec264b | tanx-code/levelup | /design_patterns/state.py | 858 | 4 | 4 | """状态机模式
允许对象在内部状态改变时改变它的行为,对象
看起来好像改了它的类。
"""
class State:
def __init__(self, m):
self.machine = m
class AState(State):
def db_a(self):
print('do a')
self.machine.set_state(self.machine.b_state)
class BState(State):
def do_b(self):
print('do b')
class Machine:
current_state = None
def run(self):
self.a_state = AState(self)
self.b_state = BState(self)
self.current_state = self.a_state
def do_a(self):
self.current_state.do_a()
def do_b():
self.current_state.do_b()
def set_state(state):
self.current_state = state
if __name__ == '__main__':
m = Machine()
# 对于客户来说,不知道机器内部状态在怎么变化
m.do_a()
m.do_b()
|
a87aaf69c2971b2ae241cae12c4b3c2624005e83 | tjatn304905/algorithm | /SWEA/5186_이진수2/sol1.py | 411 | 3.59375 | 4 | import sys
sys.stdin = open('sample_input.txt')
def change(N):
result = ''
for i in range(1, 13):
if N >= 1 / 2**i:
result += '1'
N -= 1 / 2**i
if N == 0:
return result
else:
result += '0'
return 'overflow'
T = int(input())
for tc in range(1, T+1):
N = float(input())
print('#{} {}'.format(tc, change(N))) |
3a1c50c59e5819bf13bfd8b4ab7108fe0c639771 | ramaranjanruj/Machine-Learning | /Ridge Regression/Ridge.Regression.py | 5,393 | 3.75 | 4 | import pandas as pd
import numpy as np
from sklearn import linear_model
import math
dtype_dict = {'bathrooms':float, 'waterfront':int, 'sqft_above':int,
'sqft_living15':float, 'grade':int, 'yr_renovated':int,
'price':float, 'bedrooms':float, 'zipcode':str, 'long':float,
'sqft_lot15':float, 'sqft_living':float, 'floors':float,
'condition':int, 'lat':float, 'date':str, 'sqft_basement':int,
'yr_built':int, 'id':str, 'sqft_lot':int, 'view':int}
# Importing the sales data
sales = pd.read_csv('kc_house_data.csv', dtype=dtype_dict)
sales = sales.sort(['sqft_living','price'])
def polynomial_dataframe(feature, degree): # feature is pandas.Series type
"""
This function is to create polynomial features from a given column
"""
# assume that degree >= 1
# initialize the dataframe:
poly_dataframe = pd.DataFrame()
# and set poly_dataframe['power_1'] equal to the passed feature
poly_dataframe['power_1'] = feature
# first check if degree > 1
if degree > 1:
# then loop over the remaining degrees:
for power in range(2, degree+1):
# first we'll give the column a name:
name = 'power_' + str(power)
# assign poly_dataframe[name] to be feature^power; use apply(*)
poly_dataframe[name] = poly_dataframe['power_1'].apply(lambda x: math.pow(x, power))
return poly_dataframe
poly15_data = polynomial_dataframe(sales['sqft_living'], 15)
l2_small_penalty = 1.5e-5
model = linear_model.Ridge(alpha=l2_small_penalty, normalize=True)
model.fit(poly15_data, sales['price'])
print model.coef_[0] # Prints the coefficient of the column with power =1
"""
Reading the other 4 datasets
"""
set_1 = pd.read_csv('wk3_kc_house_set_1_data.csv', dtype=dtype_dict)
set_2 = pd.read_csv('wk3_kc_house_set_2_data.csv', dtype=dtype_dict)
set_3 = pd.read_csv('wk3_kc_house_set_3_data.csv', dtype=dtype_dict)
set_4 = pd.read_csv('wk3_kc_house_set_4_data.csv', dtype=dtype_dict)
def get_ridge_coef(data, deg, l2_penalty):
"""
This is a fucntion to generate the 1st coefficient of the ridge regression
"""
poly15 = polynomial_dataframe(data['sqft_living'], deg)
model = linear_model.Ridge(alpha=l2_penalty, normalize=True)
model.fit(poly15, data['price'])
return model.coef_[0]
"""
Finf the ridge coefficients for the 4 datasets for l2_small_penalty=1e-9
"""
l2_small_penalty=1e-9
print get_ridge_coef(set_1, 15, l2_small_penalty)
print get_ridge_coef(set_2, 15, l2_small_penalty)
print get_ridge_coef(set_3, 15, l2_small_penalty)
print get_ridge_coef(set_4, 15, l2_small_penalty)
"""
Finf the ridge coefficients for the 4 datasets for l2_large_penalty=1.23e2
"""
l2_large_penalty=1.23e2
print get_ridge_coef(set_1, 15, l2_large_penalty)
print get_ridge_coef(set_2, 15, l2_large_penalty)
print get_ridge_coef(set_3, 15, l2_large_penalty)
print get_ridge_coef(set_4, 15, l2_large_penalty)
train_valid_shuffled = pd.read_csv('wk3_kc_house_train_valid_shuffled.csv', dtype=dtype_dict)
test = pd.read_csv('wk3_kc_house_test_data.csv', dtype=dtype_dict)
def k_fold_cross_validation(k, l2_penalty, data, output):
"""
Function to find the best value of lambda in a given k_fold_cross_validation
"""
n = len(data)
total_mse = []
best_mse = None
best_lambda = 0
poly_data = polynomial_dataframe(data['sqft_living'], 15)
for l2_value in l2_penalty:
for i in xrange(k):
# Generates the index of the dataframe
start = (n*i)/k
end = (n*(i+1))/k-1
round_mse = 0
# Splits the dataframe
X_test, Y_test = poly_data[start:end+1], output[start:end+1]
X_train = pd.concat([poly_data[0:start], poly_data[end+1:n]], axis=0, ignore_index=True)
Y_train = pd.concat([pd.Series(output[0:start]), pd.Series(output[end+1:n])], axis=0, ignore_index=True)
# Peform a ridge regression of the training and testing sets
ridge = linear_model.Ridge(alpha=l2_value, normalize=True)
ridge.fit(X_train, Y_train)
out = ridge.predict(X_test)
round_mse += ((out - Y_test)**2).sum()
# Calculate the mse for each value of lambda
round_mse = round_mse/k
# Get the best value of mse and lambda
if best_mse is None or best_mse > round_mse:
best_mse = round_mse
best_lambda = l2_value
total_mse.append(round_mse)
return np.mean(total_mse), best_lambda
"""
Get the best value of lambda and mse on the kfolded training sets
"""
l2_penalty = np.logspace(3, 9, num=13)
kfold_mse, kfold_lambda = k_fold_cross_validation(10, l2_penalty, train_valid_shuffled, train_valid_shuffled['price'])
print kfold_mse # 3.13176238516e+13
print kfold_lambda # 1000.0
"""
Get the RSS on the testing datasets
"""
ridge_all = linear_model.Ridge(alpha=1000, normalize=True)
ridge_all.fit(polynomial_dataframe(train_valid_shuffled['sqft_living'],15), train_valid_shuffled['price'])
predicted = ridge_all.predict(polynomial_dataframe(test['sqft_living'],15))
print ((predicted - test['price'])**2).sum() # 2.83856861224e+14
|
b9104f7316d95eaa733bbbd4926726472855046e | emma-rose22/practice_problems | /HR_arrays1.py | 247 | 4.125 | 4 | '''You are given a space separated list of nine integers. Your task is to convert this list into a 3x3 NumPy array.'''
import numpy as np
nums = input().split()
nums = [int(i) for i in nums]
nums = np.array(nums)
nums.shape = (3, 3)
print(nums)
|
34ad6779977c33d824b00a8b63e64d72566b3165 | alexandraback/datacollection | /solutions_1674486_0/Python/rfonseca/diamond.py | 885 | 3.5625 | 4 | #!/usr/bin/env python3
import sys
def dfs(visited, classes, node):
if visited[node]:
return True
visited[node] = True
for child in classes[node]:
res = dfs(visited, classes, child)
if res:
return True
return False
def diamond(n, classes):
for i in range(n):
visited = [False for _ in range(n)]
exists = dfs(visited, classes, i)
if exists:
return "Yes"
return "No"
if __name__ == "__main__":
ncases = int(sys.stdin.readline().strip())
for case in range(1, ncases + 1):
n = int(sys.stdin.readline().strip())
classes = []
for i in range(n):
line = sys.stdin.readline().strip().split(' ')
#n = int(line[0])
classes.append([(int(x) - 1) for x in line[1:]])
print("Case #", case, ": ", diamond(n, classes), sep="")
|
aa0e9bf9680e5b121616348f47a67511b7cbc3fb | LailaBenz/Bioinformatik-sose18 | /assignment2/fasterfrequentwords.py | 1,691 | 3.8125 | 4 | def PatternCount(text, pattern):
result = 0
for i in range(0, len(text)-len(pattern)+1):
if (text[i:i+len(pattern)] == pattern):
result += 1
return result
def FrequentWords(text, k=4):
#Return a list of the most frequent substrings in a given text.
# import previosly written programs to get SymbolToNumber, PatternToNumber, NumberToSymbol and NumberToPattern
import ba1m
import ba1l
# Create an array for all patterns, initialize by size 4^k
allPatternsWithCount = [0]*(4**k)
# A list to store the final result
result = []
# Loop over the whole text moving forward one letter at a time
for i in range(0, len(text)-k):
# pattern is a small part of the text (with length k)
pattern = text[i:i+k]
# Add one to the counter of this pattern
allPatternsWithCount[ba1l.PatternToNumber(pattern)] += 1
# After counting everything, find the maximum value
maximum = max(allPatternsWithCount)
#Print count of most frequent patterns
print(maximum)
# Loop over all patters that have been found (evtl geht das nicht bei array)
for number, count in enumerate (allPatternsWithCount):
# If the count for this pattern is the maximum ...
if count == maximum:
# Add it to the result
result.append((number, count))
print(ba1m.NumberToPattern(number, k),end=' ')
return result
with open ("input.txt", "r") as myfile:
data=myfile.readlines()
# For testing
text = data[0]
#print(FrequentWords(text, int(data[1])))
FrequentWords(text, int(data[1]))
|
8b43a57e4785d57809eb60a3a30b8590d5981b1c | ieee-saocarlos/desafios-cs | /Esther Bastos/produtos.py | 549 | 3.65625 | 4 | leite = int(input("Número de conjuntos de leite: "))
ovo = int(input("Número de conjuntos de ovo: "))
prendedores = int(input("Número de conjuntos de prendedores: "))
sabão = int(input("Número de conjuntos de sabão: "))
iogurte = int(input("Número de conjuntos de iogurte: "))
leite = 12 * leite
ovo = 12 * ovo
prendedores = 24 * prendedores
sabão = 5 * sabão
iogurte = 6 * iogurte
print("Há {0} caixas de leite, {1} ovos, {2} prendedores, {3} barras de sabão e {4} copinhos de iogurte".format(leite, ovo, prendedores, sabão, iogurte)) |
46f1616e0375fee9c7de88544433c5655f22f912 | mittal-umang/Analytics | /Assignment-1/MinutesToYears.py | 580 | 4.15625 | 4 | # Chapter 2 Question 7
# Write a program that prompts the user to
# enter the minutes (e.g., 1 billion), and displays the number of years and days for
# the minutes. For simplicity, assume a year has 365 days.
def main():
minutes = eval(input("Enter the number of minutes : "))
days, years = _calculate_(minutes)
print(minutes, "minutes is approximately", years, "years and", days, "days.")
def _calculate_(minutes):
years = minutes / (365 * 24 * 60)
days = (years - int(years))*365
return int(days), int(years)
if __name__ == "__main__":
main()
|
8980f33232eba85fc9f3532b53aa1cd3075fc066 | andrebaboim/data-lake | /src/pipelines/cache.py | 1,613 | 3.625 | 4 | class SourceCache():
singleton = None
def __init__(self):
"""
Class constructor.
Returns:
(SourceCache): A new instance of SourceCache class.
"""
self._sources = {}
@classmethod
def instance(cls):
"""
Gets or creates the singleton instance of the SourceCache class.
Returns:
(SourceCache): The SourceCache singleton instance.
"""
if cls.singleton is None:
cls.singleton = cls()
return cls.singleton
def exists(self, source_name):
"""
Checks if the given dataframe is already cached.
Parameters:
source_name (str): The dataframe name.
Returns:
(bool): True if the dataframe is cached, otherwise returns False.
"""
return source_name in self._sources
def get_source(self, source_name):
"""
Gets the cached dataframe corresponding the given name.
Parameters:
source_name (str): The dataframe name.
Returns:
(DataFrame): The cached dataframe.
"""
print('Retrieving {} dataframe from cache'.format(source_name))
return self._sources[source_name]
def set_source(self, source_name, source_data):
"""
Caches the given dataframe.
Parameters:
source_name (str): The dataframe name.
source_data (DataFrame): The dataframe itself.
"""
print('Caching {} dataframe'.format(source_name))
self._sources[source_name] = source_data
|
de93fb69a0f878335bfb70abeedf1b9ed6d23cea | JBustos22/Physics-and-Mathematical-Programs | /computational derivatives/simpson.py | 597 | 3.859375 | 4 | #! /usr/bin/env python
"""
This program uses the simpson method of approximating integrals to find
the integral of x**4-2*x+1 from 0 to 2.
Jorge Bustos
Feb 22, 2019
"""
from __future__ import division, print_function
import numpy as np
def f(x):
return x**4 - 2*x + 1
N = 1000 #max value in summation
a = 0.0
b = 2.0
h = (b-a)/N #width of intervals
s = (f(a) + f(b)) #the two lone terms inside the parentheses
for k in range(1,int(N/2+1)): #first summation term
s += 4*f(a+(2*k-1)*h)
for j in range(1,int(N/2)): #second summation term
s += 2*f(a+2*j*h)
print(1/3*h*s) #multiplying what's outside
|
0d5212d22101ff756968732a4b5e481d39e18286 | patterson-dtaylor/python_work | /Chapter_4/animals.py | 246 | 4.21875 | 4 | # 10/1/19 Exercise 4-2: Using for loops with a list of animals.
animals = ['flying squirell', 'gold fish', 'racoon']
for animal in animals:
print(f"A {animal} would make a great pet!\n")
print("Any of these animals would make a great pet!")
|
d894857c9d0e6d217782a7cfda00e31123cc0b30 | kevinelong/AM_2015_04_06 | /Week1/pocket_change_answer.py | 530 | 3.5625 | 4 | pocket_change = {
"pennies": 13,
"nickels": 3,
"dimes": 2,
"quarters": 4
}
change_values = {
"pennies": 1,
"nickels": 5,
"dimes": 10,
"quarters": 25
}
def add_up(pocket_change):
totals = {}
grand = 0
# ... DO YOUR WORK HERE
for k in pocket_change.keys():
subtotal = pocket_change[k] * change_values[k]
totals[k] = subtotal
grand += subtotal
totals["all_totaled"] = grand
return totals
if __name__ == "__main__":
print(add_up(pocket_change))
|
c2898bd7a8bce643f164e03c7260d937283abfa8 | yueqiusun/DS1004-Big-Data-HW | /Map-Reduce/task3/map.py | 851 | 3.734375 | 4 | #!/usr/bin/python
# map function for matrix multiply
#Input file assumed to have lines of the form "A,i,j,x", where i is the row index, j is the column index, and x is the value in row i, column j of A. Entries of A are followed by lines of the form "B,i,j,x" for the matrix B.
#It is assumed that the matrix dimensions are such that the product A*B exists.
#Input arguments:
#m should be set to the number of rows in A, p should be set to the number of columns in B.
import sys
import string
import csv
# input comes from STDIN (stream data that goes to the program)
for line in sys.stdin:
#Remove leading and trailing whitespace
entry = list(csv.reader([line], delimiter = ','))[0]
if len(entry) != 18:
continue
key = entry[2]
value = entry[12]
if len(key) < 2:
continue
print(str(key) + '\t' + str(value))
|
2417bafe451e0957bb17ed1930679562bf13f7c6 | ShubhAgarwal566/Maze-Solver | /driver.py | 4,243 | 3.859375 | 4 | #global libraries
import turtle
import Tkinter as tk
# user libraries
import maze_generator
import LHR
import RHR
import randomMouse
import dfs1
import dfs2
import bfs
import deadendFilling
import aStar
#driver function which helps in setting up maze and calling respective algorthim function
def start(width, height, lastMaze, speed, algo):
maze_color = 'white'
bg_color = 'black'
def setupMaze(grid):
for y in range(len(grid)): # loop through all the elements in the list(maze)
for x in range(len(grid[y])):
character = grid[y][x]
screen_x = -588 + (x * cellWidth) # calculate the position of x coordinate
screen_y = 288 - (y * cellWidth) # calculate the position of y coordinate
if character == "+": # if wall
maze.goto(screen_x, screen_y) # go to location
maze.stamp() # put stamp (make wall)
walls.append((screen_x, screen_y)) # append in walls list
elif character == "e": # if end point (target/goal)
maze.goto(screen_x, screen_y) # goto location
maze.color('green') # make color green
maze.stamp() # put stamp
maze.color(maze_color) # switch back to wall color
finish.append((screen_x, screen_y)) # append in finish list
grid = maze_generator.createMaze(width, height, lastMaze) # generate a maze with given width and height
cellWidth = row = int( min( 700.0 / (len(grid)*1.1), 1300.0 / (len(grid[0])*1.05) ) ) # calculate the width of each cell to fit the maze properly on screen
window = tk.Tk() # create a tkinter window
window.title("Maze-Solver") # put title
window.geometry('1300x700') # set dimension
window.resizable(False, False) # make it non resizeable
wn = turtle.Canvas(window, width=1300, height=700) # take turtle canvas
wn.place(x=0, y=0) # pin the canvas on the window
maze = turtle.RawTurtle(wn) # create a turtle object for maze
wn['bg'] = bg_color # set background color
maze.shape('square') # set shape of wall as sqaure
maze.penup() # put penup (no trail)
maze.color(maze_color) # set wall color
maze.speed(0) # fastest # set speed to draw maze as fastest(0)
maze.shapesize(cellWidth/24.0) # set the size of each cell
maze.hideturtle() # hide the maze turtle
walls =[] # list to store walls
finish = [] # list to store the end point
setupMaze(grid) # create the maze
maze.speed(speed) # set the speed given by the user
maze.hideturtle() # hide
myTurtle = turtle.RawTurtle(wn) # create a turtle object for mover(solver)
myTurtle.shape('turtle') # set its shape
myTurtle.hideturtle() # hide the turtle
myTurtle.color('red') # set its color as red
myTurtle.speed(0) # set its speed to fastest(0)
myTurtle.penup() # put pen up initially (no trail)
myTurtle.shapesize(cellWidth/24.0) # set the size of each cell
myTurtle.goto(-588+cellWidth, 288-cellWidth) # move the turtle to the starting position
myTurtle.speed(speed) # set the speed to user given speed
myTurtle.pendown() # put the pen down (for trail)
# call apt function as per the given algo
if(algo == 'Left Hand Rule'):
LHR.start(myTurtle, walls, finish, cellWidth)
elif(algo == 'Right Hand Rule'):
RHR.start(myTurtle, walls, finish, cellWidth)
elif(algo == 'Random Mouse'):
randomMouse.start(myTurtle, walls, finish, cellWidth)
elif(algo == 'Depth First Search - 1'):
dfs1.start(myTurtle, walls, finish, cellWidth)
elif(algo == 'Depth First Search - 2') :
dfs2.start(myTurtle, walls, finish, cellWidth, maze)
elif(algo == 'Breadth First Search'):
bfs.start(myTurtle, walls, finish, cellWidth, maze)
elif(algo == 'Dead-End Filling'):
deadendFilling.start(myTurtle, walls, finish, cellWidth, maze)
elif(algo == 'A* Search'):
aStar.start(myTurtle, walls, finish, cellWidth, maze)
window.mainloop() # prevents program from quiting
# start(10,10,False,5,'A* Search') # used for faster debugging |
a5c6fe96d40c81d888fc4d5f6ba0d26b1604e3ec | xilousong/test_git | /00打招呼.py | 649 | 3.859375 | 4 | #!/usr/bin/env python3
class Name():
def __init__(self,name,age):
self.__name = name
self.__age = age
def set_name(self,new_name):
self.__name = new_name
def set_age(self,new_age):
if new_age >0 and new_age <100:
self.__age = new_age
else:
self.__age = 0
def get_name(self):
return self.__name
def get_age(self):
return self.__age
def __str__(self):
return "我叫%s,今年%d 岁"%(self.get_name(),self.get_age())
p = Name("小明",20)
print(p)
p.set_name("明明")
print(p)
p.set_age(30)
print(p)
p.set_age(300)
print(p)
|
42754928e6000ce6c441e53d45a412d3a7a1cd0c | rado0x54/CTFs | /picoCTF2019/100_caesar/solve.py | 315 | 3.609375 | 4 | #!/usr/bin/env python3
CIPHERTEXT = 'dspttjohuifsvcjdpoabrkttds'
# (ord(K) - ord('a')) + {1-25} % 26 = ord(C)
def move(c_char, shift):
return chr(((ord(c_char) - ord('a')) + shift) % 26 + ord('a'))
# test all solutions. only 25 makes sense
print(f"picoCTF{{{''.join([move(c, 25) for c in CIPHERTEXT])}}}")
|
3b01eeb6abd077b89deb8a7e1d2c20d46cb1c844 | kaceyabbott/intro-python | /iterations.py | 1,489 | 4 | 4 | """
when working with iterators, generators, etc
look at the documentatoin for the itertools module
"""
from itertools import islice, count, chain
from listcomprehensions import prime
import statistics
def main():
"""
test function
:return:
"""
thousandprimes = islice((x for x in count() if prime(x)), 1000)
print(thousandprimes,type(thousandprimes))
#print('list of first 1000 prime numbers:', list(thousandprimes))
#if you need to use the object again, you will need to regenerate it
thousandprimes = islice((x for x in count() if prime(x)), 1000)
print('list of first 1000 prime numbers:',sum((thousandprimes)))
#other built ins use with itertools: any(or) or all(and)
print(any([False, False, True]))
print(all([False, False, True]))
print('any primes in range',any(prime(x) for x in range(1328,1363)))
names = ['London','New York','Ogden']
print(all(name == name.title() for name in names))
#another builtin: zip()
sunday = [2,2,5,7,9,10,9,6,4,4]
monday = [12,14,14,15,15,16,15,13,10,9]
tuesday = [13,14,15,15,16,17,16,16,12,12]
for temps in zip(sunday,monday, tuesday):
print('min=',min(temps),'max=',max(temps),'average=',statistics.mean(temps))
# {:6.1f} => chars width, 1 decimal precision floating point
#chain
alltemps = chain(sunday,monday,tuesday)
print('all temps > 0',all(t> 0 for t in alltemps))
if __name__ == '__main__':
main()
exit(0) |
4ab61f9bff0812b77f63df896c80a61612fd03e2 | droomkan/AI_ML_weekopdrachten | /week_1/a_star/model.py | 5,203 | 3.5 | 4 | import random
import heapq
import math
import config as cf
# global var
grid = [[0 for x in range(cf.SIZE)] for y in range(cf.SIZE)]
class PriorityQueue:
# to be used in the A* algorithm
# a wrapper around heapq (aka priority queue), a binary min-heap on top of a list
# in a min-heap, the keys of parent nodes are less than or equal to those
# of the children and the lowest key is in the root node
def __init__(self):
# create a min heap (as a list)
self.elements = []
def empty(self):
return len(self.elements) == 0
# heap elements are tuples (priority, item)
def put(self, item, priority):
heapq.heappush(self.elements, (priority, item))
# pop returns the smallest item from the heap
# i.e. the root element = element (priority, item) with highest priority
def get(self):
return heapq.heappop(self.elements)[1]
def bernoulli_trial(app):
return 1 if random.random() < int(app.prob.get())/10 else 0
def get_grid_value(node):
# node is a tuple (x, y), grid is a 2D list [x][y]
return grid[node[0]][node[1]]
def set_grid_value(node, value):
# node is a tuple (x, y), grid is a 2D list [x][y]
grid[node[0]][node[1]] = value
def search(app, start, goal):
# plot a sample path for demonstration
for i in range(cf.SIZE-1):
app.plot_line_segment(i, i, i, i+1, color=cf.FINAL_C)
app.plot_line_segment(i, i+1, i+1, i+1, color=cf.FINAL_C)
app.pause()
# voor de uitwerking van het UCS algoritme is het voorbeeld uit de sheets
# van het hoorcollege 1-2 gebruikt.
def ucs(app, start, goal):
pqueue = PriorityQueue()
path = []
visited = {}
visited[start] = 0
pqueue.put((start,path+[start]), 0)
# loop through possible paths while the queue
while not pqueue.empty():
item = pqueue.get()
prev_node = item[0]
prev_cost = visited[prev_node]
path = item[1]
current = path[-1]
if current == goal:
return path
for neighbour in neighbours(current):
cost = prev_cost + 1
if neighbour not in visited:
visited[neighbour] = cost
pqueue.put((current, path+[neighbour]), cost)
app.plot_node(neighbour, color=cf.PATH_C)
app.pause()
app.path_not_found_message()
return path
# TODO: WERKT NIET OPTIMAAl, WE WETEN OOK NIET PRECIES WAAROM. GRAAG DIT OVERLEGGEN IN VRAGENUURTJE
def a_star(app, start, goal):
pqueue = PriorityQueue()
path = [] # keeps being added onto and will eventually return from function as shortest path
visited = {} # keeps track of all visited nodes and their priority values
pqueue.put((start, path+[start]), 0)
visited[start] = 0
# loop through possible paths while the queue is not empty
while not pqueue.empty():
item = pqueue.get()
parent = item[0]
path = item[1]
prev_cost = visited[parent]
current = path[-1]
print("current path {0} with priority {1}".format(current, prev_cost))
if current == goal:
return path
for neighbour in neighbours(current):
g = prev_cost + 1
h = cost(neighbour, goal) # heuristic
p = g + h # priority = g + h
# or (neighbour in visited and not visited[neighbour] > visited[current])
if neighbour not in visited or g < prev_cost:
visited[neighbour] = g # node has now been visited
print(" p for neighbour {0} is {1}".format(neighbour, p))
pqueue.put((current, path+[neighbour]), p) # add neighbour to queue
app.plot_node(neighbour, color=cf.PATH_C)
app.pause() # pause loop according to set delay
app.path_not_found_message()
return path
# calculates cost based on heuristic
# source for chosen heuristic: https://www.kdnuggets.com/2017/08/comparing-distance-measurements-python-scipy.html
def cost(n1, n2):
x1 = n1[0]
y1 = n1[1]
x2 = n2[0]
y2 = n2[1]
# Euclidian distance. allows for diagonal measurement of distance
return math.sqrt(abs((x2-x1)**2) + abs((y2-y1)**2))
# helper function that checks all possible neighbours for a given node
def neighbours(node):
x = node[0]
y = node[1]
# directions: left, right, up, down
directions = [(x-1, y), (x+1, y), (x, y-1), (x, y+1)]
neighbours = []
for direction in directions:
if not out_of_bounds(direction) and not_blocked(direction):
neighbours.append(direction)
return neighbours
# helper function that checks if a node is blocked
def not_blocked(node):
if get_grid_value(node) == -1:
return True
else:
return False
# helper function that checks if a coordinate is out of bounds
def out_of_bounds(node):
# compare coordinates with size of board or if they are smaller than 0
if node[0] > cf.SIZE-1 or node[1] > cf.SIZE-1 or node[0] < 0 or node[1] < 0:
return True
else:
return False
|
465ef0a5df387181caa40ea565b69aeb3628129f | jproddy/rosalind | /python_village/ini3.py | 623 | 3.859375 | 4 | '''
Strings and Lists
http://rosalind.info/problems/ini3/
Given: A string s of length at most 200 letters and four integers a, b, c and d.
Return: The slice of this string from indices a through b and c through d (with space in between), inclusively. In other words, we should include elements s[b] and s[d] in our slice.
'''
filename = 'rosalind_ini3.txt'
def strings(s, a, b, c, d):
return [s[a:b+1], s[c:d+1]]
def main():
with open(filename) as f:
s = f.readline().strip()
a, b, c, d = [int(i) for i in f.readline().strip().split()]
print(' '.join(strings(s, a, b, c, d)))
if __name__ == '__main__':
main()
|
ee09f1aa120c6ab960cc2a0caaa5e74cba1bd9dd | erjan/coding_exercises | /Find Maximum Number of String Pairs.py | 1,410 | 3.75 | 4 | '''
You are given a 0-indexed array words consisting of distinct strings.
The string words[i] can be paired with the string words[j] if:
The string words[i] is equal to the reversed string of words[j].
0 <= i < j < words.length.
Return the maximum number of pairs that can be formed from the array words.
Note that each string can belong in at most one pair.
'''
class Solution:
def maximumNumberOfStringPairs(self, words: List[str]) -> int:
res = 0
n = len(words)
for i in range(n):
temp = list(words[i])
temp.reverse()
temp = "".join(temp)
for j in range(i+1, n):
if words[j] == temp:
res+=1
return res
-------------------------------------------------------------------------------------------
class Solution:
def maximumNumberOfStringPairs(self, words: List[str]) -> int:
d = defaultdict(int)
for word in words:
d[min(word, word[::-1])]+= 1
return sum(map((lambda x: x*(x-1)), d.values()))//2
---------------------------------------------------------------------------------------
class Solution:
def maximumNumberOfStringPairs(self, words: List[str]) -> int:
count=0
s=set()
for ele in words:
if ele[::-1] in s:
count+=1
s.add(ele)
return count
|
feff1b82513e75dd2b2f9d86d07003c8d5d2ba20 | GirishJoshi/interviewcake | /Greedy algorithms/apple_stock.py | 2,807 | 4.09375 | 4 | """
Writing programming interview questions hasn't made me rich yet ... so I might give up and start
trading Apple stocks all day instead.
First, I wanna know how much money I could have made yesterday if I'd been trading Apple stocks all day.
So I grabbed Apple's stock prices from yesterday and put them in a list called stock_prices,
where:
* The indices are the time (in minutes) past trade opening time, which was 9:30am local time.
* The values are the price (in US dollars) of one share of Apple stock at that time.
So if the stock cost $500 at 10:30am, that means stock_prices[60] = 500.
Write an efficient function that takes stock_prices and returns the best profit I could have made
from one purchase and one sale of one share of Apple stock yesterday.
For example:
stock_prices = [10, 7, 5, 8, 11, 9]
get_max_profit(stock_prices)
# Returns 6 (buying for $5 and selling for $11)
No "shorting"—you need to buy before you can sell. Also, you can't buy and sell in the same
time step—at least 1 minute has to pass.
"""
"""
At each iteration, our max_profit is either:
the same as the max_profit at the last time step, or
the max profit we can get by selling at the current_price
How do we know when we have case (2)?
The max profit we can get by selling at the current_price is simply the difference
between the current_price and the min_price from earlier in the day.
If this difference is greater than the current max_profit, we have a new max_profit.
So for every price, we’ll need to:
keep track of the lowest price we’ve seen so far
see if we can get a better profit
"""
# stock_prices = [10, 7, 5, 8, 11, 9]
stock_prices = [10, 9, 7, 3, 1]
def get_max_profit_enum(stock_prices):
max_profit = min(stock_prices) - max(stock_prices)
for i, price in enumerate(stock_prices[:-1]):
profit = max(stock_prices[i + 1 :]) - price
if profit > max_profit:
max_profit = profit
return max_profit
def get_max_profit(stock_prices):
if len(stock_prices) < 2:
raise ValueError("Require at least 2 prices to find profit.")
# We'll greedily update min_price and max_profit, so we initialize them at first price
# and first possible profit
min_price = stock_prices[0]
max_profit = stock_prices[1] - stock_prices[0]
for current_price in stock_prices[1:]:
# See what our profit would be if we bought at min_price and sold at current price
potential_profit = current_price - min_price
# Update max_profit if we can do better
max_profit = max(potential_profit, max_profit)
# Update the min_price so it's always the lowest price we have seen so far
min_price = min(min_price, current_price)
return max_profit
print(get_max_profit(stock_prices))
|
b387c6daa15dc9ad3c696b2ff2bbe115c03472f6 | webclinic017/TFS | /tfs/utils/charts.py | 6,699 | 3.59375 | 4 | import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.ticker import FuncFormatter
import pdb
class Chart(object):
pass
class BulletGraph(Chart):
"""Charts a bullet graph.
For examples see: http://pbpython.com/bullet-graph.html
"""
def draw_graph(self, data=None, labels=None, axis_label=None,
title=None, size=(5, 3), formatter=None,
target_color="gray", bar_color="black", label_color="gray"):
""" Build out a bullet graph image
Args:
data = List of labels, measures and targets
limits = list of range valules
labels = list of descriptions of the limit ranges
axis_label = string describing x axis
title = string title of plot
size = tuple for plot size
palette = a seaborn palette
formatter = matplotlib formatter object for x axis
target_color = color string for the target line
bar_color = color string for the small bar
label_color = color string for the limit label text
Returns:
a matplotlib figure
"""
# Must be able to handle one or many data sets via multiple subplots
if len(data) == 1:
fig, ax = plt.subplots(figsize=size, sharex=True)
else:
fig, axarr = plt.subplots(len(data), figsize=size, sharex=True)
# Add each bullet graph bar to a subplot
index = -1
for idx, item in data.iterrows():
index += 1
ticker = item['ticker']
# set limits
graph_data, prices = self._normalize_data(item)
# Determine the max value for adjusting the bar height
# Dividing by 10 seems to work pretty well
h = graph_data[-1] / 10
# Reds_r / Blues_r
palette = sns.color_palette("Blues_r", len(graph_data) + 2)
# Get the axis from the array of axes returned
# when the plot is created
if len(data) > 1:
ax = axarr[index]
# Formatting to get rid of extra marking clutter
ax.set_aspect('equal')
ax.set_yticklabels([ticker])
ax.set_yticks([1])
ax.spines['bottom'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
labelbottom=False)
prev_limit = 0
n_items = len(graph_data)
corr_factor = len(graph_data) / 2
for idx2, lim in enumerate(graph_data):
color_index = int(abs(
abs(n_items - corr_factor - idx2) -
corr_factor))
# Draw the bar
ax.barh([1], lim - prev_limit, left=prev_limit,
height=h,
color=palette[color_index])
prev_limit = lim
rects = ax.patches
"""
prev_limit = limits[0]
n_items = len(limits)
corr_factor = len(limits) / 2
for idx2, lim in enumerate(limits):
color_index = int(abs(
abs(n_items - corr_factor - idx2) -
corr_factor))
# Draw the bar
# pdb.set_trace()
ax.barh([1], lim - prev_limit, left=prev_limit,
height=h,
color=palette[color_index + 2])
# pdb.set_trace()
prev_limit = lim
rects = ax.patches
"""
# The last item in the list is the value we're measuring
# Draw the value we're measuring
# ax.barh([1], item['close'], height=(h / 3), color=bar_color)
# Need the ymin and max in order to make sure the target marker
# fits
ymin, ymax = ax.get_ylim()
ax.vlines(
prices['close'],
ymin * .9,
ymax * .9,
linewidth=1.5,
color=target_color)
# Now make some labels
if labels is not None:
for rect, label in zip(rects, labels):
height = rect.get_height()
ax.text(
rect.get_x() + rect.get_width() / 2,
-height * .4,
label,
ha='center',
va='bottom',
color=label_color)
if formatter:
ax.xaxis.set_major_formatter(formatter)
if axis_label:
ax.set_xlabel(axis_label)
if title:
fig.suptitle(title, fontsize=14)
fig.subplots_adjust(hspace=0)
# plt.show()
return fig
def _normalize_data(self, data):
"""Normalize data. Scale all data between 0 and 1
and multiply by a fixed value to make sure the graph
looks great.
:param data: the data that needs to be normalized
:return: normalized indicators and prices
"""
bandwith = 0.1
mult_factor = 100
# normalize indicators
graph_data = [data['55DayLow'], data['20DayLow'],
data['20DayHigh'], data['55DayHigh']]
extra_bandwith = data['55DayHigh'] * bandwith
graph_data.insert(0, data['55DayLow'] - extra_bandwith)
graph_data.insert(
len(graph_data),
graph_data[len(graph_data) - 1] + extra_bandwith)
scaled_data = []
max_distance = max(graph_data) - graph_data[0]
scaled_data.append(0)
# numbers = graph_data[1 - len(graph_data):]
sum_scaled_values = 0
for i, d in enumerate(graph_data[1:]):
sum_scaled_values += (graph_data[i + 1] - graph_data[i]) / max_distance
scaled_data.append(sum_scaled_values)
scaled_data = [i * mult_factor for i in scaled_data]
# normalize prices
prices = {}
close_price = data['close']
scaled_close_price = (close_price - min(graph_data)) / \
(max(graph_data) - min(graph_data))
prices['close'] = scaled_close_price * mult_factor
return scaled_data, prices
|
823cf9d7be1ebf0db238e037f1936fa00d6c75d3 | talhahome/codewars | /Oldi3/Buddy_Pairs.py | 1,885 | 4.1875 | 4 | # You know what divisors of a number are. The divisors of a positive integer n
# are said to be proper when you consider only the divisors other than n itself.
# In the following description, divisors will mean proper divisors.
# For example for 100 they are 1, 2, 4, 5, 10, 20, 25, and 50.
#
# Let s(n) be the sum of these proper divisors of n. Call buddy two positive integers such that
# the sum of the proper divisors of each number is one more than the other number:
#
# (n, m) are a pair of buddy if s(m) = n + 1 and s(n) = m + 1
#
# For example 48 & 75 is such a pair:
# Divisors of 48 are: 1, 2, 3, 4, 6, 8, 12, 16, 24 --> sum: 76 = 75 + 1
# Divisors of 75 are: 1, 3, 5, 15, 25 --> sum: 49 = 48 + 1
#
# Task
# Given two positive integers start and limit, the function buddy(start, limit) should return
# the first pair (n m) of buddy pairs such that n (positive integer) is between
# start (inclusive) and limit (inclusive); m can be greater than limit and has to be greater than n
#
# If there is no buddy pair satisfying the conditions, then return "Nothing" or (for Go lang) nil
#
# Examples
# (depending on the languages)
#
# buddy(10, 50) returns [48, 75]
# buddy(48, 50) returns [48, 75]
# or
# buddy(10, 50) returns "(48 75)"
# buddy(48, 50) returns "(48 75)"
from functools import reduce
def buddy(start, limit):
for i in range(start, limit+1):
dev = sorted(factors(i))[:-1]
bud = sum(dev) - 1
if bud > i:
bud_dev = sorted(factors(bud))[:-1]
if sum(bud_dev) - 1 == i:
print([i, bud])
return [i, bud]
print("Nothing")
return "Nothing"
def factors(n):
return set(reduce(list.__add__,
([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0)))
#buddy(10, 50)
#buddy(57345, 90061)
# Ans: [62744, 75495]
buddy(1071625, 1103735)
# Ans: [1081184, 1331967]
|
723f26335ada24311601004e1b8c83fa0d0d1d0e | xnth97/Data-Structure-Notes | /DataStructurePython/heap.py | 2,151 | 3.5625 | 4 | class MaxHeap:
def __init__(self):
self.heap_array = []
def insert(self, key):
new_node = self.Node(key)
self.heap_array.append(new_node)
self.__percolate_up(len(self.heap_array) - 1)
def __percolate_up(self, index: int):
# save the bottom node
bottom = self.heap_array[-1]
# find the initial index value of parent
parent = int((index - 1) / 2)
# while parent's key is smaller than the new key
while index > 0 and self.heap_array[parent].key < bottom.key:
# parent node comes down
self.heap_array[index] = self.heap_array[parent]
index = parent # index moves up
parent = int((parent - 1) / 2)
# finally, insert newly added node into proper position
self.heap_array[index] = bottom
def remove_max(self) -> int:
if not self.heap_array:
return
root = self.heap_array[0]
self.heap_array[0] = self.heap_array[-1]
del self.heap_array[-1]
if self.heap_array:
self.__perculate_down(0)
return root.key
def __perculate_down(self, index):
top = self.heap_array[index]
larger_child = -1 # larger child's index
while index < int(len(self.heap_array) / 2):
left_child = index * 2 + 1
right_child = (index + 1) * 2
# find which one is larger
if right_child < len(self.heap_array) and self.heap_array[left_child].key < self.heap_array[right_child].key:
larger_child = right_child
else:
larger_child = left_child
# no need to go down any more
if self.heap_array[larger_child].key <= top.key:
break
# move the nodes up
self.heap_array[index] = self.heap_array[larger_child]
# index goes down toward larger child
index = larger_child
# put top key into proper location to restore the heap
self.heap_array[index] = top
# Node
class Node:
def __init__(self, key):
self.key = key |
d4eb0130619c7b9110f00211fe47ca8b04279def | nsq974487195/pyldpc | /pyldpc/code.py | 7,736 | 3.515625 | 4 | import numpy as np
from scipy.sparse import csr_matrix
from . import utils
def parity_check_matrix(n, d_v, d_c, seed=None):
"""
Builds a regular Parity-Check Matrix H (n, d_v, d_c) following
Callager's algorithm.
Parameters:
n: Number of columns (Same as number of coding bits)
d_v: number of ones per column (number of parity-check equations including
a certain variable)
d_c: number of ones per row (number of variables participating in a
certain parity-check equation);
Errors:
The number of ones in the matrix is the same no matter how we calculate
it (rows or columns), therefore, if m is
the number of rows in the matrix:
m*d_c = n*d_v with m < n (because H is a decoding matrix) => Parameters
must verify:
0 - all integer parameters
1 - d_v < d_v
2 - d_c divides n
---------------------------------------------------------------------------------------
Returns: 2D-array (shape = (m, n))
"""
rnd = np.random.RandomState(seed)
if n % d_c:
raise ValueError("""d_c must divide n. help(coding_matrix)
for more info.""")
if d_c <= d_v:
raise ValueError("""d_c must be greater than d_v.
help(coding_matrix) for
more info.""")
m = (n * d_v) // d_c
Set = np.zeros((m//d_v, n), dtype=int)
a = m // d_v
# Filling the first set with consecutive ones in each row of the set
for i in range(a):
for j in range(i * d_c, (i+1 * d_c)):
Set[i, j] = 1
# Create list of Sets and append the first reference set
Sets = []
Sets.append(Set.tolist())
# reate remaining sets by permutations of the first set's columns:
i = 1
for i in range(1, d_v):
newSet = rnd.permutation(np.transpose(Set)).T.tolist()
Sets.append(newSet)
# Returns concatenated list of sest:
H = np.concatenate(Sets)
return H
def coding_matrix(X, sparse=True):
"""
CAUTION: RETURNS tG TRANSPOSED CODING X.
Function Applies gaussjordan Algorithm on Columns and rows of X in
order to permute Basis Change matrix using Matrix Equivalence.
Let A be the treated Matrix. refAref the double row reduced echelon Matrix.
refAref has the form:
(e.g) : |1 0 0 0 0 0 ... 0 0 0 0|
|0 1 0 0 0 0 ... 0 0 0 0|
|0 0 0 0 0 0 ... 0 0 0 0|
|0 0 0 1 0 0 ... 0 0 0 0|
|0 0 0 0 0 0 ... 0 0 0 0|
|0 0 0 0 0 0 ... 0 0 0 0|
First, let P1 Q1 invertible matrices: P1.A.Q1 = refAref
We would like to calculate:
P,Q are the square invertible matrices of the appropriate size so that:
P.A.Q = J. Where J is the matrix of the form (having X's shape):
| I_p O | where p is X's rank and I_p Identity matrix of size p.
| 0 0 |
Therfore, we perform permuations of rows and columns in refAref
(same changes are applied to Q1 in order to get final Q matrix)
NOTE: P IS NOT RETURNED BECAUSE WE DO NOT NEED IT TO SOLVE H.G' = 0
P IS INVERTIBLE, WE GET SIMPLY RID OF IT.
Then
solves: inv(P).J.inv(Q).G' = 0 (1) where inv(P) = P^(-1) and
P.H.Q = J. Help(PJQ) for more info.
Let Y = inv(Q).G', equation becomes J.Y = 0 (2) whilst:
J = | I_p O | where p is H's rank and I_p Identity matrix of size p.
| 0 0 |
Knowing that G must have full rank, a solution of (2)
is Y = | 0 | Where k = n-p.
| I-k |
Because of rank-nullity theorem.
-----------------
parameters:
H: Parity check matrix.
sparse: (optional, default True): use scipy.sparse format to speed up
computation.
---------------
returns:
tG: Transposed Coding Matrix.
"""
if type(X) == csr_matrix:
X = X.toarray()
H = X.copy()
m, n = H.shape
# DOUBLE GAUSS-JORDAN:
Href_colonnes, tQ = utils.gaussjordan(np.transpose(H), 1)
Href_diag = utils.gaussjordan(np.transpose(Href_colonnes))
Q = np.transpose(tQ)
k = n - sum(Href_diag.reshape(m*n))
Y = np.zeros(shape=(n, k)).astype(int)
Y[n-k:, :] = np.identity(k)
if sparse:
Q = csr_matrix(Q)
Y = csr_matrix(Y)
tG = utils.binaryproduct(Q, Y)
return H, tG
def coding_matrix_systematic(X, sparse=True):
"""
Description:
Solves H.G' = 0 and finds the coding matrix G in the systematic form :
[I_k A] by applying permutations on X.
CAUTION: RETURNS TUPLE (Hp,tGS) WHERE Hp IS A MODIFIED VERSION OF THE
GIVEN PARITY CHECK X, tGS THE TRANSPOSED
SYSTEMATIC CODING X ASSOCIATED TO Hp. YOU MUST USE THE RETURNED TUPLE
IN CODING AND DECODING, RATHER THAN THE UNCHANGED
PARITY-CHECK X H.
-------------------------------------------------
Parameters:
X: 2D-Array. Parity-check matrix.
sparse: (optional, default True): use scipy.sparse matrices
to speed up computation if n>100.
------------------------------------------------
>>> Returns Tuple of 2D-arrays (Hp,GS):
Hp: Modified H: permutation of columns (The code doesn't change)
tGS: Transposed Systematic Coding matrix associated to Hp.
"""
H = X.copy()
m, n = H.shape
if n > 100 and sparse:
sparse = True
else:
sparse = False
P1 = np.identity(n, dtype=int)
Hrowreduced = utils.gaussjordan(H)
k = n - sum([a.any() for a in Hrowreduced])
# After this loop, Hrowreduced will have the form H_ss : | I_(n-k) A |
while(True):
zeros = [i for i in range(min(m, n)) if not Hrowreduced[i, i]]
indice_colonne_a = min(zeros)
list_ones = [j for j in range(indice_colonne_a+1, n)
if Hrowreduced[indice_colonne_a, j]]
if not len(list_ones):
break
indice_colonne_b = min(list_ones)
aux = Hrowreduced[:, indice_colonne_a].copy()
Hrowreduced[:, indice_colonne_a] = Hrowreduced[:, indice_colonne_b]
Hrowreduced[:, indice_colonne_b] = aux
aux = P1[:, indice_colonne_a].copy()
P1[:, indice_colonne_a] = P1[:, indice_colonne_b]
P1[:, indice_colonne_b] = aux
# NOW, Hrowreduced has the form: | I_(n-k) A | ,
# the permutation above makes it look like :
# |A I_(n-k)|
P1 = P1.T
identity = list(range(n))
sigma = identity[n-k:] + identity[:n-k]
P2 = np.zeros(shape=(n, n), dtype=int)
P2[identity, sigma] = np.ones(n)
if sparse:
P1 = csr_matrix(P1)
P2 = csr_matrix(P2)
H = csr_matrix(H)
P = utils.binaryproduct(P2, P1)
if sparse:
P = csr_matrix(P)
Hp = utils.binaryproduct(H, np.transpose(P))
GS = np.zeros((k, n), dtype=int)
GS[:, :k] = np.identity(k)
GS[:, k:] = (Hrowreduced[:n-k, n-k:]).T
return Hp, GS.T
def make_ldpc(n, d_v, d_c, seed=None, systematic=False, sparse=True):
"""Creates an LDPC coding and decoding matrices H and G.
Parameters:
-----------
n: Number of columns (same as number of coding bits)
d_v: number of ones per column (number of parity-check equations including
a certain variable)
d_c: number of ones per row (number of variables participating in a
certain parity-check equation);
systematic: optional, default False. if True, constructs a systematic
coding matrix G.
Returns:
--------
H: (n, m) array with m.d_c = n.d_v with m < n. parity check matrix
G: (n, k) array coding matrix."""
H = parity_check_matrix(n, d_v, d_c, seed=seed)
if systematic:
H, G = coding_matrix_systematic(H, sparse=sparse)
else:
H, G = coding_matrix(H, sparse=sparse)
return H, G
|
869b7c1209d7863c8052005f2f05488bbb17a9c1 | phibzy/InterviewQPractice | /Solutions/MinimumRemoveToMakeValidParentheses/test.py | 1,209 | 3.6875 | 4 | #!/usr/bin/python3
"""
Test Cases:
- Empty string
- All letters
- Perfectly balanced string
- Starting with closed parentheses
- Starting with open
- Input of length N, output empty string
- Length 1 string, invalid and valid
"""
import unittest
from minRemove import Solution
class test(unittest.TestCase):
a = Solution()
def testBasic(self):
self.assertEqual(self.a.minRemoveToMakeValid(""), "")
self.assertEqual(self.a.minRemoveToMakeValid("nicegary"), "nicegary")
def testBalanced(self):
self.assertEqual(self.a.minRemoveToMakeValid("aa(noice(d))n"), "aa(noice(d))n")
self.assertEqual(self.a.minRemoveToMakeValid("(((((((())))))))"), "(((((((())))))))")
def testInvalid(self):
self.assertEqual(self.a.minRemoveToMakeValid(")aa(noice(d))n"), "aa(noice(d))n")
self.assertEqual(self.a.minRemoveToMakeValid("(aa(noice(d))n"), "aa(noice(d))n")
self.assertEqual(self.a.minRemoveToMakeValid("))))((("), "")
self.assertEqual(self.a.minRemoveToMakeValid("aa(noice(d))n)"), "aa(noice(d))n")
self.assertEqual(self.a.minRemoveToMakeValid("())()((("), "()()")
|
ed4920e82c04dfcb5e887b58d450f8fddb2286ad | halysl/code | /python/fibolique.py | 209 | 3.65625 | 4 | def fib(n):
count = 0
num1 = 1
num2 = 1
while count < n:
result = num1
num1, num2 = num2, num1+num2
count += 1
yield result
f = fib(10)
for i in f:
print(i) |
fd888d0d51184570ed83fb5e2cb92ecd5aafef5b | zerghua/leetcode-python | /N888_FairCandySwap.py | 2,784 | 3.703125 | 4 | #
# Create by Hua on 5/12/22
#
"""
Alice and Bob have a different total number of candies. You are given two integer arrays aliceSizes and bobSizes where aliceSizes[i] is the number of candies of the ith box of candy that Alice has and bobSizes[j] is the number of candies of the jth box of candy that Bob has.
Since they are friends, they would like to exchange one candy box each so that after the exchange, they both have the same total amount of candy. The total amount of candy a person has is the sum of the number of candies in each box they have.
Return an integer array answer where answer[0] is the number of candies in the box that Alice must exchange, and answer[1] is the number of candies in the box that Bob must exchange. If there are multiple answers, you may return any one of them. It is guaranteed that at least one answer exists.
Example 1:
Input: aliceSizes = [1,1], bobSizes = [2,2]
Output: [1,2]
Example 2:
Input: aliceSizes = [1,2], bobSizes = [2,3]
Output: [1,2]
Example 3:
Input: aliceSizes = [2], bobSizes = [1,3]
Output: [2,3]
Constraints:
1 <= aliceSizes.length, bobSizes.length <= 104
1 <= aliceSizes[i], bobSizes[j] <= 105
Alice and Bob have a different total number of candies.
There will be at least one valid answer for the given input.
"""
class Solution(object):
def fairCandySwap(self, aliceSizes, bobSizes):
"""
:type aliceSizes: List[int]
:type bobSizes: List[int]
:rtype: List[int]
thought: math, sort list to make solution o(nlogn) rather than o(n^2),
key is to find the abs(x-y) == abs(sum(a) - sum(b))/2
TLE, this solution is not truly o(nlogn)
second thought: use binary search to make it real o(nlogn)
05/12/2022 11:26 Accepted 551 ms 15.2 MB python
easy - medium 20-30 mins. binary search
better code use set(below solution assumes a >= b):
https://leetcode.com/problems/fair-candy-swap/discuss/161269/C%2B%2BJavaPython-Straight-Forward
def fairCandySwap(self, A, B):
dif = (sum(A) - sum(B)) / 2
A = set(A)
for b in set(B):
if dif + b in A:
return [dif + b, b]
"""
import bisect
is_alice_larger = False
if sum(aliceSizes) >= sum(bobSizes):
is_alice_larger = True
aliceSizes, bobSizes = bobSizes, aliceSizes
diff = (sum(bobSizes) - sum(aliceSizes)) / 2
b = sorted(bobSizes)
for i in sorted(aliceSizes):
v = diff + i
j = bisect.bisect_left(b, v) # j is index
if j != len(bobSizes) and b[j] == v:
if is_alice_larger: return [v,i]
return [i,v]
return None
|
643141e6a3807e3a64619c94a05660f1d4cfb12a | d3athwarrior/LearningPython | /NonSequentialDataTypes.py | 1,405 | 4.625 | 5 | # Dictionaries
# Different ways to declare a dictionary
dict_way_one = {'One': 1, 'Two': 2} # This requires the key, if a string, to be put in double (double) quotes
dict_way_two = dict(One = 1, Two = 2) # This takes in the string as keyword arguments. The part before the = becomes the keys
# Printing the dict
for k, v in dict_way_one.items():
print(f"Key is {k} and value is {v}")
print('Using key in a for loop')
for k in dict_way_two:
print(f"Key is {k} and value is {dict_way_two[k]}")
# Sets
# Different ways to declare sets
set_way_one = {1, 2, 3, 4, 5, 3, 'T', 'w'} # This will create a set
set_way_two = set("Hello! This is way two to declare a set")
# This will not work since it will treat the string as a single object rather than multiple characters
# In order for the set to be able to contain a string split into its independent characters we need to have it added using
# the set() constructor
set_way_three = {"Hello! This is a set."}
set_way_two_obj_two = set("Hello! This is a third way to declare a set.")
print(len(set_way_one))
print(len(set_way_two))
print(len(set_way_three))
# Set operations like union, substraction,
print(f"In set a or set b {set_way_two | set_way_two_obj_two}")
print(f"In set b but not a {set_way_two_obj_two - set_way_two}")
print(f"In either a or b but not both {set_way_two ^ set_way_one}")
print(f"In both a & b {set_way_one & set_way_two}") |
75fb58b0beb1243b6ad53f936bef8cb98b53352a | egyilmaz/mathQuestions | /questions/src/question/year6/Question113.py | 801 | 3.65625 | 4 | import random
from questions.src.question.BaseQuestion import BaseQuestion
from questions.src.question.year6.Types import Types, Complexity
class Question113(BaseQuestion):
def __init__(self):
self.type = [Types.Geometry_circle_perimeter, Types.sat_reasoning]
self.complexity = Complexity.Moderate
diameter = random.choice([40, 50, 90, 100])
self.body = "A car tyre is {0} cm in diameter. what is the area and perimeter of this tyre(Take pi as 3.14)"\
.format(diameter)
perimeter = 3.14*diameter
area = 3.14*(diameter/2)**2
self.res="Perimeter is 2*pi*r = {0} and Area is pi*r^2 = {1}".format(perimeter, area)
def question(self):
return self.body
def answer(self):
return "{res}".format(res=self.res)
|
b50cf08167a4c1484c3bd482935ad18c950beac7 | pengyuhou/git_test1 | /leetcode/234. 回文链表.py | 452 | 3.515625 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
cur = head
ret = []
while cur:
ret.append(cur.val)
cur = cur.next
l = len(ret)
for i in range(l//2):
if ret[i]!=ret[l-1-i]:
return False
return True
|
dfec3abe11bdf547f4bbec1f084e6d88d8a6dbc7 | ChenQQ96/flask_study | /test12.py | 848 | 3.578125 | 4 | #知道一个函数,怎么去获得这个URL呢:通过 url_for(函数名,查询参数)
from flask import Flask,url_for,request
app = Flask(__name__)
@app.route('/',methods=['POST','GET'])
def index():
if request.method=='POST':
return 'POST'
else:
return 'GET'
@app.route('/login/')
def login():
return 'login'
@app.route('/user/<username>/')
def user(username):
return 'Welcome, {}'.format(username)
#url_for这个函数正确运行需要上下文的支持,也就是说要保证url_for这个函数所处的地方必须是一个app里面
#当写在某个响应函数中没有问题,如果在app外面使用url_for的话,可以使用with关键字指定上下文.
with app.test_request_context():
print(url_for('index'))
print(url_for('login'))
print(url_for('user',username='ChenQQ'))
app.run() |
4d337df370d6ba293ff86cc71cb4f5c79ba3c4c8 | FidelNava2002/Actividades-de-python | /condiciones-02.py | 398 | 3.953125 | 4 | """3. - Escribe un programa que pida dos números y que conteste cuál es el menor y
cuál el mayor o que escriba que son iguales."""
n1=int(input("Ingresa el numero 1: "))
n2=int(input("Ingresa el numero 2: "))
if n1>n2:
print(n1, "Es el mayor y ",n2,"es el menor")
elif n1<n2:
print(n2, "Es el mayor y ",n1,"es el menor")
elif n1==n2:
print("Los numeros son iguales")
|
7fb91c0d4c32b04dd5fc1b791b5766aae6ec09de | geniousisme/CodingInterview | /leetCode/Python/157-readNCharsGivenRead4.py | 1,380 | 3.5625 | 4 | # Time: O(n)
# Space: O(1)
#
# The API: int read4(char *buf) reads 4 characters at a time from a file.
#
# The return value is the actual number of characters read. For example, it returns 3 if there is only 3 characters left in the file.
#
# By using the read4 API, implement the function int read(char *buf, int n) that reads n characters from the file.
#
# Note:
# The read function will only be called once for each test case.
#
# The read4 API is already defined for you.
# @param buf, a list of characters
# @return an integer
# def read4(buf):
def read4(buf):
global file_content
i = 0
while i < len(file_content) and i < 4:
buf[i] = file_content[i]
i += 1
if len(file_content) > 4:
file_content = file_content[4:]
else:
file_content = ""
return i
class Solution:
def read(self, buf, n):
idx = 0
buf4 = ['', '', '', '']
while True:
curr = min(read4(buf4), n - idx)
for i in xrange(curr):
buf[idx] = buf4[i]
idx += 1
if curr != 4 or idx == n:
return idx
if __name__ == "__main__":
global file_content
buf = ['' for _ in xrange(100)]
file_content = "a"
print buf[:Solution().read(buf, 9)]
file_content = "abcdefghijklmnop"
print buf[:Solution().read(buf, 9)] |
Subsets and Splits