blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
706288997df87249c95c8fb41e9d351f6c2860fa
|
AcxelMorales/Learn-Python
|
/classes/rectangulo.py
| 444 | 3.765625 | 4 |
class Rectangulo:
def __init__(self, base, altura):
self.base = base
self.altura = altura
def area(self):
return self.base * self.altura
def perimetro(self):
return (self.base + self.altura) * 2
base = float(input("Base: "))
altura = float(input("Altura: "))
rectangulo = Rectangulo(base, altura)
print("Area: {}".format(rectangulo.area()))
print("Perimetro: {}".format(rectangulo.perimetro()))
|
085cf8d2df1a49c87e46a3787266eb0e1806e8ee
|
SabinaZolnowska/JezykPython
|
/zestawyZadan/zestaw4/zd4.4.py
| 398 | 3.953125 | 4 |
#-*- coding: utf-8 -*-
#Napisać iteracyjną wersję funkcji fibonacci(n) obliczającej n-ty wyraz ciągu Fibonacciego.
def fibonacci(n):
if n==0:
wynik=0
return 0
elif n==1:
wynik=1
return 1
elif n>1:
f1=0
f2=1
for i in range(n-1):
temp=f1+f2
f1=f2
f2=temp
return f2
else:
print "Wprowadzono bledne dane"
return -1
n=10
print "F("+str(n)+")="+str(fibonacci(n))
|
c7595bc7ebe34963fd2fd5fc881faf9c0050f6e4
|
rafaelperazzo/programacao-web
|
/moodledata/vpl_data/313/usersdata/303/75391/submittedfiles/imc.py
| 320 | 3.859375 | 4 |
# -*- coding: utf-8 -*-
PESO= float(input('Digite o peso (kg):'))
ALTURA= float(input('Digite a altura (m):'))
IMC= (PESO/(ALTURA**2))
if IMC<20:
print('ABAIXO')
if 20<=IMC<=25:
print('NORMAL')
if 25<IMC<=30:
print('SOBREPESO')
if 30<IMC<=40:
print('OBESIDADE')
if IMC>40:
print('OBESIDADE GRAVE')
|
be828487ad8092023d6f51fba3f5fb9e81516854
|
elsuavila/Python3
|
/Ejercicios Elsy Avila/Ejer14.py
| 390 | 3.84375 | 4 |
#Leer tres numeros entereos de un digito y almacenarlos en una sola variable
#Que contenga a esos tres digitos por ejemplo si A=5 y B=6 y C=2 entomces X=562
print("Bienvedido al Programa".center(50,"-"))
a = ""
b = ""
c = ""
x = ""
a = input("Ingrese primer numero: ")
b = input("Ingrese segundo numero: ")
c = input("Ingrese tercer numero: ")
x = a + b + c
print("X= {}".format(x))
|
4edb73c146d1becdfea673b8a4e94dc76d5f43d6
|
julionieto48/situaciones_jend
|
/sumatoriaTriangularEuler/sumaEuler.py
| 656 | 3.734375 | 4 |
arregloImpar = [1,2,3,4,5] ; arreglopar = [1,2,3,4,5,6]
total = 0
for i in range(len(arregloImpar)):
suma = arregloImpar[i] + arregloImpar[-1]
print suma
arregloImpar.pop(i) ; arregloImpar.pop(i +len(arregloImpar) - 1)
total = total + suma
#print total
print arregloImpar
# https://stackoverflow.com/questions/930397/getting-the-last-element-of-a-list
# https://thispointer.com/python-numpy-select-an-element-or-sub-array-by-index-from-a-ndarray/
# https://es.stackoverflow.com/questions/108027/encontrar-el-ultimo-elemento-del-array
# https://es.stackoverflow.com/questions/47764/manejo-de-un-elemento-de-una-lista-en-python
|
780106ed06f06a52b08cdf61e94df6ea7bce195e
|
mishrakeshav/Competitive-Programming
|
/binarysearch.io/merging_k_sorted_lists.py
| 1,213 | 3.734375 | 4 |
class Solution:
def solve(self, lists):
# Write your code here
new_list = []
def merge(l1,l2,new_list):
n = len(l1)
m = len(l2)
i = 0
j = 0
while i < n and j < m:
if l1[i] < l2[j] :
new_list.append(l1[i])
i += 1
else:
new_list.append(l2[j])
j += 1
if i < n:
while i < n:
new_list.append(l1[i])
i += 1
if j < m:
while j < m:
new_list.append(l2[j])
j += 1
return new_list
if len(lists) == 1:
return lists[0]
new_list = merge(lists[0],lists[1],[])
for i in range(2,len(lists)):
new_list = merge(lists[i],new_list,[])
return new_list
class Solution:
def solve(self, lists):
# Write your code here
new_list = []
for l in lists:
new_list.extend(l)
new_list.sort()
return new_list
|
979213b3fd840286a1ea31c978470c7a59ce61ad
|
praveengadiyaram369/leetcode_submissions
|
/leetcode_189.py
| 696 | 3.6875 | 4 |
# _189. Rotate Array
class Solution:
def rotate(self, nums: List[int], k: int) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
n = len(nums)
k = k%len(nums)
# _solution 1
# nums_updated = nums[(n-k):n]
# nums_updated.extend(nums[0:(n-k)])
# for index, value in enumerate(nums_updated):
# nums[index] = value
# _solution 2
# buffer = [value for value in nums]
# for index, value in enumerate(buffer):
# nums[(index+k) % n] = value
# _solution 3
temp = nums[-k:]
nums[k:] = nums[:-k]
nums[:k] = temp
|
a0761e61e636b12c2ac832860608ff5c3c45b4bc
|
moontree/leetcode
|
/version1/1020_Number_of_Enclaves.py
| 2,889 | 3.796875 | 4 |
"""
Given a 2D array A, each cell is 0 (representing sea) or 1 (representing land)
A move consists of walking from one land square 4-directionally to another land square,
or off the boundary of the grid.
Return the number of land squares in the grid for which
we cannot walk off the boundary of the grid in any number of moves.
Example 1:
Input:
[
[0,0,0,0],
[1,0,1,0],
[0,1,1,0],
[0,0,0,0]
]
Output:
3
Explanation:
There are three 1s that are enclosed by 0s, and one 1 that isn't enclosed because its on the boundary.
Example 2:
Input:
[
[0,1,1,0],
[0,0,1,0],
[0,0,1,0],
[0,0,0,0]
]
Output:
0
Explanation:
All 1s are either on the boundary or can reach the boundary.
Note:
1 <= A.length <= 500
1 <= A[i].length <= 500
0 <= A[i][j] <= 1
All rows have the same size.
"""
class Solution(object):
def numEnclaves(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
q = []
r, c = len(A), len(A[0])
for j in range(c):
if A[0][j] == 1:
q.append([0, j])
A[0][j] = -1
for j in range(c):
if A[-1][j] == 1:
q.append([r - 1, j])
A[-1][j] = -1
for i in range(1, r - 1):
if A[i][0] == 1:
q.append([i, 0])
A[i][0] = -1
for i in range(1, r - 1):
if A[i][-1] == 1:
q.append([i, c - 1])
A[i][-1] = -1
directions = [[-1, 0], [1, 0], [0, 1], [0, -1]]
while q:
i, j = q.pop(0)
for d in directions:
ni, nj = i + d[0], j + d[1]
if 0 <= ni < r and 0 <= nj < c and A[ni][nj] == 1:
q.append([ni, nj])
A[ni][nj] = -1
res = 0
for i in range(1, r - 1):
for j in range(1, c - 1):
if A[i][j] == 1:
res += 1
return res
examples = [
{
"input": {
"A": [
[0, 0, 0, 0],
[1, 0, 1, 0],
[0, 1, 1, 0],
[0, 0, 0, 0]
],
},
"output": 3
}, {
"input": {
"A": [
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 0]
],
},
"output": 0
}
]
import time
if __name__ == '__main__':
solution = Solution()
for n in dir(solution):
if not n.startswith('__'):
func = getattr(solution, n)
print(func)
for example in examples:
print '----------'
start = time.time()
v = func(**example['input'])
end = time.time()
print v, v == example['output'], end - start
|
87c0a4373ba2f270cc25e577d707bc26779b1aea
|
czfyy/Think-Python-2ed
|
/ThinkPython_Exercise12.1.py
| 595 | 3.671875 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 24 15:00:19 2019
@author: czfyy
"""
def frequent(s):
h = histogram(s)
t = []
for x, freq in h.items():
t.append((freq, x))
t.sort(reverse = True)
res = []
for freq, x in t:
res.append(x)
return res
def histogram(s):
hist = {}
for x in s:
hist[x] = hist.get(x, 0) + 1
return hist
def read_file(filename):
return open(filename).read()
string = read_file('theater.txt')
letter_seq = frequent(string)
print(letter_seq)
|
7b778efb517aa9c7f3403b5eaef6b530f14bd74e
|
aakashsbhatia2/Support-Vector-Machine
|
/svm.py
| 6,181 | 3.796875 | 4 |
"""
Imported Libraries
"""
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
import random
import math
def create_data():
"""
Function to create data.
- Here, X0 and y hold the initial points created by make_blobs
- A np.array is created using X0 and y which contains data of the form [1, x1, x2, y] and is stored in data_final
- This function returns data_final
"""
X0, y = make_blobs(n_samples=100, n_features = 2, centers=2, cluster_std=1.05, random_state=10)
X0 = X0.tolist()
for i in range(len(X0)):
X0[i].insert(0, 1)
if y[i] == 0:
X0[i].append(-1)
else:
X0[i].append(1)
data_final = np.array(X0)
return data_final
def split_data(data_final):
"""
Function to split data.
- The fina_data array is split into the training dataset and testing dataset
- 80% train
- 20% test
- The data is split AFTER shuffling [code in main function]
"""
samples_test = data_final[80:]
samples_train = data_final[:80]
return samples_train, samples_test
def train(samples_train, T):
"""
Function to train SVM model.
- This function takes input as the training samples and number of epochs
- While the algorithm has not converged (i.e. we have not found the optimal hyperplane)
- A random point is select
- If y*(<w,x>) <1: We update weight vector
- Check if the support vector is on either side, equidistant and the hyperplane perfectly seperates the two clusters
- terminate
"""
w = np.array([0,0,0])
lmd = 3
converged = False
t = 0
min_distance_negative = 0
min_distance_positive = 0
while(converged == False) and t < T:
t +=1
sample = int(random.uniform(0,len(samples_train)-1))
x_i = samples_train[sample][:-1]
y_i = samples_train[sample][-1]
n_t = 1/(t*lmd)
if (y_i*np.dot(x_i,w)) < 1:
w[1:] = (1-n_t*lmd)*w[1:] + (n_t*y_i*x_i[1:])
#Calculating bias independantly
w[0] = w[0] + (y_i*x_i[0])
else:
w = (1-n_t*lmd)*w
min_distance_positive, min_distance_negative, converged = check_support_vectors(samples_train, w)
print("=================\n")
print("Number of iterations to Converge: ", t)
draw(samples_train, samples_train, min_distance_negative, min_distance_positive, w,"Train Plot")
return w, min_distance_negative, min_distance_positive
def check_support_vectors(samples_train, w):
"""
Here, we identify the support vectors for each weight vectort and see if it is equidistant from w
"""
min_distance_positive = 999.0
min_distance_negative = 999.0
for i in samples_train:
x1 = i[1]
x2 = i[2]
y = i[3]
try:
d = abs(w[1]*x1 + w[2]*x2 + w[0])/ (math.sqrt(w[1]**2) + (math.sqrt(w[2]**2)))
if y == -1:
if d<=min_distance_negative:
min_distance_negative = d
else:
if d<=min_distance_positive:
min_distance_positive = d
except:
pass
if round(min_distance_positive,1) == round(min_distance_negative,1):
return round(min_distance_positive)+0.6, round(min_distance_negative)+0.6, True
else:
return 1,1,False
def draw(samples_train, samples_test, min_distance_negative, min_distance_positive, w, plot_type):
"""
Generating the scatter plot for the trained samples and corresponding tested samples
"""
if plot_type == "Train Plot":
plt.scatter(samples_train[:, 1], samples_train[:, 2], c=samples_train[:, 3], edgecolor="black")
ax = plt.gca()
ax.set_facecolor('red')
ax.patch.set_alpha(0.1)
xlim = ax.get_xlim()
xx = np.linspace(xlim[0], xlim[1])
yy = -(w[1]/w[2]) * xx - (w[0]/w[2])
yy1 = min_distance_positive-(w[1]/w[2]) * xx - (w[0]/w[2])
yy2 = -min_distance_negative-(w[1]/w[2]) * xx - (w[0]/w[2])
plt.plot(xx, yy, c="r")
plt.plot(xx, yy1, c="g", linestyle = "dashed")
plt.plot(xx, yy2, c="g", linestyle = "dashed")
plt.show()
if plot_type == "Test Plot":
plt.scatter(samples_train[:, 1], samples_train[:, 2], c=(samples_train[:, 3]), edgecolor="black")
plt.scatter(samples_test[:, 1], samples_test[:, 2], c='r', marker="D", edgecolor="black")
ax = plt.gca()
ax.set_facecolor('red')
ax.patch.set_alpha(0.1)
xlim = ax.get_xlim()
xx = np.linspace(xlim[0], xlim[1])
yy = -(w[1]/w[2]) * xx - (w[0]/w[2])
yy1 = min_distance_positive-(w[1]/w[2]) * xx - (w[0]/w[2])
yy2 = -min_distance_negative-(w[1]/w[2]) * xx - (w[0]/w[2])
plt.plot(xx, yy, c="r")
plt.plot(xx, yy1, c="g", linestyle = "dashed")
plt.plot(xx, yy2, c="g", linestyle = "dashed")
plt.show()
def test(sample_train, samples_test, w, min_distance_negative, min_distance_positive, plot_type):
"""
Function to test SVM Model
"""
errors = 0
for i in samples_test:
prediction = np.dot(i[:-1], w)
if prediction<0 and i[-1] == 1:
errors +=1
elif prediction>0 and i[-1] == -1:
errors +=1
print("\nTotal Points trained: ", len(sample_train))
print("\nTotal Points tested: ", len(samples_test))
print("\nTotal Points Misclassified: ", errors)
print("\n=================")
draw(sample_train, samples_test, min_distance_negative, min_distance_positive, w, plot_type)
def main():
#Generate dataset
data_final = create_data()
#Generate Train and Test splot
samples_train, samples_test = split_data(data_final)
#Calculate weight vector and Support vectors by training model. T = 150,000
w, min_distance_negative, min_distance_positive = train(samples_train, T = 150000)
#Test SVM Model
test(samples_train, samples_test, w, min_distance_negative, min_distance_positive, "Test Plot")
if __name__ == '__main__':
main()
|
98bafe96c28c3fbaff44665364863e54597b20a4
|
prateek1192/leetcode
|
/invest.py
| 1,525 | 3.546875 | 4 |
import sys
from collections import OrderedDict
range = input().split(", ")
starting_date = range[0]
ending_date = range[1]
line = input()
dates = OrderedDict()
while True:
try:
line = input()
data = line.split(",")
datemon = data[0]
if datemon > starting_date and datemon < ending_date:
datemo = datemon[0:7]
if datemo not in dates:
dates[datemo] = {}
if data[1]in dates[datemo]:
dates[datemo][data[1]] = int(dates[datemo][data[1]]) + int(data[2])
else:
dates[datemo].update({data[1] : data[2]})
except EOFError:
keys = sorted(dates.keys(), reverse = True)
for key in keys:
if len(dates[key]) > 1:
#inner_keys = sorted(dates[key].keys())
str = "".join("{!s},{!r},".format(key,val) for (key,val) in sorted(dates[key].items()))
str = str.replace("'","")
str = str.rstrip(",")
print (key+","+str)
#text = ""
#for inner_key in inner_keys:
# text = text + inner_key + ((dates[key][inner_key]))
#print (text)
else:
str = "".join("{!s},{!r}".format(key,val) for (key,val) in dates[key].items())
str = str.replace("'","")
print (key+","+str)
#print ( key + ", "+str(dates[key].keys()))
#print (dates)
break
|
62a1bdba720411b34e56927b63b51c9e5236e35c
|
GabrielaVargas/Tarea-02
|
/auto.py
| 691 | 4.03125 | 4 |
#encoding: UTF-8
# Autor: Gabriela Mariel Vargas Franco, A01745775
# Descripcion: Preguntar al usario la velocidad a la que viaja un auto (km/h) y que imprima: la distancia en km que recorre en 6 hrs, la distancia en km que recorre en 10hrs y el tienpo que requiere para recorrer 500 km.
# A partir de aquí escribe tu programa
strVelocidad= input("¿Velocidad?")
Velocidad=int(strVelocidad)
#1.
tiempo=6
distancia= Velocidad*tiempo
print("Distancia recorrida en 6hrs:", distancia, "km")
#2.
tiempo=10
distancia= Velocidad*tiempo
print("Distancia recorrida en 10hrs:", distancia, "km")
#3.
distancia=500
tiempo=distancia/Velocidad
print("Tiempo para recorrer 500 km:", tiempo, "hrs")
|
0650f0c431ed095b03dc2cd1917cd1d20124216f
|
python-programming-1/homework-2b-mfreyer12
|
/RockPaperScissors.py
| 2,390 | 4.03125 | 4 |
import random
player_score = 0
computer_score = 0
passed_name = False
while True:
if not passed_name:
print('make a move! (r/p/s)')
player_roll = input()
if player_roll.lower() not in ('r','s','p'):
continue
passed_name = True
if passed_name:
random_roll = ''
for num in range(1):
random_roll = random.randint(1,3)
#print(roll)
hand = ''
if random_roll == 3:
computer_roll = 's'
elif random_roll == 2:
computer_roll = 'r'
else: computer_roll = 'p'
print(computer_roll)
#player_roll = ''
#computer_roll = ''
def results(computer_roll):
if player_roll == 'p':
if computer_roll == 'r':
return 'you win'
elif computer_roll == 's':
return 'you lose'
elif computer_roll == 'p':
return 'we tie'
elif player_roll == 'r':
if computer_roll == 's':
return 'you win'
elif computer_roll == 'p':
return 'you lose'
elif computer_roll == 'r':
return 'we tie'
elif player_roll == 's':
if computer_roll == 'p':
return 'you win'
elif computer_roll == 'r':
return 'you lose'
elif computer_roll == 's':
return 'we tie'
outcome = results(computer_roll)
print(outcome)
#outcome = 'you win'
if outcome == 'you win':
player_score = player_score + 1
elif outcome == 'you lose':
computer_score = computer_score + 1
print('player ' + str(player_score) + ' / computer ' + str(computer_score))
while True:
print('Would you like to play again? (y/n)')
continue_playing = input()
if continue_playing.lower() not in ('y','n'):
print('please chose y or n')
continue
elif continue_playing.lower() == 'y':
is_no = False
passed_name = False
break
elif continue_playing.lower() == 'n':
print('thank you for playing, goodbye')
exit(0)
|
ae5c9b55ac128233fd5cdff91059777d5e9e8b60
|
as030pc/MisionTIC
|
/Fundamentos de Programacion - Python/Semana 6/Archivos/basic ej1.py
| 441 | 3.796875 | 4 |
import json
"""CREAR Y LEER JSON"""
"""crear diccionario"""
dicc={"nombre":"paola", "edad":20}
"""escribir archivo json"""
with open("test.json", "w") as fl: #w: escribirlo, fl es un alias
json.dump(dicc, fl,indent=4) #indent: da una estructura de identacion
"""leer un json"""
with open("test.json", "r") as fl:
dicc=json.load(fl) ##convierte el json a un diccionario
print(dicc)
print(type(dicc))
print(dicc["nombre"])
|
18d1518d344503233321d3bef473fccbfaa1c24f
|
slahmar/advent-of-code-2018
|
/23-01.py
| 776 | 3.59375 | 4 |
from dataclasses import dataclass
@dataclass
class Nanobot:
position: tuple
radius: int
def distance(self, other):
return sum([abs(a-b) for (a,b) in zip(self.position, other.position)])
def in_range(self, other):
return self.distance(other) <= self.radius
with open('23.txt', 'r') as file:
lines = file.read().splitlines()
nanobots = [Nanobot(tuple(map(int, line[line.index("<")+1:line.index(">")].split(","))), int(line[line.index("r")+2:])) for line in lines]
strongest = max(nanobots, key=lambda nanobot: nanobot.radius)
in_range = 0
for bot in nanobots:
if strongest.in_range(bot):
in_range += 1
print(f'{in_range} nanobots are in range of the strongest nanobot {strongest}')
|
94dfc08b7f340472cf0387273b6b206498540bbb
|
boknowswiki/mytraning
|
/lintcode/python/0585_maximum_number_in_mountain_sequence.py
| 2,150 | 3.90625 | 4 |
#!/usr/bin/python3 -t
# binary search
# time O(logn)
# space O(1)
from typing import (
List,
)
class Solution:
"""
@param nums: a mountain sequence which increase firstly and then decrease
@return: then mountain top
"""
def mountain_sequence(self, nums: List[int]) -> int:
# write your code here
n = len(nums)
if n == 0:
return 0
start = 0
end = n-1
while start + 1 < end:
mid = start + (end-start)//2
if nums[mid] > nums[mid+1]:
end = mid
else:
start = mid
return max(nums[start], nums[end])
if __name__ == '__main__':
s = Solution()
a = [1,2,4,8,6,3]
a = [10, 9, 8]
a = [1,2,3]
print(s.mountain_sequence(a))
# binary search same as 0075
# better and cleaner
class Solution:
"""
@param nums: a mountain sequence which increase firstly and then decrease
@return: then mountain top
"""
def mountainSequence(self, nums):
# write your code here
n = len(nums)
if n == 0:
return 0
l = 0
r = n-1
while l+1 < r:
mid = (l+r)/2
if nums[mid] < nums[mid+1]:
l = mid
else:
r = mid
return max(nums[l], nums[r])
class Solution:
"""
@param nums: a mountain sequence which increase firstly and then decrease
@return: then mountain top
"""
def mountainSequence(self, nums):
# write your code here
n = len(nums)
if n == 0:
return 0
l = 0
r = n-1
while l < r:
mid = (l+r)/2
if nums[mid] > nums[mid-1] and nums[mid] > nums[mid+1]:
return nums[mid]
elif nums[mid] < nums[mid+1]:
l = mid+1
else:
r = mid
print l
return nums[l]
if __name__ == '__main__':
s = [60]
ss = Solution()
print "answer is\n"
print ss.mountainSequence(s)
|
2dbbdef34ef23cfeeea3e3c7dba30aad1f31a055
|
zlc18/LocalJudge
|
/tests/python/SecondMinimumNodeInABinaryTree/findSecondMinimumValue.py
| 705 | 4.03125 | 4 |
"""
because of the special porperty of the tree, the question basically is asking to find
the smallest element in the subtree of root. So, we can recursively find left and right
value that is not equal to the root's value, and then return the smaller one of them
"""
def findSecondMinimumValue(self, root):
if not root: return -1
if not root.left and not root.right: return -1
left, right = root.left.val, root.right.val
if left == root.val: left = self.findSecondMinimumValue(root.left)
if right == root.val: right = self.findSecondMinimumValue(root.right)
if left != -1 and right != -1: return min(left, right)
if left == -1: return right
if right == -1: return left
|
8a5261e614bb9beb6ca5366055595f39f83ef566
|
devendraingale2/PythonPrograms
|
/soln3.py
| 257 | 3.828125 | 4 |
dict1 = dict(input("Enter key and value : ").split() for i in range(int(input("Enter range : "))))
print(dict1)
str1 = ""
for a in dict1:
for b in dict1:
if(a == dict1[b]):
str1 = a
break
dict1.pop(str1)
print(dict1)
|
2521ae4bc34ea0ffa306ddcfe0b1c594aa74aee5
|
Shu-HowTing/Code-exercises
|
/E13.py
| 1,996 | 3.75 | 4 |
# -*- coding: utf-8 -*-
# Author: 小狼狗
'''
请设计一个函数,用来判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,
每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
例如: a b c e s f c s a d e e 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,
因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。
'''
'''
问题所在:如果此路不通,matrix[i*cols+j]='0',如何将matrix恢复到原始状态
matrix = [[a, b, t, g],
[c, f, c, s],
[j, d, e, h]]
path = b->f->c->j->d->e->c
答案为true, 但测试结果为false
'''
class Solution:
def hasPath(self, matrix, rows, cols, path): #matrix只是一行字符串
# write code here
for i in range(rows):
for j in range(cols):
if matrix[i*cols+j] == path[0]:
if self.find(list(matrix),rows,cols,path[1:],i,j): #下一个
return True
return False
def find(self,matrix,rows,cols,path,i,j):
if not path:
return True
matrix[i*cols+j]='0'
if j+1<cols and matrix[i*cols+j+1]==path[0]:
return self.find(matrix,rows,cols,path[1:],i,j+1)
elif j-1>=0 and matrix[i*cols+j-1]==path[0]:
return self.find(matrix,rows,cols,path[1:],i,j-1)
elif i+1<rows and matrix[(i+1)*cols+j]==path[0]:
return self.find(matrix,rows,cols,path[1:],i+1,j)
elif i-1>=0 and matrix[(i-1)*cols+j]==path[0]:
return self.find(matrix,rows,cols,path[1:],i-1,j)
else:
return False
if __name__ == '__main__':
S = Solution()
print(S.hasPath("abtgcfcsjdeh", 3, 4, 'bfcjdec'))
|
eed71f7fd0c53ef13cf4259fff04bf489600d298
|
qwedsafgt/hha
|
/alien_invasion.py
| 1,271 | 3.5625 | 4 |
import pygame#导入pygame
from pygame.sprite import Group#导入group类
from settings import Settings#导入settings类
from ship import Ship#导入ship类
import game_functions as gf#导入game_functions类作为gf
def run_game():#运行程序的主要函数
# Initialize pygame, settings, and screen object.
pygame.init()#使pygame初始化
ai_settings = Settings()#实例化类
screen = pygame.display.set_mode(
(ai_settings.screen_width, ai_settings.screen_height))#创建背景surface
pygame.display.set_caption("Alien Invasion")#为背景添上名字
# Set the background color.
bg_color = (230, 230, 230)#设置背景颜色
# Make a ship.
ship = Ship(ai_settings, screen)#创建一个ship对象
# Make a group to store bullets in.
bullets = Group()#创建GROUP实例
# Start the main loop for the game.
while True:#管理程序的主循环
gf.check_events(ai_settings, screen, ship, bullets)#检测键盘的按键 #处理用户使用空格键时处理bullets
ship.update()#使飞船图像得到更新
gf.update_bullets(bullets)#使子弹图像得到更新
gf.update_screen(ai_settings, screen, ship, bullets)#使更新的图像得到显示
run_game()#运行程序
|
4322742f04cd515a17f3840965fc7e6bf0d09b62
|
mamaluigie/Code-Wars
|
/python/Convert-A-Hex-String-To-RGB.py
| 445 | 3.671875 | 4 |
import string
def hex_string_to_RGB(hex_string):
# your code here
string_list = []
dictionary = {'r': 0, 'g': 0, 'b': 0}
for begin, end in zip(range(1, len(hex_string), 2), range(3, len(hex_string) + 1, 2)):
string_list.append(hex_string[begin:end].lower())
for x, entry in zip(string_list, dictionary):
dictionary[entry] = int(x, 16)
return dictionary
print(hex_string_to_RGB("#FF9933"))
|
ccfb1bf83219ad7d4bdc2d348492b1f32ff7ba90
|
yaswanthkumartheegala/py
|
/factorial.py
| 126 | 4.15625 | 4 |
n=int(input('enter the number:'))
result=1
for i in range(n,0,-1):
result=result*i
print('factorial of',n,'is',result)
|
7a4794b1b1987f6c816a27f4fb548211e06559dd
|
achrefbs/holbertonschool-interview
|
/0x19-making_change/0-making_change.py
| 578 | 3.9375 | 4 |
#!/usr/bin/python3
"""
Given a pile of coins of different values, determine the fewest
number of coins needed to meet a given amount total.
"""
def makeChange(coins, total):
"""
Given a pile of coins of different values, determine the fewest
number of coins needed to meet a given amount total.
"""
sum = 0
if (total <= 0):
return 0
coins.sort(reverse=True)
for i in coins:
if (total < i):
pass
q, r = divmod(total, i)
total = r
sum += q
if (total != 0):
return -1
return sum
|
658380398f1482a0afa3e31bcb780a63338354f1
|
Alex-Beng/ojs
|
/FuckLeetcode/199.二叉树的右视图.py
| 838 | 3.59375 | 4 |
#
# @lc app=leetcode.cn id=199 lang=python3
#
# [199] 二叉树的右视图
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def rightSideView(self, root: TreeNode) -> [int]:
ans = []
def caoOrder(nodes):
ans.append(nodes[-1].val)
nnodes = []
for node in nodes:
if node.left is not None:
nnodes.append(node.left)
if node.right is not None:
nnodes.append(node.right)
if len(nnodes):
caoOrder(nnodes)
if not root:
return []
caoOrder([root])
return ans
# @lc code=end
|
420b7fe2d8f259a3f7312669bebd4d395f94d3d7
|
dorotamierzwa/PyLove-workshops
|
/Week 10 - repetition/10.8-figures.py
| 1,931 | 3.875 | 4 |
# Stwórz - z wykorzystaniem klas i dziedziczenia - kalkulator objętości brył:
# sześcianu, prostopadłościanu, stożka i walca.
# Powinien on wczytać od użytkownika opcję (0, 1, 2 lub 3) i w zależności od tego przyjąć
# 3 argumenty, 2 lub 1 i obliczyć objętość. Na wszelki wypadek wzory na objętość podane poniżej.
# Sześcian: V = a^3
# Prostopadłościan: V = a*b*c
# Kula: V = 4/3 * pi * r^3
from math import pi
class Szescian():
def __init__(self, a):
self.a = a
def obj_szesc(self):
return print("Objetosc szescianu wynosi", self.a ** 3)
class Prostopadloscian(Szescian):
def __init__(self, b, h, *args):
self.b = b
self.h = h
super(Prostopadloscian, self).__init__(*args)
def obj_prost(self):
return print("Objetosc prostopadloscianu wynosi", self.a * self.b * self.h)
class Stozek():
def __init__(self, r, h):
self.r = r
self.h = h
def obj_stoz(self):
return print("Objetosc stozka wynosi", self.h * pi * 1/3 * self.r)
class Walec(Stozek):
def __init__(self, *args):
super(Walec, self).__init__(*args)
def obj_wal(self):
return print("Objetosc walca wynosi", self.h * pi * self.r)
choice = input("Podaj jaka bryle chcesz policzyc:\n"
"1 - Szescian\n"
"2 - Prostopadloscian\n"
"3 - Stozek\n"
"4 - Walec\n")
if choice == '1':
a = int(input("Bok a: "))
sz1 = Szescian(a)
sz1.obj_szesc()
elif choice == '2':
a = int(input("Bok a: "))
b = int(input("Bok b: "))
h = int(input("Wysokosc: "))
p1 = Prostopadloscian(a, b, h)
p1.obj_prost()
elif choice == '3':
r = int(input("Promien: "))
h = int(input("Wysokosc: "))
s1 = Stozek(r, h)
s1.obj_stoz()
elif choice == '4':
r = int(input("Promien: "))
h = int(input("Wysokosc: "))
w1 = Walec(r, h)
w1.obj_wal()
else:
print("Invalid input")
|
a63514a385ec52bb3a563ea67b52bee89d241e68
|
telavivmakers/at-tami
|
/gerber/gerbmerge/bin/placement.py
| 3,291 | 4 | 4 |
#!/usr/bin/env python
"""A placement is a final arrangement of jobs at given (X,Y) positions.
This class is intended to "un-pack" an arragement of jobs constructed
manually through Layout/Panel/JobLayout/etc. (i.e., a layout.def file)
or automatically through a Tiling. From either source, the result is
simply a list of jobs.
--------------------------------------------------------------------
This program is licensed under the GNU General Public License (GPL)
Version 3. See http://www.fsf.org for details of the license.
Rugged Circuits LLC
http://ruggedcircuits.com/gerbmerge
"""
import sys
import re
import parselayout
import jobs
class Placement:
def __init__(self):
self.jobs = [] # A list of JobLayout objects
def addFromLayout(self, Layout):
# Layout is a recursive list of JobLayout items. At the end
# of each tree there is a JobLayout object which has a 'job'
# member, which is what we're looking for. Fortunately, the
# canonicalize() function flattens the tree.
#
# Positions of jobs have already been set (we're assuming)
# prior to calling this function.
self.jobs = self.jobs + parselayout.canonicalizePanel(Layout)
def addFromTiling(self, T, OriginX, OriginY):
# T is a Tiling. Calling its canonicalize() method will construct
# a list of JobLayout objects and set the (X,Y) position of each
# object.
self.jobs = self.jobs + T.canonicalize(OriginX,OriginY)
def extents(self):
"""Return the maximum X and Y value over all jobs"""
maxX = 0.0
maxY = 0.0
for job in self.jobs:
maxX = max(maxX, job.x+job.width_in())
maxY = max(maxY, job.y+job.height_in())
return (maxX,maxY)
def write(self, fname):
"""Write placement to a file"""
fid = file(fname, 'wt')
for job in self.jobs:
fid.write('%s %.3f %.3f\n' % (job.job.name, job.x, job.y))
fid.close()
def addFromFile(self, fname, Jobs):
"""Read placement from a file, placed against jobs in Jobs list"""
pat = re.compile(r'\s*(\S+)\s+(\S+)\s+(\S+)')
comment = re.compile(r'\s*(?:#.+)?$')
try:
fid = file(fname, 'rt')
except:
print 'Unable to open placement file: "%s"' % fname
sys.exit(1)
lines = fid.readlines()
fid.close()
for line in lines:
if comment.match(line): continue
match = pat.match(line)
if not match:
print 'Cannot interpret placement line in placement file:\n %s' % line
sys.exit(1)
jobname, X, Y = match.groups()
try:
X = float(X)
Y = float(Y)
except:
print 'Illegal (X,Y) co-ordinates in placement file:\n %s' % line
sys.exit(1)
rotated = 0
if len(jobname) > 8:
if jobname[-8:] == '*rotated':
rotated = 90
jobname = jobname[:-8]
elif jobname[-10:] == '*rotated90':
rotated = 90
jobname = jobname[:-10]
elif jobname[-11:] == '*rotated180':
rotated = 180
jobname = jobname[:-11]
elif jobname[-11:] == '*rotated270':
rotated = 270
jobname = jobname[:-11]
addjob = parselayout.findJob(jobname, rotated, Jobs)
addjob.setPosition(X,Y)
self.jobs.append(addjob)
|
3653061fd40826b990eb4a4430003e706165631b
|
YuduDu/cracking-the-coding-interview
|
/1.4.py
| 298 | 3.75 | 4 |
#!/usr/bin/python
from pprint import pprint
def replace(s,len):
tmp = s[:len].split(" ")
result = ""
for item in tmp:
if item != "":
result = result+item+"%20"
return result[:-3]
print replace("asd fasd fadsf a sdf at ees d fs df sdf sdf dasfhuadsf asdfad asdfaesdfs ",80)
|
519112166b8d4821e6f51810e9955a254be9a358
|
mehulchopradev/ava-python-core
|
/author.py
| 860 | 3.5 | 4 |
from address import Address
class Author:
def __init__(self, name, gender, ratings, address=None):
self.name = name
self.gender = gender
self.ratings = ratings
if isinstance(address, Address):
# composition association
# where the Address obj exists in the system only till the Author obj exists
self.address = address
else:
self.address = None
def get_details(self):
part1 = 'Name : {0}\nGender : {1}\nRatings: {2}\n'.format(self.name, self.gender, self.ratings)
if self.address is not None:
part2 = self.address.get_details()
else:
part2 = 'Address : NA'
return part1 + part2
if __name__ == '__main__':
addr1 = Address('India', 'MH', 'Mumbai', '400053')
a1 = Author('mehul', 'm', 5, addr1)
a2 = Author('jane', 'f', 4)
print(a1.get_details())
print(a2.get_details())
|
b38659e37e8f59d72f2f84337dae92859f9d9cea
|
SarveshSiddha/Demo-repo
|
/assignment3/F.py
| 191 | 4.125 | 4 |
#print F using *
for i in range(0,6):
for j in range(0,5):
if i==0 or i==2 or j==0:
print("*",end='');
else:
print(" ",end='')
print("");
|
dd08866556ea8bbe992410b09e1f45fa4b4243c9
|
jasongan234/CP1401p
|
/sales_bonus.py
| 472 | 3.875 | 4 |
def main():
""" Program to calculate and display a user's bonus based on sales.
If sales are under $1,000, the user gets a 10% bonus.
If sales are $1,000 or over, the bonus is 15%."""
sales = float(input("Enter sales: $"))
while sales >=0:
if sales<1000:
bonus= sales* 10//100
elif sales>=1000:
bonus= sales*15//100
print(bonus)
sales = float(input("Enter sales: $"))
print(bonus)
main()
|
11d1c1c5e09650dd5627ebf221a74dcf00d9ad48
|
NickWilsonDev/python-DigitalCrafts
|
/python105/blastoff4.py
| 195 | 3.765625 | 4 |
# blastoff4.py
num = 22
while num > 20:
num = int(raw_input("Number to count down from? "))
i = num
while i > -1:
if i == 0:
print "Boom!"
else:
print i
i -= 1
|
5ca2922226b5715a2e94c49da5706e4931c2633b
|
Darkseidddddd/project
|
/leetcode/Search_in_Rotated_Sorted_Array.py
| 1,665 | 3.859375 | 4 |
def search(nums, target):
if not nums:
return -1
n = len(nums)
left, right = 0, n-1
if target == nums[0]:
return 0;
if target == nums[n-1]:
return n-1;
if target >= nums[0]:
while left <= right:
mid = (left+right) // 2
if nums[mid] == target:
return mid
if nums[mid] > target or (nums[mid] <= nums[n-1] and nums[n-1] < nums[0]):
right = mid - 1
else:
left = mid + 1
else:
while left <= right:
mid = (left+right) // 2
if nums[mid] == target:
return mid
if nums[mid] < target or nums[mid] >= nums[0]:
left = mid + 1
else:
right = mid - 1
return -1
def search_(nums, target):
n = len(nums)
left, right = 0, n-1
if n == 0:
return -1
if n == 1 and target != nums[0]:
return -1
while left < right:
mid = (left+right) // 2
if nums[mid] > nums[left]:
left = mid
else:
right = mid
if target >= nums[0] and target <= nums[left]:
right = left
left = 0
elif target >= nums[left+1] and target <= nums[n-1]:
right = n-1
left += 1
else:
return -1
while left <= right:
mid = (left+right) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return -1
if __name__ == '__main__':
nums = [5,6,7,8,0,1,2,3,4]
target = 1
print(search_(nums, target))
|
242d015ab13dab743a6291419862235b67a8f362
|
jmmunoza/ST0245-008
|
/Parcial_2/7.py
| 1,223 | 3.65625 | 4 |
class Pila:
def __init__(self):
self.items = []
def __str__(self):
return str(self.items)
def no_vacia(self):
return len(self.items) == 0
def promedio(self):
sum = self.items[0]
for i in range(len(self.items)-1):
sum = sum+self.items[i+1]
prom = sum/len(self.items)
return prom
def getTop(self):
return self.items[len(self.items)-1]
def inspeccionar(self):
assert not self.verificar()
return self.items[-1]
def apilar(self, elemento):
self.items.append(elemento)
def desapilar(self):
assert not self.no_vacia()
return self.items.pop()
def peek(self):
if len(self.items)>0:
return self.items[-1]
else:
return None
def invertir_pila(pila):
pila_invertida = Pila()
while not pila.no_vacia():
pila_invertida.apilar(pila.getTop())
pila.desapilar()
return pila_invertida
pila = Pila()
pila.apilar(1)
pila.apilar(2)
pila.apilar(3)
pila.apilar(4)
pila.apilar(5)
pila.apilar(6)
print(pila.items)
pila = invertir_pila(pila)
print(pila.items)
|
8b436d72a70152991de14e636cc7cb9862c13510
|
zhangquanliang/python
|
/学习/day8_笔试题/列表.py
| 351 | 4.0625 | 4 |
# -*- coding:utf-8 -*-
"""
author = zhangql
"""
# def f(x, l=[]):
# for i in range(x):
# l.append(i*i)
# print(l)
#
#
# f(2)
# f(3, [3,2,1])
# f(3)
#
# A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))
# print(AO) {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# 生成器
def func():
yield '1'
a = func()
for i in a:
print(i)
|
889f22752128d186670e9673ec28240fcea41af0
|
wiamsuri/intro-to-programming
|
/0-data-type-and-operators/2-comparison.py
| 438 | 3.59375 | 4 |
bangkok_population = 8281000
chiang_mai_population = 131091
phuket_population = 386605
buriram_population = 1579000
# Print True or False from the statement
# Bangkok population is smaller than Chiang Mai
print()
# Chiang Mai population is smaller than Phuket
print()
# Buriram population is larger than Bangkok
print()
# Buriram population is equal to Phuket
print()
# Chiang Mai population is not equal to Buriram
print()
|
fc60d27952496a64b5af1fd035642f9a9416b7ae
|
krstoilo/SoftUni-Fundamentals
|
/Python-Fundamentals/Exams/world_tour.py
| 1,061 | 3.640625 | 4 |
initial_stops = input()
command = input()
while command != "Travel":
if "Add" in command:
command = command.replace("Add ","")
token = command.split(":")
index = int(token[1])
stop_string = token[2]
if index < len(initial_stops):
initial_stops = initial_stops[:index] + stop_string + initial_stops[index:]
print(initial_stops)
elif "Remove" in command:
token = command.split(":")
start_index = int(token[1])
end_index = int(token[2])
if start_index < len(initial_stops) and end_index < len(initial_stops):
initial_stops = initial_stops[:start_index] + initial_stops[end_index+1:]
print(initial_stops)
elif "Switch" in command:
token = command.split(":")
old_str = token[1]
new_str = token[2]
if old_str in initial_stops:
initial_stops = initial_stops.replace(old_str, new_str)
print(initial_stops)
command = input()
print(f"Ready for world tour! Planned stops: {initial_stops}")
|
0cf23cf79002ab1fa4f90d011b964270fd6bda80
|
stulsani/Academic-Related-Projects
|
/Python-Library-Project/main.py
| 2,280 | 3.9375 | 4 |
#Sumeet Tulsani
from searchengine import Searchengine
from media import Media
def main():
choice = 'y'
matches = list()
while(choice == 'Y' or choice == 'y'):
print ("What type of search would you like to do::");
print (" 1. Search by Title\n 2. Search by Call Number\n 3. Search by Subject\n 4. Search by Other\n 5. Exit");
searchby = input();
choice = 'n'
if searchby < "1" or searchby > "5":
print("Invalid Choice, Please enter a valid choice");
if searchby >= "1" and searchby <= "4":
print ("Enter the string you would like to search");
searchthis = input();
if searchby == "1":
obj = Searchengine()
matches = obj.search_by_title(searchthis)
i = 0
size = len(matches)
while i != size:
matches[i].display()
i = i + 1
print("--------TOTAL SEARCHES-------\n Total number of searches: ");
print (len(matches))
if searchby == "2":
obj = Searchengine()
matches = obj.search_by_call_number(searchthis)
i = 0
size = len(matches)
while i != size:
matches[i].display()
i = i + 1
print("--------TOTAL SEARCHES-------\n Total number of searches: ");
print (len(matches))
if searchby == "3":
obj = Searchengine()
matches = obj.search_by_subjects(searchthis)
i = 0
size = len(matches)
while i != size:
matches[i].display()
i = i + 1
print("--------TOTAL SEARCHES-------\n Total number of searches: ");
print (len(matches))
if searchby == "4":
obj = Searchengine()
matches = obj.search_by_other(searchthis)
i = 0
size = len(matches)
while i != size:
matches[i].display()
i = i + 1
print("--------TOTAL SEARCHES-------\n Total number of searches: ");
print (len(matches))
if searchby == "5":
quit()
print("Would you like to continue(y/n)????");
choice = input();
main()
|
057262fe0482596a06bb5db10026b729f1d54951
|
coder4378/test-your-GK
|
/gk-quiz.py
| 945 | 3.765625 | 4 |
print("Hello, welcome to the GK quiz!")
ready=input("are you ready to play(yes/no): ")
score=0
total_q = 4
if ready.lower() == "yes":
ans1 = input("is silver fish an insect (True/False)?")
if ans1.lower() == "False":
score+=1
print("correct")
else : print("incorrect it is an insect")
ans2 = input("which is largest land animal?")
if ans2.lower() == "elephant":
print("correct")
score+=1
else : print("it is elephant")
ans3 = input("in which year does covid 19 came in china?")
if ans3.lower() == "2019":
print("correct")
score+=1
else : print("incorrect it came un 2019")
ans4 = input("when did India win 1st world cup?")
if ans1.lower() == "1983":
print("correct")
score+=1
else : print("incorrect 1983")
print("Thank you for playing you got", score , "question correct")
mark=(score/total_q)*100
print("Marks", mark, "%")
print("Good By")
|
bbd68d8c47e0d5dcc67c8d6d33f16904a1d266fb
|
Omkarj21/DataAnalysis_Sales_Data
|
/QA_script05.py
| 3,367 | 3.515625 | 4 |
# import all the needed modules
import pandas as pd
import os
import matplotlib.pyplot as plt
#-------------------------------------------------------------------------------
""" Which products sold most and why """
#-------------------------------------------------------------------------------
### Start : Collect All Data at one place --------------------------------------
df_allmonthsdata = pd.DataFrame()
listfile = os.listdir('Sales_Data')
print("Name of Files available in folder : ", ", ".join(listfile))
print("Total count of files : ", len(listfile))
for csvf in listfile:
dfsalesdt = pd.read_csv('Sales_Data/' + csvf) # Read CSVs of the folder one by one
df_allmonthsdata = pd.concat([df_allmonthsdata, dfsalesdt]) # Concatenate the data of CSV's into dataframe
print("Length of new Dataframe which has 12 month's data : ", len(df_allmonthsdata))
df_allmonthsdata.to_csv("Output/alldata.csv", index=False)
# here index=False does not include index i.e. 0,1,2,3......
# here index=True includes index i.e. 0,1,2,3......
df_allmonthsdata = pd.read_csv("Output/alldata.csv") # Read CSV to start Fresh
### End : Collect All Data at one place ---------------------------------------
### Start : Clean up the Data -------------------------------------------------
#### Check NaN values present
nan_val = df_allmonthsdata[df_allmonthsdata.isna().any(axis=1)]
print("Check NaN values present : ",nan_val.head())
#### Drop rows of NAN
df_allmonthsdata = df_allmonthsdata.dropna(how="all")
invalid_data = df_allmonthsdata[df_allmonthsdata["Order Date"].str[0:2] == 'Or']
print("Invalid values present : ", invalid_data.head())
# Now Select Correct Data which does not have "Or" value in Date
df_allmonthsdata = df_allmonthsdata[df_allmonthsdata["Order Date"].str[0:2] != 'Or']
#### Convert Columns to appropriate data type
df_allmonthsdata["Quantity Ordered"] = pd.to_numeric(df_allmonthsdata["Quantity Ordered"]) # Make int
df_allmonthsdata["Price Each"] = pd.to_numeric(df_allmonthsdata["Price Each"]) # Make int
### End : Clean up the Data -------------------------------------------------
### Start : Calculate products sold most on the basis of Quantity Ordered and Its Price----------------------------
product_group = df_allmonthsdata.groupby("Product")
qty_ordered = product_group.sum()["Quantity Ordered"]
products = [product for product,df in product_group]
print(products)
prices = df_allmonthsdata.groupby("Product").mean()["Price Each"]
print(prices)
### End : Calculate products sold most on the basis of Quantity Ordered and Its Price----------------------------
### Start : Show Actual Answer on Plot : Find products sold most on the basis of Quantity Ordered and Its Price -------------
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.bar(products,qty_ordered,color="g")
ax2.plot(products,prices,"b-")
ax1.set_xlabel("Product Name")
ax1.set_ylabel("Quantity Ordered", color="g")
ax2.set_ylabel("Price ($)",color="b")
ax1.set_xticklabels(products,rotation="vertical",size=8)
plt.show()
### End : Show Actual Answer on Plot : Find products sold most on the basis of Quantity Ordered and Its Price ---------------
#-------------------------------------------------------------------------------
""" End of : Which products sold most and why """
#-------------------------------------------------------------------------------
|
90aa44365d05b0bf884fa4599dc26836f7639f97
|
jym197228/guessnumpractice
|
/r.py
| 520 | 3.640625 | 4 |
import random
start = input('請輸入隨機整數範圍開始值: ')
end = input('請輸入隨機整數範圍結束值: ')
start = int(start)
end = int(end)
r = random.randint(start, end)
count = 0
while True:
count += 1 # count = count + 1
num = input('請猜猜數字: ')
num = int(num)
if num == r:
print('您猜中了!')
print('您總共猜了', count, '次')
break
elif num > r:
print('答案比您輸入的還要小')
else:
print('答案比您輸入的還要大')
print('您猜了', count, '次')
|
067e23c1476b6791d3ae889edcca17719342b1b2
|
jnobre/python-classes
|
/sheet5/ex5-Folha5.py
| 395 | 3.78125 | 4 |
def printFuncao():
global c #global
b=5 #local
c=6
teste = 1
print("a dentro da funcao: ", a)
print("b dentro da funcao: ", b)
print("c dentro da funcao: ", c)
a=1
b=2
c=3
print("a fora da funcao: ", a)
print("b fora da funcao: ", b)
print("c fora da funcao: ", c)
printFuncao()
print2()
print("a fora da funcao: ", a)
print("b fora da funcao: ", b)
print("c fora da funcao: ", c)
|
73342b3b4f8d44e5a75b98b1d21ef21612a324b9
|
JavierCuesta12/Algoritmia
|
/Entegas/Entrega3/Ejercicio4.py
| 587 | 3.6875 | 4 |
Tapones=[1,3,4,2]
Botellas=[3,2,4,1]
def Entaponar(tapones, botellas, inicio):
if inicio < len(tapones) and inicio < len(botellas):
if(tapones[inicio] != botellas[inicio]):
for i in range(inicio + 1, len(botellas)):
if (tapones[inicio] == botellas[i]):
baux=botellas[inicio]
botellas[inicio] = botellas[i]
botellas[i]=baux
break
inicio=inicio+1
Entaponar(tapones, botellas,inicio)
return tapones, botellas
print(Entaponar(Tapones, Botellas, 0))
|
9d63be07ce5d2539d084b115983a2ea8b44b2a57
|
okapetanios/practice
|
/leetcode/twosum.py
| 400 | 3.75 | 4 |
def twosum(nums, target):
index_map = {}
for i in range(len(nums)):
num = nums[i]
print("NUM:", num)
twin = target - num
print("TWIN:"+ str(twin))
if twin in index_map:
print([i,index_map.get(twin)])
print(index_map)
return
index_map[num]=i
print("No sum found\n")
a = [5,3,6,8,7]
twosum(a, 9)
|
4a8d36809efe7a342f20429c263dd6b771df741c
|
wanghan79/2019_Python
|
/2017010886_WangYuTing/ConnectMongodb.py
| 947 | 4.125 | 4 |
'''
姓名:王宇婷
学号:2017010886
内容:连接mongodb并操作
'''
import pymongo
client = pymongo.MongoClient(host='localhost', port=27017)
db = client['RandomData']#指定数据库
collection = db['students']
student1 = {
'id': '20170101',
'name': 'Jordan',
'age': 20,
'gender': 'male'
}
student2 = {
'id': '20170202',
'name': 'Mike',
'age': 21,
'gender': 'male'
}
#插入数据
result = collection.insert_many([student1, student2])
print(result)
print(result.inserted_ids)
#数据更新
condition = {'name': 'Kevin'}
student = collection.find_one(condition)
student['age'] = 25
result = collection.update(condition, student)
print(result)
def save_to_mongo(ur):
#如果插入的数据成功,返回True,并打印存储内容:否则返回False
if db[student].insert(ur):
print("成功存储到MongoDB",ur)
return True
return False
|
100a9fedbaf05b5c2db1d7fc0a66c407df7d7b79
|
aashish2000/Data-Structures-in-Python
|
/Sorting/radix-sort.py
| 587 | 3.578125 | 4 |
def countingSort(arr,exp):
arr=arr[::-1]
digarr=[]
bucket=[0]*10
for i in range(len(arr)):
try:
dig=int(str(arr[i])[-exp])
except:
dig=0
#print("dig: ",dig)
digarr.append(dig)
bucket[dig]+=1
for i in range(1,10):
bucket[i]+=bucket[i-1]
#print(digarr,bucket)
sortedarr=[0]*len(arr)
for i in range(len(arr)):
sortedarr[bucket[digarr[i]]-1]=arr[i]
bucket[digarr[i]]-=1
return(sortedarr)
def radixSort(arr):
val=len(str(max(arr)))
for i in range(val):
arr=countingSort(arr,(i+1))
return(arr)
print(radixSort([1000,170,45,75,90,802,24,2,66]))
|
45cfa4ee053dd31fa68453e353a67ebca88cf506
|
shrikantchine/algorithm-practice
|
/iDeserve/is_btree_symmetric.py
| 922 | 4 | 4 |
class Node(object):
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def is_symmetric(root):
return symmetric_helper(root.left, root.right)
def symmetric_helper(n_left, n_right):
if n_left is None and n_right is None:
return True
if (n_left is not None and n_right is None) or (n_right is not None and n_left is None):
return False
return (n_left.data == n_right.data) and symmetric_helper(n_left.left, n_right.right) and symmetric_helper(n_left.right, n_right.left)
root = Node(3)
root.left = Node(1)
root.right = Node(1)
root.left.left = Node(0)
root.left.right = Node(2)
root.right.left = Node(2)
root.right.right = Node(0)
root.left.left.left = Node(3)
root.left.right.right = Node(4)
root.right.left.left = Node(4)
root.right.right = Node(0)
root.right.right.right = Node(3)
print(is_symmetric(root))
|
ddd0b713ea90a4230560d6534410d43e41f020bb
|
yiming1012/MyLeetCode
|
/LeetCode/贪心算法/1196. 最多可以买到的苹果数量.py
| 1,434 | 3.921875 | 4 |
"""
1196. 最多可以买到的苹果数量
楼下水果店正在促销,你打算买些苹果,arr[i] 表示第 i 个苹果的单位重量。
你有一个购物袋,最多可以装 5000 单位重量的东西,算一算,最多可以往购物袋里装入多少苹果。
示例 1:
输入:arr = [100,200,150,1000]
输出:4
解释:所有 4 个苹果都可以装进去,因为它们的重量之和为 1450。
示例 2:
输入:arr = [900,950,800,1000,700,800]
输出:5
解释:6 个苹果的总重量超过了 5000,所以我们只能从中任选 5 个。
提示:
1 <= arr.length <= 10^3
1 <= arr[i] <= 10^3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/how-many-apples-can-you-put-into-the-basket
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
from typing import List
class Solution:
def maxNumberOfApples(self, arr: List[int]) -> int:
"""
思路:贪心算法
1. 要求个数多,肯定先买重量轻的苹果
@param arr:
@return:
"""
t = 5000
arr.sort()
res = 0
for num in arr:
if t >= num:
res += 1
t -= num
else:
break
return res
if __name__ == '__main__':
arr = [100, 200, 150, 1000]
print(Solution().maxNumberOfApples(arr))
|
aa3338bb2bc16b1169c648bad0a67fee84bee64a
|
munzalaj/jacklyne
|
/prime_number.py
| 143 | 3.828125 | 4 |
def_prime_number(num):
for i in range(2,num)
prime = True
if ((num/i)*i)=num
return "Not Prime"
else:
print True
|
28e5bdaa5555ece59b7f41d29f04b3e1c867f0ad
|
RaazeshP96/Python_assignment2
|
/assignment14.py
| 521 | 4.125 | 4 |
'''
Write a function that reads a CSV file. It should return a list of dictionaries,
using the first row as key names, and each subsequent row as values for those keys.
For the data in the previous example it would return:
[{'name': 'George', 'address': '4312 Abbey Road', 'age': 22},
{'name': 'John', 'address': '54 Love Ave', 'age': 21}]
'''
import csv
with open('comma.csv', 'r') as files:
csv_reader = csv.DictReader(files)
result = []
for row in csv_reader:
result.append(row)
print(result)
|
1ac59cc2dfd0edfd10860df09961e8088d78b52a
|
aaronmontano/InvestBot
|
/PROJECT_2_RF/ML_alg.py
| 3,868 | 3.765625 | 4 |
# Import statements
import pandas as pd
import numpy as np
# Create a Pandas DataFrame containing closing prices for stock FNTK
fntk_df = pd.DataFrame(
{"close": [30.05, 30.36, 30.22, 30.52, 30.45, 31.85, 30.47, 30.60, 30.21, 31.30]}
)
# Review the DataFrame
fntk_df
# Set the index as datetime objects starting from 2019-09-09, but only for business days
fntk_df.index = pd.bdate_range(start='2019-09-09', periods=10)
# Review the DataFrame
fntk_df
# Initialize trade_type column to track buys and sells
fntk_df["trade_type"] = np.nan
# Initialize variable to hold previous day's trading price
# Set the initial value of the previous_price to 0
previous_price = 0
# Loop through the Pandas DataFrame and initiate a trade at each iteration
for index, row in fntk_df.iterrows():
# buy if the previous_price is 0, in other words, buy on the first day
if previous_price == 0:
fntk_df.loc[index, "trade_type"] = "buy"
# buy if the current day's price is less than the previous day's price
elif row["close"] < previous_price:
fntk_df.loc[index, "trade_type"] = "buy"
# sell if the current day's price is greater than the previous day's price
elif row["close"] > previous_price:
fntk_df.loc[index, "trade_type"] = "sell"
# hold if the current day's price is equal to the previous day's price
else:
fntk_df.loc[index, "trade_type"] = "hold"
# update the previous_price to the current row's price
previous_price = row["close"]
# if the index is the last index of the DataFrame, sell
if index == fntk_df.index[-1]:
fntk_df.loc[index, "trade_type"] = "sell"
# Review the DataFrame
fntk_df
# Initialize trade_type column to track buys and sells
fntk_df["trade_type"] = np.nan
# Initialize a cost/proceeds column for recording trade metrics
fntk_df["cost/proceeds"] = np.nan
# Initialize share size and accumulated shares
share_size = 100
accumulated_shares = 0
# Initialize variable to hold previous price
previous_price = 0
# Loop through the Pandas DataFrame and initiate a trade at each iteration
for index, row in fntk_df.iterrows():
# buy if the previous_price is 0, in other words, buy on the first day
if previous_price == 0:
fntk_df.loc[index, "trade_type"] = "buy"
# calculate the cost of the trade by multiplying the current day's price
# by the share_size, or number of shares purchased
fntk_df.loc[index, "cost/proceeds"] = -(row["close"] * share_size)
# add the number of shares purchased to the accumulated shares
accumulated_shares += share_size
# buy if the current day's price is less than the previous day's price
elif row["close"] < previous_price:
fntk_df.loc[index, "trade_type"] = "buy"
# calculate the cost of the trade by multiplying the current day's price
# by the share_size, or number of shares purchased
fntk_df.loc[index, "cost/proceeds"] = -(row["close"] * share_size)
# add the number of shares purchased to the accumulated shares
accumulated_shares += share_size
# hold if the current day's price is greater than the previous day's price
elif row["close"] > previous_price:
fntk_df.loc[index, "trade_type"] = "hold"
# hold if the current day's price is equal to the previous day's price
else:
fntk_df.loc[index, "trade_type"] = "hold"
# update the previous_price to the current row's price
previous_price = row["close"]
# if the index is the last index of the DataFrame, sell
if index == fntk_df.index[-1]:
fntk_df.loc[index, "trade_type"] = "sell"
# calculate the proceeds by multiplying the last day's price by the accumulated shares
fntk_df.loc[index, "cost/proceeds"] = row["close"] * accumulated_shares
# Review the DataFrame
fntk_df
|
377d7bf0d345a462858ce2d1f70d6841e4c24018
|
shaweii/programming-practices
|
/Python/Python triangle.py
| 261 | 4.03125 | 4 |
print("Python triangle.")
n = int(input("Please enter a number: "))
for i in range(1,n+1):
for j in range(1,i+1):
print("*",end=" ")
print()
"""i = 1
while i <= n:
print("*"*i)
i += 1
f = open("demofile.txt", "a")
"""
|
1ebd1ace4de9a7bb569ab28016758cd64142d949
|
geekcomputers/Python
|
/Hangman.py
| 2,216 | 4.21875 | 4 |
# importing the time module
import time
# importing the random module
import random
# welcoming the user
name = input("What is your name? ")
print("\nHello, " + name + "\nTime to play hangman!\n")
# wait for 1 second
time.sleep(1)
print("Start guessing...\nHint:It is a fruit")
time.sleep(0.5)
someWords = """apple banana mango strawberry
orange grape pineapple apricot lemon coconut watermelon
cherry papaya berry peach lychee muskmelon"""
someWords = someWords.split(" ")
# randomly choose a secret word from our "someWords" LIST.
word = random.choice(someWords)
# creates an variable with an empty value
guesses = ""
# determine the number of turns
turns = 5
# Create a while loop
# check if the turns are more than zero
while turns > 0:
# make a counter that starts with zero
failed = 0
# for every character in secret_word
for char in word:
# see if the character is in the players guess
if char in guesses:
# print then out the character
print(char, end=" ")
else:
# if not found, print a dash
print("_", end=" ")
# and increase the failed counter with one
failed += 1
# if failed is equal to zero
# print You Won
if failed == 0:
print("\nYou won")
# exit the script
break
print
# ask the user go guess a character
guess = input("\nGuess a character:")
# Validation of the guess
if not guess.isalpha():
print("Enter only a LETTER")
continue
elif len(guess) > 1:
print("Enter only a SINGLE letter")
continue
elif guess in guesses:
print("You have already guessed that letter")
continue
# set the players guess to guesses
guesses += guess
# if the guess is not found in the secret word
if guess not in word:
# turns counter decreases with 1 (now 9)
turns -= 1
# print wrong
print("\nWrong")
# how many turns are left
print("You have", +turns, "more guesses\n")
# if the turns are equal to zero
if turns == 0:
# print "You Loose"
print("\nYou Loose")
|
a223be6a31e87564568726ca4a37ea4dd0ccad59
|
vieirads/MCSC1
|
/extras/solutions/4_script.py
| 211 | 3.953125 | 4 |
#!/usr/bin/env python
import argparse
parser = argparse.ArgumentParser(description='Double a number.')
parser.add_argument("x", help="value to double",type=float)
args = parser.parse_args()
print(args.x**2)
|
6042a54aa9bbcde9dbee8b42dbbda62d670befc9
|
darkbodhi/homeworks_math
|
/pesron.py
| 945 | 3.890625 | 4 |
class Acquintance(object):
def __init__(self):
self.name = None
self.byear = None
self.pnumber = None
def input(self):
self.name = input("Введіть ім*я знайомого: ")
self.byear = input("Введіть рік народження знайомого: ")
self.pnumber = input("Введіть номер телефону знайомого: ")
def print(self):
print(self.name, self.byear, self.pnumber)
def read_database(self):
data_name = str(input("Please, insert the name of the file you want to import: "))
f = open("data_name", "r")
contents = f.read()
print(contents)
def create_database(self):
data_name2 = str(input("Please, insert the name of the file you want to create: "))
f = open("data_name2", "w+")
f.write("{} : {} : {}".format(self.name, self.byear, self.pnumber))
f.close()
|
4e8cf0bc97d4834f08b4c76f54bd8b55fa61eeba
|
kgudipati/DataScienceTools
|
/simpleLinearRegression.py
| 1,961 | 3.75 | 4 |
'''
Simple Linear Regression Classifier Module
y_i = alpha + beta*x_i + error_i
'''
import vectors as vec
import matrix as mat
import statistics as stat
import gradientDescent as gd
import random
# Predict final label
# y_i = beta*x_i + alpha + error
def predict(alpha, beta, x_i):
return beta * x_i + alpha
# Compute error from predicted y to actual y_i
def error(alpha, beta, x_i, y_i,):
return y_i - predict(alpha, beta, x_i)
# Use sum of square on errors to get total error over entire data
def sumOfSquaredErrors(alpha, beta, x, y):
return sum(error(alpha, beta, x_i, y_i) ** 2 for x_i, y_i in zip(x, y))
# Given training data x and y, find alpha, beta that makes sum of square error as small as possible
def leastSquaresFit(x, y):
beta = stat.correlation(x, y) * stat.standardDeviation(y) / stat.standardDeviation(x)
alpha = stat.mean(y) - beta + stat.mean(x)
return alpha, beta
# How well does model equation fit the data.
# Use coefficient of determination (r-squared)
def totalSumOfSquares(y):
return sum(v ** 2 for v in stat.de_mean(y))
def r_squared(alpha, beta, x, y):
return 1.0 - (sumOfSquaredErrors(alpha, beta, x, y) / totalSumOfSquares(y))
# Minimize the total error using gradient descent
# theta = [alpha, beta]
def squaredError(x_i, y_i, theta):
alpha, beta, = theta
return error(alpha, beta, x_i, y_i) ** 2
def squaredErrorGradients(x_i, y_i, theta):
alpha, beta = theta
return [-2 * error(alpha, beta, x_i, y_i), -2 * error(alpha, beta, x_i, y_i) * x_i]
# Use data too minimize the total error of function over dataset and return coefficients alpha and beta
def estimateCoefficients(x,y ):
random.seed(0)
theta = [random.random(), random.random()]
alpha, beta = gd.minimizeStochastic(squaredError,
x, y,
theta,
0.0001)
return alpha, beta
|
4feb387e21fcfe764d750e2bf170d98a1678a95c
|
pnaithani23/python
|
/id_2.py
| 437 | 3.765625 | 4 |
id=int(input("enter the product id "))
pd=str(input("enter the product "))
cp=float(input("enter the cost price of the product "))
sp=float(input("enter the selling price of the product "))
qt=int(input("enter the quantity of the product "))
print("product name :",pd,"\nproduct id :",id,"\ncost price of the product :",cp,"\nselling price of the product :",sp,"\nquantity of the product :",qt)
profit=(sp-cp)*qt
print("profit =",profit)
|
6e38b041c8ba9a33259be3f2f74b8910a9ebde44
|
DidiMilikina/DataCamp
|
/Machine Learning Scientist with Python/19. Image Processing with Keras in Python/04. Understanding and Improving Deep Convolutional Networks/06. Visualizing kernel responses.py
| 1,344 | 4.5625 | 5 |
'''
Visualizing kernel responses
One of the ways to interpret the weights of a neural network is to see how the kernels stored in these weights "see" the world. That is, what properties of an image are emphasized by this kernel. In this exercise, we will do that by convolving an image with the kernel and visualizing the result. Given images in the test_data variable, a function called extract_kernel() that extracts a kernel from the provided network, and the function called convolution() that we defined in the first chapter, extract the kernel, load the data from a file and visualize it with matplotlib.
A deep CNN model, a function convolution(), along with the kernel you extracted in an earlier exercise is available in your workspace.
Ready to take your deep learning to the next level? Check out Advanced Deep Learning with Keras in Python to see how the Keras functional API lets you build domain knowledge to solve new types of problems.
Instructions
100 XP
Use the convolution() function to convolve the extracted kernel with the first channel of the fourth item in the image array.
Visualize the resulting convolution with imshow().
'''
SOLUTION
import matplotlib.pyplot as plt
# Convolve with the fourth image in test_data
out = convolution(test_data[3, :, :, 0], kernel)
# Visualize the result
plt.imshow(out)
plt.show()
|
5def7260c3e53ce3ebd6d9f1ab75835f19ec38de
|
jochemste/GB_usage_calculator
|
/src/DateTime.py
| 1,908 | 3.828125 | 4 |
# -*- coding: utf-8 -*-
import datetime
from calendar import monthrange
class DateTime():
printAll: bool
def __init__(self, printAll: bool = False):
self.printAll = printAll
def __del__(self):
pass
def getDate(self):
currentDate = datetime.datetime.now().strftime("%Y-%m-%d")
if self.printAll == True:
print("Current date: " + currentDate)
return currentDate
def getDate_dayOnly(self):
currentDate = datetime.datetime.now().strftime("%d")
if self.printAll == True:
print("Current date: " + currentDate)
return currentDate
def getDate_monthOnly(self):
currentDate = datetime.datetime.now().strftime("%m")
if self.printAll == True:
print("Current date: " + currentDate)
return currentDate
def getDate_yearOnly(self):
currentDate = datetime.datetime.now().strftime("%Y")
if self.printAll == True:
print("Current date: " + currentDate)
return currentDate
def getTime(self):
currentTime = datetime.datetime.now().strftime("%H:%M:%S")
if self.printAll == True:
print("Current time: " + currentTime)
return currentTime
def getMonthRange(self):
month = int(self.getDate_monthOnly())
year = int(self.getDate_yearOnly())
range = monthrange(year, month)
return range[1]
## @brief Returns true if a date is in the future, and false if it is not
def date_in_future(self, date):
currentDate= datetime.datetime.now()
if date == currentDate.date() or date > currentDate.date():
return True
else:
return False
## @brief Returns true if date1 is bigger and false if date2 is bigger or equal
def compare_dates(self, date1, date2):
return date1 < date2
|
ad221b19245d677b4aaaf31cd9ecae1592e1b55d
|
avaz7791/UCSD
|
/Python/Day 2/Hello USer.py
| 429 | 4.09375 | 4 |
# Print Hello User!
print("Hello User!")
# Take in user input
User1 = input("What is your name?")
# Respond Back with User input
print("Hello "+ User1 + "!" )
# Take in the User Age
age1 = input("What is your Age?")
# Respond Back wiht a Statement
if int(age1) < 20:
print("Awww you are just a baby!")
else:
print("Ah... a well traveled soul are we ye.")
#-----------------------------------------------------
|
cdc5b2082c617f30f4f63f4bb8dc36e7278e3266
|
FelipeABortolini/Exercicios_Python
|
/Exercícios/009.py
| 473 | 3.953125 | 4 |
a=int(input('Digite um número inteiro qualquer para obter sua tabuada: '))
print('{} x 0 = {}'.format(a, a*0))
print('{} x 1 = {}'.format(a, a*1))
print('{} x 2 = {}'.format(a, a*2))
print('{} x 3 = {}'.format(a, a*3))
print('{} x 4 = {}'.format(a, a*4))
print('{} x 5 = {}'.format(a, a*5))
print('{} x 6 = {}'.format(a, a*6))
print('{} x 7 = {}'.format(a, a*7))
print('{} x 8 = {}'.format(a, a*8))
print('{} x 9 = {}'.format(a, a*9))
print('{} x 10 = {}'.format(a, a*10))
|
d7926a8d3a9515f3e6f088bcb15cae95647b8b24
|
noliverh/CLMITS_ACITIVITIES
|
/jack_n_poy.py
| 1,597 | 4.09375 | 4 |
import random
weapons = [1, 2, 3]
comp_action = random.randint(0, 2)
player = False
while not player:
player_action = int(input("\nEnter your weapon ([1]rock, [2]paper, [3]scissors): "))
if player_action == weapons[0]:
player_action = "rock"
elif player_action == weapons[1]:
player_action = "paper"
elif player_action == weapons[2]:
player_action = "scissors"
else:
print("No match! Choose correct weapon.")
if comp_action == 0:
comp_action = "rock"
elif comp_action == 1:
comp_action = "paper"
elif comp_action == 2:
comp_action = "scissors"
print(f"\nYou chose {player_action}, computer chose {comp_action}.\n")
if player_action == comp_action:
print(f"Both players selected {player_action}. It's a tie!")
elif player_action == "rock":
if comp_action == "scissors":
print("Rock smashes scissors! You win!")
else:
print("Paper covers rock! You lose.")
elif player_action == "paper":
if comp_action == "rock":
print("Paper covers rock! You win!")
else:
print("Scissors cuts paper! You lose.")
elif player_action == "scissors":
if comp_action == "paper":
print("Scissors cuts paper! You win!")
else:
print("Rock smashes scissors! You lose.")
new_game = input("\nDo you want another game? (y/n): ")
if new_game == "y":
player = False
else:
print("Thank you!")
break
|
310c1a3c72d478fa66d3aa0b260767bb0c5d980d
|
Jnayakk/Querying-Data
|
/Querying Data/starter/squeal.py
| 5,654 | 4.21875 | 4 |
from reading import *
from database import *
# The delimiter which is a comma for sql purposes.
COMMA_DELIMETER = ','
# The operator representing equal
EQUALS_OPERATOR = '='
# The operator representing greater than.
GREATER_OPERATOR = '>'
# The delimeter which is a space
SPACE_DELIMETER = ' '
# The token where one can declare which tables to acquire.
FROM_TOKEN = "from"
# The token where one can declare which columns to acquire
SELECT_TOKEN = "select"
# The input prompt
INPUT_PROMT = "Enter a SQuEaL query, or a blank line to exit:"
ALL_TOKEN = '*'
# Below, write:
# *The cartesian_product function
# *All other functions and helper functions
# *Main code that obtains queries from the keyboard,
# processes them, and uses the below function to output csv results
def print_csv(table):
'''(Table) -> NoneType
Print a representation of table.
'''
dict_rep = table.get_dict()
columns = list(dict_rep.keys())
print(','.join(columns))
rows = table.count_rows()
for i in range(rows):
cur_column = []
for column in columns:
cur_column.append(dict_rep[column][i])
print(','.join(cur_column))
def cartesian_product(first_table, second_table):
'''(Table, Table) -> Table
Computes the cartesian product of the first and second table and
returns it. That is where each row in the first table is paired
with every row in the second table.
'''
# look in database.py file for how this was calculated.
return first_table.cartesian_product(second_table)
def format_query(query):
'''(str) -> dict
Whatever query is entered as a string, this function takes it and
returns it as a dictionary where select and from are keys and
their values are columns and tables.
REQ: query is in proper sql syntax
>>> format_query('select books.title from books')
{'from': ['books'], 'select': ['books.title']}
>>> format_query("select o.category, m.title from movies,oscar")
{'from': ['movies', 'oscar'], 'select': ['o.category', 'm.title']}
'''
formatted_query = {}
# split query by using a white space as the delimeter
query = query.split(SPACE_DELIMETER)
# get the select and from values, since the sql syntax will always be
# in correct form, the values for select will be the string after
# the 0th index and the values for from will be the string after
# the 3rd index
select_values = query[1].split(COMMA_DELIMETER)
from_values = query[3].split(COMMA_DELIMETER)
# map the string "select" to the values after select in the query
formatted_query[SELECT_TOKEN] = select_values
# map the string "from" to the values after select in the query
formatted_query[FROM_TOKEN] = from_values
return formatted_query
def run_query(db, query):
'''(Database, str) -> Table
Given a Database object and a query in the form of a string. This
function runs the query on the database and returns a table
representing the resulting table.
r = ({'b.title': ['The Maze Runner', 'Dusk'], 'b.category':
['Mystery', 'Thriller'], 'b.movies': ['yes', 'no']})
d = Database()
d.save_to_database(r)
res = run_query(db, "select b.title,b.movies from ratings").get_dict()
res == ({'b.title': ['The Maze Runner', 'Dusk'], 'b.movies':
['yes', 'no']})
True
'''
# format the query to know for sure what token wants what.
formatted_query = format_query(query)
# get the cartesian table of all the tables listed in query after from
# look in database.py to see how that happens.
table = db.get_cartesian_table(query)
# whichever columns were selected in the query thats what is going
# to be in the final table.
final_table = sql_syntax_select(table, formatted_query)
return final_table
def sql_syntax_select(table, formatted_query):
'''(Table, dict) -> Table
From the formatted query, find select and its values and only return
them in a new table
>>> t = Table()
>>> t.set_dict({'b.title': ['The Maze Runner', 'Dusk'], 'b.category':
['Mystery', 'Thriller'], 'b.movies': ['yes', 'no']})
res = sql_syntax_select(t, {'from': [t],
'select': ['b.title']}
res.get_dict() == {'b.title': ['The Maze Runner', 'Dusk']}
True
'''
# find the select key and declare its values as list of columns
list_of_columns = formatted_query[SELECT_TOKEN]
# get the table represented as a dictionary from the table object
my_table = table.share_table()
selected = {}
# create a table
select_table = Table()
# get all of the columns if the value in select key is '*'
if list_of_columns == [ALL_TOKEN]:
list_of_columns = [(my_table.keys())]
# if the query is not selecting all of the values, then go through
# each column and get its values to store in the new dictionary.
else:
for column in list_of_columns:
selected[column] = my_table[column]
# save the dictionary to the table and then return it.
select_table.save_to_table(selected)
return select_table
if(__name__ == "__main__"):
# ask the input prompt and read the database
query = input(INPUT_PROMT)
database = read_database()
# while a blank line is not entered, keep showing the input prompt
while (query != ""):
print_csv(run_query(database, query))
query = input(INPUT_PROMT)
|
3a3ac81a5e353b759795d5912ded44c18445e289
|
yl123168/Hello_world
|
/06LectureP9.py
| 691 | 3.75 | 4 |
animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}
animals['d'] = ['donkey']
animals['d'].append('dog')
animals['d'].append('dingo')
def howMany(aDict):
result = 0
if aDict == {}:
return result
for i in aDict.values():
result += len(i)
return result
def biggest(aDict):
if aDict == {}:
return None
key_list = aDict.keys()
key = key_list[0]
for i in key_list:
if len(aDict[i]) > len(aDict[key]):
key = i
return key
test = {}
test2 = {'a':[]}
#print(howMany(animals))
#print(howMany(test))
print(biggest(animals))
print(biggest(test))
print(biggest(test2))
|
bff71e559bf0619c0629bd7b7d8f857066012039
|
wheejoo/PythonCodeStudy
|
/2주차 BFS,DFS/프로그래머스/타겟넘버/김휘주.py
| 470 | 3.71875 | 4 |
from collections import deque
def solution(numbers, target):
answer = 0
q = deque([(0,0)])
while q:
n_sum, n_idx = q.popleft()
if n_idx == len(numbers):
if n_sum == target:
answer += 1
else:
number = numbers[n_idx]
q.append((n_sum+number, n_idx+1))
q.append((n_sum-number, n_idx+1))
return answer
numbers = [1, 1, 1, 1, 1]
target = 3
print(solution(numbers,target))
|
9878574d2c1056680df73c2a81b0f96d4346cc2b
|
zopepy/leetcode
|
/longest_even_word.py
| 185 | 3.875 | 4 |
def longest(s):
s = s.split()
w = [len(w) for w in s]
we = max([l if l&1==0 else 0 for l in w])
for w in s:
if len(w) == we:
return w
print(longest("hello world this is new"))
|
0986719af98e8d2e88323dfad6df596a390b10d8
|
fengxiaolong886/leetcode
|
/234. 回文链表.py
| 534 | 3.796875 | 4 |
"""
请判断一个链表是否为回文链表。
示例 1:
输入: 1->2
输出: false
示例 2:
输入: 1->2->2->1
输出: true
"""
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
current = head
res = []
while current is not None:
res.append(current.val)
current = current.next
return res == res[::-1]
|
0e8f893cabeae58331612126de9dd7b3da294c05
|
NintendoLink/leetcode_py
|
/_list/getKthFromEndSolution.py
| 1,611 | 3.765625 | 4 |
class ListNode:
def __init__(self,x):
self.val = x
self.next = None
"""
剑指 Offer 22. 链表中倒数第k个节点
输入一个链表,输出该链表中倒数第k个节点。为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3、4、5、6。这个链表的倒数第3个节点是值为4的节点。
示例:
给定一个链表: 1->2->3->4->5, 和 k = 2.
返回链表 4->5.
"""
class Solution:
"""
思路
1、快慢指针
2、普通算法
"""
def getKthFromEnd(self,head:ListNode,k:int):
"""
快慢指针
"""
fast = head # 快指针
slow = head # 慢指针
for i in range(0,k):
if not fast:
return 0
fast = fast.next
while(fast):
fast = fast.next
slow = slow.next
return slow
def getKthFromEnd2(self, head:ListNode, k:int):
head_cp = head
ls_count = 0
while(head_cp):
ls_count += 1
head_cp = head_cp.next
iter_count = ls_count - k
result = head
for i in range(0,iter_count):
result = result.next
return result
if __name__ == '__main__':
solution = Solution()
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node1.next = node2
node2.next = node3
node3.next = node4
print(solution.getKthFromEnd(node1,2).val)
|
436ce1c65da388add7e566eb053657d93132b2ef
|
marcdloz/cosc4377-Computer-Networks
|
/practice4_1.py
| 1,164 | 4.09375 | 4 |
import math
current_score = 1000
max_score = 500
number, answer = 9, 0
if current_score > max_score:
print("A new high score!")
max_score = current_score
if number >= 0:
answer = math.sqrt(number)
print(answer)
else:
answer = -1
print(answer)
print(2 + 2 == 4)
print(4 < 3)
print(2 < 2.5)
print(int("40") > 35) # Convert string to integer and compare
print("42" == 42) # Compare == between string and integer
"""print("42" > 40) # Compare > between string and integer, results in TypeError"""
if number > 0:
print("Number is positive")
if number == 0:
print("Number is zero.")
if number < 0:
print("Number is negative")
if number > 0:
print("Number is positive")
elif number == 0:
print("Number is zero.")
else:
print("Number is negative")
money = 2000
print("You have $", money, "left")
if money < 500:
print("Cash is dangerously low. Bet carefully")
elif money < 1000:
print("Cash is somewhat low. Bet moderately")
else:
print("Cash is in good shape. Bet liberally")
bet = int(input("How much do you want to bet? "))
age1 = 20
age2 = 16
if age1 >= 18 > age2:
print("OK!")
|
e9ba83a71d911d4a569e3d525ef49d392974c2f7
|
rhnvrm/mini-projects
|
/test_driven_dev/tests/test_parking_lot.py
| 3,091 | 3.65625 | 4 |
import unittest
from app.parking import Parking
from app.car import Car
class TestParkingLotCreation(unittest.TestCase):
def test_create_new_parking_lot(self):
park_lot = Parking(6)
result = park_lot.size
self.assertEqual(6, result)
def test_parking_raises_error_if_arg_is_not_a_number(self):
self.assertRaises(ValueError, Parking, "123")
self.assertRaises(ValueError, Parking, 1.5)
class TestParkingLotMethods(unittest.TestCase):
def setUp(self):
self.lot = Parking(5)
def test_add_new_cars_to_lot(self):
self.assertEqual(1, self.lot.newCar("KA-01-HH-1234", "White"))
self.assertEqual(2, self.lot.newCar("KA-02-HH-1234", "White"))
self.assertEqual(3, self.lot.newCar("KA-03-HH-1234", "White"))
self.assertEqual(self.lot.currentCarCount(), 3)
def test_add_and_remove_multiple_new_cars_to_lot(self):
self.assertEqual(1, self.lot.newCar("KA-01-HH-1234", "White"))
self.assertEqual(2, self.lot.newCar("KA-02-HH-1234", "White"))
self.lot.leave(1)
self.assertEqual(1, self.lot.newCar("KA-03-HH-1234", "White"))
def test_new_cars_returns_lot_full_when_lot_full(self):
self.assertEqual(1, self.lot.newCar("KA-01-HH-1234", "White"))
self.assertEqual(2, self.lot.newCar("KA-02-HH-1234", "White"))
self.assertEqual(3, self.lot.newCar("KA-03-HH-1234", "White"))
self.assertEqual(4, self.lot.newCar("KA-04-HH-1234", "White"))
self.assertEqual(5, self.lot.newCar("KA-05-HH-1234", "White"))
print(self.lot.lot)
self.assertEqual(-1, self.lot.newCar("KA-06-HH-1234", "White"))
def test_leave_returns_error_if_slot_is_empty(self):
self.assertEqual(self.lot.leave(3), -1)
def test_find_cars_by_color(self):
self.lot.newCar("KA-01-HH-1234", "white")
self.lot.newCar("KA-02-HH-1234", "White")
self.lot.newCar("KA-03-HH-1234", "Black")
self.lot.newCar("KA-04-HH-1234", "black")
self.lot.newCar("KA-05-HH-1234", "BLACK")
white_cars = self.lot.find_cars_by_color("WHITE")
black_cars = self.lot.find_cars_by_color("bLaCk")
self.assertEqual(len(white_cars), 2)
self.assertEqual(len(black_cars), 3)
#find_cars_by_color returns a list of tuples having (slot, Car)
self.assertEqual(white_cars[1][0], 2)
self.assertEqual(black_cars[1][0], 4)
self.assertIsInstance(white_cars[0][1], Car)
def test_find_cars_by_color_raises_error_if_arg_not_str(self):
self.assertRaises(ValueError, self.lot.find_cars_by_color, 123)
def test_find_car_by_reg_no(self):
self.lot.newCar("KA-01-HH-1234", "white")
self.lot.newCar("KA-02-HH-1234", "red")
self.lot.newCar("KA-03-HH-1234", "green")
#find_car_by_reg_no returns slot
self.assertEqual(self.lot.find_car_by_reg_no("KA-02-HH-1234"), 2)
def test_find_car_by_reg_no_returns_none_if_not_found(self):
self.assertEqual(self.lot.find_car_by_reg_no("KA-02-HH-1234"), None)
|
ec0623933ecbda22d27afd07a18e79ca51469a8b
|
avellar1975/python
|
/cursoemvideo/exercicio030.py
| 202 | 4.1875 | 4 |
n = int(input('Digite um número inteiro: '))
r = n % 2
if (r == 0):
print('O número digitado foi {}, ele é PAR'.format(n))
else:
print('O número digitado foi {}, ele é IMPAR'.format(n))
|
68302cf67e0ec80525548ee2b6f6c771ea053e6f
|
sigerclx/python
|
/python-book01/2018/2018-05/P071-string.py
| 278 | 3.828125 | 4 |
name = 'Jackyzhao'
print (name[0])
print (name[-2])
print (name[0:4])
print (name[:])
print ('Jac' in name)
print ('ack' in name)
print ('Ack' in name)
for i in name :
print ('---'+i+'----')
name = 'Jacky zhao'
newName = name[0:5]+' and ' + name[6:]
print (newName)
|
8975358b0f3596e406acc5cda3053c4d08c866cb
|
wagolemusa/Class
|
/employ.py
| 454 | 3.78125 | 4 |
class Employee:
def __init__(self, first,last,pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@company.com'
# method to dispaly fullname
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp_1 = Employee('Corey', 'Schofar', 500000)
emp_2 = Employee('Test', 'User', 600000)
print(emp_1.email)
print(emp_2.email)
print(emp_1.fullname())
print (emp_2.fullname())
|
48da3ea0fb9da1a7d2a894d5761f0b96a7306ed0
|
HaTrang97/How-to-think-like-a-computer-scientist
|
/littleTurtleClock.py
| 656 | 4.21875 | 4 |
% let the turtle move a shape like a clock
import turtle
screen = turtle.Screen() % view screen
screen.bgcolor('lightgreen') % set back ground color
screen.title('Hello, Trang!') % set the title
alex = turtle.Turtle() % give him a name!
alex.shape('turtle') % let alex be a turtle
alex.color('blue') % set the color for the turtle
alex.pensize(3)
alex.speed(5) % speed can be from 0 to 10
for i in range(12):
alex.penup()
alex.forward(90)
alex.pendown()
alex.forward(10)
alex.penup()
alex.forward(20)
alex.stamp()
alex.backward(120)
alex.right(30)
alex.stamp()
screen.mainloop() % wait for user to close window
|
1d5e0a0a6b67ea7e5263abe748361de0bb92c033
|
SergueiBaskakov/ML
|
/Semana01/Arreglos_Matrices_DotProduct.py
| 854 | 3.8125 | 4 |
# -*- coding: utf-8 -*-
"""
Editor de Spyder
Este es un archivo temporal.
"""
import numpy as np
def main():
a = (np.random.rand(1,4)*10+1)
b = (np.random.rand(1,4)*10+1)
"""print(a)
print("tamaño: ", a.size)"""
"""c= (np.random.rand(2,4))
print(c)
print("tamaño: ", c.size)
print("dimensión: ", c.shape)
print("rows: ", c.shape[0])
print("colums: ", c.shape[1])
print(c[1,1])"""
print(a)
print(b)
s = 0
print("shape: ", a.shape)
for i in range(0, a.shape[1]):
s = s + a[:,i]*b[:,i]
print(s)
print(np.dot(a,b.T))
def func():
a = (np.random.randint(1,20,(3,5)))
print(a, "\n")
#print(a[0,1])
#print(a[2])
#print(a[1,:])
#print(a[:,:])
#print(a[:,2])
print (a[:,:-1])
if __name__=="__main__":
func()
|
4011f06b397b24b5acfbb92269e1226b7a7b7328
|
jobevers/vsh
|
/vsh/cli/support.py
| 1,516 | 3.640625 | 4 |
import sys
import textwrap
def echo(*messages, verbose=None, indent=True, end=None, flush=None, file=None):
"""Echo *message*.
indentation can be finely controlled, but by default, indentation
is related to the verbose setting set by the command-line interface
and the verbose setting passed in as a parameter. The difference
of the two identifies how much indentation is created.
Args:
messages (Tuple[Any]): messages to echo
verbose (bool|int, optional): verbosity level
indent (int): number of spaces to indent
end (str): text to print at end of message, defaults to newline
flush (bool): flush output after write
file (typing.IO): file to echo message to
Returns:
Tuple[str]: beautified messages
"""
verbose = True if verbose is None else max(int(verbose or 0), 0)
indent = 0 if indent in [None, False, True] else max(int(indent or 0), 0)
file = file or sys.stdout
messages = list(messages)
if verbose:
for index, message in enumerate(messages):
message_end = end if index == len(messages) - 1 else ' '
message = '' if message is None else message
end = '\n' if end is None else end
if end == '\n' and indent:
message = textwrap.indent(message, ' ' * indent)
message = message.rstrip('\n') if end == '\n' else message
print(message, flush=flush, end=message_end, file=file)
return tuple(messages)
|
f07f7e851fe9d5554686094ba2eaf09d05861ad5
|
Keerthanavikraman/Luminarpythonworks
|
/regular_expression/quantifier_valid5.py
| 263 | 3.71875 | 4 |
#starting with a upper case letter
#numbers,lowercase,symbols
#Abv5< G6 R. Tt Dhgfhjkhg6t667":';;
import re
n= input("enter ")
x="(^[A-Z]{1}[a-z0-9\W]+)"
match = re.fullmatch(x,n)
if match is not None:
print("valid")
else:
print("invalid")
|
cab14a0af916d12beaa2638b0b151e5ef80eba37
|
sumanth-vs/ProjectEuler
|
/test.py
| 8,217 | 4.21875 | 4 |
MERGE SORT
'''
def mergeSort(arr):
if len(arr) >1:
mid = len(arr)//2 #Finding the mid of the array
L = arr[:mid] # Dividing the array elements
R = arr[mid:] # into 2 halves
mergeSort(L) # Sorting the first half
mergeSort(R) # Sorting the second half
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i+=1
else:
arr[k] = R[j]
j+=1
k+=1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i+=1
k+=1
while j < len(R):
arr[k] = R[j]
j+=1
k+=1
# Code to print the list
def printList(arr):
for i in range(len(arr)):
print(arr[i],end=" ")
print()
# driver code to test the above code
if __name__ == '__main__':
arr = [12, 11, 13, 5, 6, 7]
print ("Given array is", end="\n")
printList(arr)
mergeSort(arr)
print("Sorted array is: ", end="\n")
printList(arr)
'''
TOH
'''def hanoi(a, c, b, n):
if n == 1:
print("move from {} to {}".format(a, c))
else:
hanoi(a, b, c, n-1)
hanoi(a, c, b, 1)
hanoi(b, c, a, n-1)
return
#hanoi('a', 'c', 'b', 3)
print("########################$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$###################################################")
def gcd(m, n1):
if(m==n1):
print(m)
return
if m>n1:
gcd(m-n1, n1)
else:
gcd(m, n1-m)
gcd(69,420)
print("########################$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$###################################################")
def partB():
flag1 = 0
a =[]
key = 2
n2 = int(raw_input("Enter length of array"))
for i in range(n):
a.append(int(raw_input()))
l1 = 0, h1 = n2-1, m1=0, m2
while l1<=h1:
m1= l1+h1 // 2
ifa[m1] == key:
m2=m1
break
elif a[m1] > key:
h1 = m1-1
else:
l1 = m1+1
while a[m1] == key or a[m2] == key:
if m1 == key:
m1 -=m1
if m2 == key:
m2 -=m2
print(m1, m2, m2-m1)
'''
TOPO SORT
'''
from collections import defaultdict
#Class to represent a graph
class Graph:
def __init__(self,vertices):
self.graph = defaultdict(list) #dictionary containing adjacency List
self.V = vertices #No. of vertices
# function to add an edge to graph
def addEdge(self,u,v):
self.graph[u].append(v)
# A recursive function used by topologicalSort
def topologicalSortUtil(self,v,visited,stack):
# Mark the current node as visited.
visited[v] = True
# Recur for all the vertices adjacent to this vertex
for i in self.graph[v]:
if visited[i] == False:
self.topologicalSortUtil(i,visited,stack)
# Push current vertex to stack which stores result
stack.insert(0,v)
# The function to do Topological Sort. It uses recursive
# topologicalSortUtil()
def topologicalSort(self):
# Mark all the vertices as not visited
visited = [False]*self.V
stack =[]
# Call the recursive helper function to store Topological
# Sort starting from all vertices one by one
for i in range(self.V):
if visited[i] == False:
self.topologicalSortUtil(i,visited,stack)
# Print contents of the stack
print stack
g= Graph(6)
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
print "Following is a Topological Sort of the given graph"
g.topologicalSort()
'''
DFS
'''
class Graph:
# Constructor
def __init__(self):
# default dictionary to store graph
self.graph = defaultdict(list)
# function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# A function used by DFS
def DFSUtil(self, v, visited):
# Mark the current node as visited
# and print it
visited[v] = True
print(v, end = ' ')
# Recur for all the vertices
# adjacent to this vertex
for i in self.graph[v]:
if visited[i] == False:
self.DFSUtil(i, visited)
# The function to do DFS traversal. It uses
# recursive DFSUtil()
def DFS(self, v):
# Mark all the vertices as not visited
visited = [False] * (len(self.graph))
# Call the recursive helper function
# to print DFS traversal
self.DFSUtil(v, visited)
# Driver code
# Create a graph given
# in the above diagram
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print("Following is DFS from (starting from vertex 2)")
g.DFS(2)
'''
BFS
'''
from collections import defaultdict
# This class represents a directed graph
# using adjacency list representation
class Graph:
# Constructor
def __init__(self):
# default dictionary to store graph
self.graph = defaultdict(list)
# function to add an edge to graph
def addEdge(self,u,v):
self.graph[u].append(v)
# Function to print a BFS of graph
def BFS(self, s):
# Mark all the vertices as not visited
visited = [False] * (len(self.graph))
# Create a queue for BFS
queue = []
# Mark the source node as
# visited and enqueue it
queue.append(s)
visited[s] = True
while queue:
# Dequeue a vertex from
# queue and print it
s = queue.pop(0)
print (s, end = " ")
# Get all adjacent vertices of the
# dequeued vertex s. If a adjacent
# has not been visited, then mark it
# visited and enqueue it
for i in self.graph[s]:
if visited[i] == False:
queue.append(i)
visited[i] = True
# Driver code
# Create a graph given in
# the above diagram
g = Graph()
g.addEdge(0, 1)
g.addEdge(0, 2)
g.addEdge(1, 2)
g.addEdge(2, 0)
g.addEdge(2, 3)
g.addEdge(3, 3)
print ("Following is Breadth First Traversal"
" (starting from vertex 2)")
g.BFS(2)
'''
JOHNSON TROTTER
'''
import math
class Node:
def __init__(self, val):
self.val = val + 1
self.dir = 'left'
#self.pos = val
def print_val(self):
print(str(self.val) + " Pointing to " + str(self.dir))
def find_larg_mobile(arr):
max_ind = None
for i in range(0, len(arr)):
if arr[i].dir == 'left' and i == 0:
continue
if arr[i].dir == 'right' and i == len(arr) - 1:
continue
if arr[i].dir == 'left' and arr[i].val > arr[i-1].val:
if max_ind == None:
max_ind = i
elif arr[max_ind].val < arr[i].val:
max_ind = i
if arr[i].dir == 'right' and arr[i].val > arr[i+1].val:
if max_ind == None:
max_ind = i
elif arr[max_ind].val < arr[i].val:
max_ind = i
return max_ind
def swap(arr, i, j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
return arr
def JT(n):
#array = [Node(4, 'left'), Node(3, 'left'), Node(1, 'left'), Node(2, 'left')]
array = []
for i in range(0, n):
array.append(Node(i))
array[i].print_val()
print("\n")
#printing all perms
for i in range(math.factorial(n) - 1):
print(i+2)
inx = find_larg_mobile(array)
print(array[inx].val)
#change big value dir
if array[inx].val < n:
for i in range(0, n):
if array[i].val > array[inx].val:
if array[i].dir == 'left':
array[i].dir = 'right'
else:
array[i].dir = 'left'
HERE
if array[inx].dir == 'left':
array = swap(array, inx, inx-1)
elif array[inx].dir == 'right':
array = swap(array, inx, inx+1)
#printing values each time
for i in range(0, n):
array[i].print_val()
print("\n")
JT(6)
'''
|
5d256c8f0d1f37c26da0fc1135a194a479f6f630
|
mickiyas123/Python-100-Exercise-Challenge
|
/49_pass.py
| 309 | 3.875 | 4 |
# Question: The code is supposed to get some input from the user, but instead it produces an error. Please try to understand the error and then fix it.
# pass = input("Please enter your password: ")
# pass can't be a variable name since it is reserved keyword
pass1 = input("Please enter your password: ")
|
866c45de82fd2b95e71053659b2a78b33bead90f
|
Python3pkg/IoTPy
|
/IoTPy/modules/ML/plot.py
| 1,617 | 4.15625 | 4 |
import numpy as np
def plot(lst, state, plot_func, num_features):
""" This function plots data using the plot_func
Parameters
----------
lst : list
Data to plot
state : object
State used for predict and plot
plot_func : function
A function that processes the data for usage such as visualization.
This function takes parameters x and y data, a model object, a state
object, and returns an updated state object.
This function has the signature
(np.ndarray np.ndarray Object Object tuple) -> (Object).
The first numpy array x has dimensions i x `num_features`, where
`min_window_size` <= i <= `max_window_size`. The second numpy array y
has dimensions i x num_outputs, where num_outputs refers to the number
of y outputs for an input. The third parameter is the model object
defined by `train_func`. The fourth parameter is a state object defined
by this function.
num_features : int
An int that describes the number of features in the data.
"""
index, value = lst
# Initialize state
if state == 0:
state = [None, None]
# Update model
if index == 1:
state[0] = value
else:
# Plot if model is valid
if state[0] is not None:
data = np.array(value)
x = data[:, 0:num_features]
y = data[:, num_features:]
model = state[0]
state_plot = state[1]
state_plot = plot_func(x, y, model, state_plot)
state[1] = state_plot
return state
|
aae3e1887d164cc2d8b92572484635f4caa7cfda
|
AlanStorm/Python
|
/practice/函数式编程-按照权重排序.py
| 970 | 3.609375 | 4 |
# 权重
goods = [{"name": "good1", "price": 200, "sales": 100, "stars": 5, "comments": 400},
{"name": "good2", "price": 300, "sales": 120, "stars": 4, "comments": 500},
{"name": "good3", "price": 500, "sales": 3000, "stars": 2, "comments": 199},
{"name": "good4", "price": 1288, "sales": 8, "stars": 5, "comments": 398},
{"name": "good5", "price": 899, "sales": 99, "stars": 5, "comments": 2000}]
# 权重
# 价格占的权重是40%,销量占的权重是17%,评级占的权重是13%,评论占的权重是30%
# sorted() 进行排序
def my_sorted(arg):
price = arg['price']
sales = arg['sales']
star = arg['stars']
comment = arg['comments']
data = price * 0.4 + sales * 0.17 + star * 0.13 + comment * 0.3
return data
print(sorted(goods, key=my_sorted))
r = sorted(goods, key=lambda x: x['price'] * 0.4 + x['sales'] * 0.17 + x['stars'] * 0.13 + x['comments'] * 0.3,
reverse=True)
print(r)
|
6499a5126cf4efa70724a88df3f34c4a090aae38
|
AudreyLBacon/Final-Project-Party-Planner
|
/finalproject.py
| 13,591 | 3.703125 | 4 |
from Tkinter import *
import tkMessageBox
from partycalc import *
import tkFont
#partycalc.Class.
root = Tk()
class Application(Frame): # Create a class called 'Application' (Which inherits from the 'Frame' class)#frame is a Tkinter thing for layout that holds everything
def __init__(self, master=None): # How to initialize the class, when created using Application()
Frame.__init__(self, master) # Initialize using Frame's __init__ function
self.parent = master # Set the parent variable to the optional value master
def make_color(self):
self.configure(background = 'orchid1')
def suggestion(self): # Expand later -add suggestion botton pop-up
self.tkMessageBox.showinfo( "Party Planner", "text stuff")#addded for suggestion
def calculate(self):
# Step One: Take the input from the GUI and put it into the party calculator.
party_calculator = None # Create an empty variable for use later. "None" means it's nothing yet.
if self.shape_selection.get() == "Round": # Get if they picked "Round" or "Rectangle" from the GUI
# If they picked round, create a calculator from the PartyCalc class using the round size.
party_calculator = PartyCalc(self.num_guests,"Round",self.round_size_selection.get(),self.seating_space_selection.get())
else:
# If they picked rectangle, create a calculator using the rectangle size.
party_calculator = PartyCalc(self.num_guests,"Rectangle",self.rectangle_size_selection.get(),self.seating_space_selection.get())
# Step Two: This moves the input from the gui questions into the report window.
# This part only handles the questions that don't require math to answer.
text = "Occasion: " + self.event_occasion.get() + "\n"
# Plus-equals is short for: text = text + "More text". Start with what's already there, then add more.
text += "Meal: " + self.meal_selection.get() + "\n"
text += "Location: " + self.location_selection.get() + "\n"
text += "Service: " + self.service_selection.get() + "\n"
text += "Hours: " + self.event_time.get() + "\n"
# Find out which shape, so we know which size to print.
if self.shape_selection.get() == "Round":
text += "Table Type: " + self.round_size_selection.get() + " " + self.shape_selection.get() + "\n"
else:
text += "Table Type: " + self.rectangle_size_selection.get() + " " + self.shape_selection.get() + "\n"
text += "Private Tables: " + self.seating_share_selection.get() + "\n"
text += "Seating: " + self.seating_space_selection.get() + "\n"
text += "Color Scheme: " + self.color_scheme.get() + "\n"
text += "Menu set up instructions included: " + self.menu_selection.get() + "\n"
text += "Table arrangement instructions included: " + self.arrangement_selection.get() + "\n"
# Last Step: Calls the calculate() method on the PartyCalc class.
text += party_calculator.calculate() # Calculate
self.label_output.configure(text = text) # Send the text to the report Label on the gui.
# This method reads the number of guests from the GUI and then saves it as an Integer.
def validate_guests(self):
try: # Try to make it an int...
self.num_guests = int(self.event_guests.get())
except ValueError: # But if it crashes, just use 0.
self.num_guests = 0
# After the user types a number of guests, call calculate() method to recalculate.
self.calculate()
return True
# This code disables the round sizes when the user picks rectangle, and vice versa.
def get_shape_type(self):
if self.shape_selection.get() == "Round":
for item in self.survey_elements[8]:
print item
item.configure(state = "disabled")
for item in self.survey_elements[7]:
item.configure(state = "normal")
else:
for item in self.survey_elements[7]:
item.configure(state = "disabled")
for item in self.survey_elements[8]:
item.configure(state = "normal")
self.calculate()
# This function creates the GUI widgets.
def create_widgets(self):
self.num_guests = 0
self.grid()
# Step One: Divide the screen into two halfs and color them.
self.survey_frame = Frame(self, bg = "orchid1") # This frame has the survey questions
self.survey_frame.grid(row=0,column=0, sticky = N+W+S) # Tells the GUI where on the screen to show the survey section
self.result_frame = Frame(self, bg = "orchid1") # Thhidis frame has the results.
self.result_frame.grid(row=0,column=1) # Tells the GUI where on the screen to show the results
# StringVar is a class used by Tkinter to store strings for the GUI.
self.meal_selection = StringVar()
self.location_selection = StringVar()
self.suggestion = StringVar()
self.service_selection = StringVar()
self.shape_selection = StringVar()
self.round_size_selection = StringVar()
self.rectangle_size_selection = StringVar()
self.seating_space_selection = StringVar()
self.seating_share_selection = StringVar()
self.arrangement_selection = StringVar()
self.menu_selection = StringVar()
self.color_scheme = StringVar()
self.event_occasion = StringVar()
self.event_guests = StringVar()
self.event_time = StringVar()
# List of dictionaries, setting up radio buttons with labels.
# Each entry in the list is a dictionary with a "label" and "options"
# The "options" entry in the dictionary is a list with each radio button option.
questions = [
{'label': "Enter the Event Occasion", 'variable': self.event_occasion},
{'label': "Enter the Number of Guests Expected", 'variable': self.event_guests, 'command': self.validate_guests},
{'label': "Event Start and Finish Time", 'variable': self.event_time},
{'label': "Choose Meal",
'options': ["Breakfast", "Brunch", "Lunch", "Dinner"],
'variable': self.meal_selection,
'command': self.calculate
},
{'label': "Choose Location",
'options': ["Indoors", "Outdoors"],
'variable': self.location_selection,
'command': self.calculate
},
{'label': "Choose Service",
'options': ["Food to Table", "Buffet"],
'variable': self.service_selection,
'command': self.calculate
},
{'label': "Table Type",
'options': ["Round", "Rectangle"],
'variable': self.shape_selection,
'command': self.get_shape_type
},
{'label': "Round sizes",
'options': ["48", "60", "72"],
'variable': self.round_size_selection,
'command': self.get_shape_type
},
{'label': "Rectangle sizes",
'options': ["6ft", "8ft", ],
'variable': self.rectangle_size_selection,
'command': self.get_shape_type
},
{'label': "Choose Seating Space",
'options': ["Max", "Spacious"],
'variable': self.seating_space_selection,
'command': self.calculate
},
{'label': "Will guests sit together or require private tables?",
'options': ["Share", "Private"],
'variable': self.seating_share_selection,
'command': self.calculate
},
{'label': "Table Arrangment instruction included?",
'options': ["Yes", "No"],
'variable': self.arrangement_selection,
'command': self.calculate
},
{'label': "What is the color scheme?",
'variable': self.color_scheme,
'command': self.calculate
},
{'label': "Menu set up instructions included?",
'options': ["Yes", "No"],
'variable': self.menu_selection,
'command': self.calculate
},
]
grid_row = 0
self.survey_elements = []
# This section creates the gui.
for entry in questions: # for loop
survey_array = []
grid_row += 1 # Move down a row, then create the label
lbl = Label(self.survey_frame,background = 'orchid1', text=entry['label'])
lbl.grid(row = grid_row, column = 0, columnspan = 3, sticky = W)
survey_array.append(lbl)
grid_row += 1 # Move down a row and put the options.
grid_column = 1 # Options start on column 1
# If the dictionary has 'options', it's a radio button
if 'options' in entry:
for option in entry['options']:
#First create the radio button
btn = Radiobutton(self.survey_frame, text=option, value = option, background = 'orchid1', variable = entry['variable'], command=entry['command'])
survey_array.append(btn)
# Then place the radio button on the grid
btn.grid(row = grid_row, column = grid_column, sticky = W)
# If this is the first option, make it the default.
if grid_column == 1:
btn.select() # This WAS how I made a line default
# Finally, move to the next column so we're ready for the next option
grid_column += 1
# Otherwise, if the dictionary has no 'options', it's an Entry
else:
if 'command' in entry:
ent = Entry(self.survey_frame, textvariable = entry['variable'], validatecommand = entry['command'], validate = 'focus')
ent.grid(row = grid_row, column = grid_column, columnspan = 2, sticky = W)
else:
ent = Entry(self.survey_frame, textvariable = entry['variable'])
ent.grid(row = grid_row, column = grid_column, columnspan = 2, sticky = W)
#Store references in list.
self.survey_elements.append(survey_array)
# Now that the questions are set up, add a button for printing the report.
self.submit_button = Button(self.survey_frame, text ="Print Report", bg = "pink", command = self.reveal)
self.submit_button.grid(row = grid_row + 1, column = 0, sticky = W)
label_font = tkFont.Font(family='Arial', size=18)# block for report
self.label_output = Label(self.result_frame, font=label_font, text="Please fill out your choices so that we can calculate the result.")
self.label_output.grid(row = 2, column = 5, sticky = E)
def reveal(self):
#display based on what you input in input box, and shown in the other section - create later
content = self.password.get()
if content == "password":
message = "Its stupid now"
else:
message = "blew it"
self.text.delete(0.0,END) #delates input after done with it
self.text.insert(0.0, message)
#When the application object is created, run the create_widgets function.
def __init__(self,master):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
#self.configure(background = 'orchid1')#backround nightmare
#This is the main function, which creates our application object
def main():
root.title("Party Planner") # set the title of the window
root.geometry("1024x768")# sets size of window
root.configure(background = 'orchid1')
app = Application(root)# creates an instance of AppMain which has all the other widgets
# which will show up on the root_widget
app.configure(background = 'orchid1')
root.mainloop() #Tkinter loop that runs all the time to make graphic stay up
if __name__ == '__main__':
main()
'''
def create_widgets():
self.button1 = Button(self,text = "yes") #one way to make buttons
self.button.grid()
self.button2 = Button(self)
self.button2.grid()
self.button2 configure(text = "no") #second way
self.button3 = Button(self) #third way
self.button3.grid()
def __init__(self, master):
# creates a label
var_lbl_message = StringVar(master) # Special Tkinter Variable for label text
var_lbl_message.set("Party Planner")
lbl_message = Label(master, textvariable=var_lbl_message)
lbl_message.pack()
# creates a text entry box
entry_message = Entry(master)
entry_message.insert(0, "text")
entry_message.pack()
# creates a button
# command= sets the function to be called when the button is clicked.
btn_ok = Button(master, text='Ok',command=lambda: var_lbl_message.set(entry_message.get()))
btn_ok.pack()
# main function where an instance of the GUI is created
def main():
root_widget = Tk() # creates a widget window which will hold all other widgets.
root_widget.geometry("1050x768") # sets the size of the window
root_widget.title("Demo Input Text") # set the title of the window
app = AppMain(root_widget) # creates an instance of AppMain which has all the other widgets
# which will show up on the root_widget
root_widget.mainloop() # make the widget window run continuously
# if running file directly
# allow option to import file and call main() from another file
if __name__ == '__main__':
main()
'''
'''
def calculate(self):# calculates numbers for reports
'''
# Future feature functions to expand on listed below:
# report include buffet servers or not
# report include waiters and waitress qty
# report include kitchen workers qty
# create food class
# method to pick menu which then translates and prints shopping list on report
# method to add menus and recipe in dictionary from class,and print info as desired in report
# food method to calculate portions /qty of food to purchase/ per number of people from food class and party class or decide if both classes should be one class
# creat shopping list print out from food class and menu picked
# create function food helpers/ employees/ volunteers tracker: direct to google virtual sign up and live communications.
# create final print out which displays tables and chairs and side tables pattern, and color, text of what is needed , time factors for set up and menue- three pages one final visual of set up and on page for menue and one instructional
# create method for food class enter your own menu
# future rewrite in html css and javascript
|
e9c0e8acc35bcd135a288838d5a8e910e5a8637c
|
adityakverma/Interview_Prepration
|
/LC-387. First Unique Letter in String.py
| 1,622 | 3.640625 | 4 |
# Tags: Hash, String, Google, AWS, MS
# Given a string, find the first non-repeating character in it and
# return it's index. If it doesn't exist, return -1.
# Examples:
# s = "leetcode"
# return 0.
#
# s = "loveleetcode",
# return 2.
class Solution():
def uniqueLetter_aditya(self,s): # ACCEPTED
if len(s) == 1:
return 0
if len(s) < 1:
return -1
for i in range(len(s)-1): # Note since we are checking for occurance of string in s[i+1:] so we take range as (len(s)-1)
if s[i] not in s[i+1:] and s[i] not in s[:i]:
return i
if s[-1] not in s[:-1]: # Special case
return len(s)-1
return -1
def firstUniqChar_Balaji(self, s):
dic = {}
for c in s:
if c in dic: # OR if c in tdict.keys():
dic[c] += 1
else:
dic[c] = 1
for index, c in enumerate(s):
if dic[c] == 1:
return index
return -1
def firstUniqChar(self, s): # TLE .. Not accepted
for i in range(len(s)):
if s.count(s[i])==1:
return i
return -1
if __name__ == '__main__':
s = Solution()
word1 = "loveleetcode"
word2 = "aadadaad" # Answer is 6 and it should be -1
word = "dddccdbba"
print "\nFirst unique letter is at index",s.uniqueLetter_aditya(word)
print "\nFirst unique letter is at index",s.firstUniqChar_Balaji(word)
print "\nFirst unique letter is at index",s.firstUniqChar(word)
|
c92a21cc061dc2d257de3d6e2b9e0bffcfae51ca
|
Virinox/saw_sharpening
|
/Exercise_37.py
| 740 | 4.71875 | 5 |
# Exercise 37
# Level 1
# written by: Vince Mao
# last modified: 2019.5.7
# Description:
# Define a function which can generate and print a list where the values are
# the square of numbers between 1 and 20 (both included). Print the last 5 elements in the list.
#
# Hint:
# Use the ** operator to calculate the power of a number.
# Use the range() method for loops.
# Use the list.append() method to add values to a list.
# Use [n1:n2] to slice a list.
#
# Pseudocode:
# 1. Define a function that loops in the range of 1 to 21.
# 2. Append the result to an array.
# 3. Return the slice of the array.
def square_slice():
result = []
for i in range(1, 21):
result.append(i ** 2)
return result[15:]
print square_slice()
|
f0cdf4d9fc2596e19fa72d0c5ea87f150ffe0a49
|
Abdelhamid-bouzid/problem-Sovling-
|
/Medium/convert.py
| 1,190 | 4.40625 | 4 |
'''
The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)
P A H N
A P L S I I G
Y I R
And then read line by line: "PAHNAPLSIIGYIR"
Write the code that will take a string and make this conversion given a number of rows:
string convert(string s, int numRows);
Example 1:
Input: s = "PAYPALISHIRING", numRows = 3
Output: "PAHNAPLSIIGYIR"
Example 2:
Input: s = "PAYPALISHIRING", numRows = 4
Output: "PINALSIGYAHRPI"
Explanation:
P I N
A L S I G
Y A H R
P I
Example 3:
Input: s = "A", numRows = 1
Output: "A"
'''
class Solution:
def convert(self, s: str, numRows: int) -> str:
string = ['' for i in range(numRows)]
i = 0
r = 0
while i<len(s):
if r<numRows:
string[r] += s[i]
r +=1
i +=1
else :
j = numRows-2
while i<len(s) and j>0:
string[j]+=s[i]
j -=1
i +=1
r = 0
ss = ''.join(string)
return ss
|
60bd29af7047f6234d46cb0c53f9db39a18c636b
|
leihuagh/python-tutorials
|
/books/AutomateTheBoringStuffWithPython/Chapter03/PracticeProjects/P01_make_collatz_seq.py
| 859 | 4.59375 | 5 |
# This program makes a Collatz Sequence for a given number
# Write a function named collatz() that has one parameter named number.
# If number is even, then collatz() should print number // 2 and return this value.
# If number is odd, then collatz() should print and return 3 * number + 1.
# Then write a program that lets the user type in an integer and that keeps calling
# collatz() on that number until the function returns the value 1.
# Sample output:
# Enter number:
# 3
# 10
# 5
# 16
# 8
# 4
# 2
# 1
def collatz(number):
if not number % 2:
return number // 2
else:
return 3 * number + 1
def main():
n = int(input("Input a number: "))
while n != 1:
print(n)
n = collatz(n)
print(n) # When n == 1
# If program is run (instead of imported), call main():
if __name__ == "__main__":
main()
|
e3ee856ab4f0ba61b4b0d9819ca959f543cd781a
|
tiddler/AutoDiff
|
/autodiff/node.py
| 2,653 | 4.15625 | 4 |
class Node(object):
"""Node in a computation graph."""
def __init__(self):
"""Constructor, new node is indirectly created by Op object __call__ method.
Instance variables
------------------
self.inputs: the list of input nodes.
self.op: the associated op object,
e.g. add_op object if this node is created by adding two other nodes.
self.const_attr: the add or multiply constant,
e.g. self.const_attr=5 if this node is created by x+5.
self.name: node name for debugging purposes.
"""
self.inputs = []
self.op = None
self.const_attr = None
self.name = ""
def __add__(self, other):
"""Adding two nodes return a new node."""
from .op import add_op, add_byconst_op
if isinstance(other, Node):
new_node = add_op(self, other)
else:
# Add by a constant stores the constant in the new node's const_attr field.
# 'other' argument is a constant
new_node = add_byconst_op(self, other)
return new_node
def __neg__(self):
"""take the negative value return a new node"""
from .op import neg_op
return neg_op(self)
def __sub__(self, other):
"""Substracting a node by another and return a new node"""
return self + (-other)
def __rsub__(self, other):
return other + (-self)
def __mul__(self, other):
"""Multiply two nodes return a new node."""
from .op import mul_op, mul_byconst_op
if isinstance(other, Node):
new_node = mul_op(self, other)
else:
# Multiply by a constant stores the constant in the new node's const_attr field.
# 'other' argument is a constant
new_node = mul_byconst_op(self, other)
return new_node
def __truediv__(self, other):
"""Divide a node by another, return a new node."""
from .op import recipr_op
if isinstance(other, Node):
new_node = self * recipr_op(other)
else:
new_node = self * (1.0 / other)
return new_node
def __rtruediv__(self, other):
"""Divide a node by another, return a new node."""
from .op import recipr_op
return other * recipr_op(self)
# Allow left-hand-side add and multiply.
__radd__ = __add__
__rmul__ = __mul__
def __str__(self):
"""Allow print to display node name."""
return self.name
__repr__ = __str__
def Variable(name):
"""User defined variables in an expression.
e.g. x = Variable(name = "x")
"""
from .op import placeholder_op
placeholder_node = placeholder_op()
placeholder_node.name = name
return placeholder_node
|
4cdc4772d79a309608cad7a32b0dcee6085637c0
|
vaibhav0103/Fb_Page_Bot
|
/fb_bot.py
| 2,708 | 3.546875 | 4 |
import facebook
from keys import *
import json
# Get Graph
graph = facebook.GraphAPI(access_token=access_token_pg)
FILE_NAME = 'last_post_id.txt'
# Retrive last post id
def retrieve_last_post_id(file_name):
f_read = open(file_name, 'r')
last_post_id = str(f_read.read())
f_read.close()
return last_post_id
# Store Last Post Id
def store_last_post_id(last_post_id, file_name):
f_write = open(file_name, 'w')
f_write.write(str(last_post_id))
f_write.close()
return
# Get the active user's page posts
def get_posts():
# get post data for current page , fields contain the required post fields
# set limit to n to get last n posts
posts = graph.get_connections(id='me', connection_name='feed', limit=5, fields='message,link,created_time')
# Reversed to get posts in the order/time created i.e older first and newest last
for post in reversed(posts['data']):
# Print data from Post
print(json.dumps(post, sort_keys=False, indent=4))
# print(post['id'])
# To like,delete, comment on multiple posts together call the like,delete comment Functions here
# And Pass the post id and message(for comment)
# eg. like_post(post['id'])
last_post_id = post['id']
# To get id of last post id
store_last_post_id(last_post_id, FILE_NAME)
# Create New Post On Page
def post_to_fb():
graph.put_object(
parent_object="me",
connection_name="feed",
message="This is a great website. Everyone should visit it.",
link="https://example.com")
print("Posted On facebook")
# Create Multiple New Posts On Page
def multiple_post_to_fb():
messages = ["Test message 1", "Test message 2", "Test message 3", "Test message 4"]
for message in messages:
graph.put_object(
parent_object="me",
connection_name="feed",
message=message,
link="https://example.com")
print("Posted " + message + " On facebook")
# Delete Post By Id
def delete_post(post_id):
# last_seen_id = retrieve_last_seen_id(FILE_NAME)
# to get last stored post id (Use get_posts to store latest post id)
graph.delete_object(id=post_id)
print("Post with ID " + post_id + " Deleted")
# Comment On Post By Id
def comment_on_post(post_id, message):
graph.put_comment(object_id=post_id, message=message)
print("Commented On the Post")
# Like Post
def like_post(post_id):
graph.put_like(object_id=post_id)
print("Liked Post")
print("Current Post Ids:")
get_posts()
# Example Delete Post
# post_to_fb()
# id = retrieve_last_post_id(FILE_NAME)
# delete_post(id)
# print("Remaining Post IDs:")
# get_posts()
|
669ae929a267ce425fa852cd392f7808cb932583
|
iamlmn/PyDS
|
/algos/patterns/slidingWindows/smallestWindowContainingSubstring.py
| 2,255 | 4.3125 | 4 |
# Smallest Window containing Substring (hard) #
# Given a string and a pattern, find the smallest substring in the given string which has all the characters of the given pattern.
# Example 1:
# Input: String="aabdec", Pattern="abc"
# Output: "abdec"
# Explanation: The smallest substring having all characters of the pattern is "abdec"
# Example 2:
# Input: String="abdabca", Pattern="abc"
# Output: "abc"
# Explanation: The smallest substring having all characters of the pattern is "abc".
# Example 3:
# Input: String="adcad", Pattern="abc"
# Output: ""
# Explanation: No substring in the given string has all characters of the pattern.
def findSmallestWindow(stringInput, subString):
'''
create a counter of chars in substring and store it as hash map.
keep increasing window end untill everythhing becomes zero and start shrinking from left untill everything in the counter/hash has values as 0.
'''
start = 0
charFrequency = {}
minLength = len(stringInput)
matched = 0
outputString = ""
for i in range(len(subString)):
if subString[i] not in charFrequency:
charFrequency[subString[i]] = 0
charFrequency[subString[i]] += 1
for i in range(len(stringInput)):
cChar = stringInput[i]
if cChar in charFrequency:
charFrequency[cChar] -= 1
if charFrequency[cChar] == 0:
matched += 1
while matched == len(charFrequency):
# found all chars, now try shrinking the window.
rChar = stringInput[start]
start += 1
if rChar in charFrequency:
if charFrequency[rChar] == 0:
matched -= 1
charFrequency[rChar] += 1
minLength = min(minLength, i - start + 1)
outputString = stringInput[start - 1: i + 1]
return outputString
if __name__ == '__main__':
string1 = 'aabdec'
substring = 'abc'
string2 = 'abdabca'
string3 = 'adcad'
print(f"aabdec, abc : {findSmallestWindow(string1, substring)}")
print(f"abdabca, abc : {findSmallestWindow(string2, substring)}")
print(f"adcad, abc : {findSmallestWindow(string3, substring)}")
|
c42d85e296e1b71ffff909e2a7791a72ec2e99e3
|
linlilin/GA
|
/coba.py
| 1,251 | 3.859375 | 4 |
"""
Matplotlib Animation Example
author: Jake Vanderplas
email: [email protected]
website: http://jakevdp.github.com
license: BSD
Please feel free to use and modify this, but keep the above information. Thanks!
"""
from matplotlib import pyplot as plt
from matplotlib import animation
# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(-2, 2), ylim=(-2, 2))
line, = ax.plot([], [], 'ro')
# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,
# animation function. This is called sequentially
def animate(i):
x = [-1,0,1]
y = [i+1,i+0,i-1]
line.set_data(x, y)
return line,
# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=2, interval=200, blit=False,repeat=True)
# save the animation as an mp4. This requires ffmpeg or mencoder to be
# installed. The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5. You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
plt.show()
|
cdd303c47b0449aeeb0d66f4b994e0d501c2ed07
|
anaxmnenik/Mk-PT1-41-21
|
/Tasks/Kuchko/test.py
| 544 | 3.78125 | 4 |
#Депозит:
#начальная сумма - 20000 BYN
#срок - 5 лет
#процент (годовой) - 15%
#ежемесячная капитализация
#Вычислить сумму на счету в конце указанного срока.
a = int(input("Введите начальную сумму: "))
b = int(input("Введите срок: "))
c = float(input("Введите процент: "))
# ежемесячная капитализация
summa = a * ((1 + (c/100)/12))**(b*12)
print(round(summa, 2))
|
84837d2193df06037893adc401ca856d2b29e465
|
Quelklef/gin-bots
|
/interactive.py
| 5,828 | 3.75 | 4 |
"""
For playing a human player against a bot using a physical deck.
Sample REPL code to use this module:
>>> import sys
>>> sys.path.append('bots/simple')
>>> from simple_gin import simple_bot
>>> import interactive
>>> interactive.play(simple_bot, bot_plays_first=True)
Of course, you can replace the simple bot with any bot
"""
import gin
import client
from cards import Card, parse_card_is_ok
from util import input_until
#= define physical deck =#
class PhysicalDeck:
def __init__(self):
self.card_count = 52
def pop(self):
card = Card(input_until(
"Draw for me, please: ",
parse_card_is_ok,
))
self.card_count -= 1
return card
def __len__(self):
return self.card_count
#= define game =#
def get_hand():
hand = set()
for i in range(1, 10 + 1):
while True:
card = Card(input_until(
f"Card #{i}: ",
lambda s: parse_card_is_ok,
))
if card in hand:
print("Woah, you've already given me that card. Try again.")
continue
hand.add(card)
break
return hand
def get_bot_hand():
print("What's my hand?")
return get_hand()
def play(bot, *, bot_plays_first: bool):
deck = PhysicalDeck()
history = []
discard = []
bot_hand = get_bot_hand()
is_bots_turn = bot_plays_first
while True:
# Deck running out is a tie
if len(deck) == 0:
return 0
if is_bots_turn:
_, _, bot_ending = play_bots_turn(deck, history, discard, bot, bot_hand)
if bot_ending: break
else:
_, _, player_ending = play_humans_turn(deck, history, discard)
if player_ending: break
is_bots_turn = not is_bots_turn
end_game(bot_hand)
def end_game(bot_hand):
print(f"What were the human player's cards?")
human_hand = get_hand()
score = gin.score_hand(bot_hand, human_hand)
print(f"Score, bot-relative, is {score}")
def play_bots_turn(deck, history, discard, bot, bot_hand):
discard_copy = [*discard]
draw_choice, discard_choice, bot_ending = player_turn(deck, history, discard, bot, bot_hand)
if draw_choice == 'discard':
gained_card = discard_copy[-1]
print(f"I'll take the {gained_card} the discard; thanks.")
if bot_ending:
points = gin.points_leftover(bot_hand)
if points == 0:
print(f"Discard {discard_choice}: Gin!")
else:
print(f"I'll discard {discard_choice} to go down for {points}.")
else:
print(f"Discard {discard_choice}, please.")
return (draw_choice, discard_choice, bot_ending)
def play_humans_turn(deck, history, discard):
draw_choice = input_until(
"Did the human draw from the deck (1) or from the discard (2)? [1/2]: ",
lambda s: s in ['1', '2']
)
draw_choice = {
'1': 'deck',
'2': 'discard',
}[draw_choice]
if draw_choice == 'deck':
deck.card_count -= 1
if draw_choice == 'discard':
discard.pop()
human_move = input_until(
"What did the human discard? Or are they ending the game? [card/'end']: ",
lambda s: s == 'end' or parse_card_is_ok(s),
)
human_ending = human_move == 'end'
if human_ending:
# Not sure what the human discarded since played face-down
discard_choice = None
else:
discard_choice = Card(human_move)
discard.append(discard_choice)
history.append((draw_choice, discard_choice))
return (draw_choice, discard_choice, human_ending)
if __name__ == '__main__':
import sys
sys.path.append('bots/simple')
from simple_gin import simple_bot
play(simple_bot, bot_plays_first=True)
# == # == #
# The following code is bad and slated for removal but is needed for this module to run right now
def do_turn(deck, history, discard, player1, hand1, player2, hand2, current_player):
""" do a turn, returning the score or None if the game isn't done """
# We choose to make the deck running out be a tie
if len(deck) == 0:
return 0
current_player_hand = hand1 if current_player == player1 else hand2
other_player_hand = hand2 if current_player == player1 else hand1
_, _, player_ending = player_turn(deck, history, discard, current_player, current_player_hand)
if player_ending:
score = score_hand(current_player_hand, other_player_hand)
score_sign = 1 if current_player_hand == hand1 else -1
return score_sign * score
def player_turn(deck, history, discard, player, hand):
""" have the player take a turn; return whether or not the player ends the game """
draw_choice, _ = player_draw (deck, history, discard, player, hand)
discard_choice, player_ending = player_discard(deck, history, discard, player, hand)
history.append((draw_choice, discard_choice))
return (draw_choice, discard_choice, player_ending)
def player_draw(deck, history, discard, player, hand):
""" have the player draw a card """
draw_choice = player({*hand}, [*history])
if draw_choice == 'deck':
drawn_card = deck.pop()
elif draw_choice == 'discard':
if len(discard) == 0:
raise ValueError("Cannot draw from an empty discard!")
drawn_card = discard.pop()
else:
raise ValueError(f"Expected either 'deck' or 'discard', not {repr(draw_choice)}.")
hand.add(drawn_card)
return (draw_choice, drawn_card)
def player_discard(deck, history, discard, player, hand):
""" have the player discard a card and optionally end the game """
discard_choice, do_end = player({*hand}, [*history])
discard_choice = Card(discard_choice)
if discard_choice not in hand:
raise ValueError(f"Cannot discard {discard_choice} since it's not in your hand.")
discard.append(discard_choice)
hand.remove(discard_choice)
if do_end: # end the game
if points_leftover(hand) > MAX_POINTS_TO_GO_DOWN:
raise ValueError(f"Cannot end on more than {MAX_POINTS_TO_GO_DOWN} points.")
return (discard_choice, do_end)
|
18169c3cee52110cd8a4841890f5056aafbc749d
|
Logan-Greenwood/py4e
|
/saved-things/week7-8/readingfiles.py
| 430 | 3.71875 | 4 |
# Use the file name mbox-short.txt as the file name
fname = input("Enter file name: ")
fh = open(fname)
total = 0
count = 0
for line in fh:
if not line.startswith("X-DSPAM-Confidence:") : continue
count += 1
line = line.rstrip()
start = line.find(":")
num2add = float(line[start + 1:])
total += num2add
# print(my_sum)
# print(count)
avg = total / count
print("Average spam confidence:", avg)
|
06e899d38de05cd8fb293cb1b1a4453ec701525c
|
Modrisco/OJ-questions
|
/Project Euler/001-100/025.py
| 419 | 3.5 | 4 |
# 1000-digit Fibonacci number
# def fib(n):
# a = 1
# b = 0
# while n > 1:
# a, b = a+b, a
# n-=1
# return a
# def binetFibFormula(n):
# n = decimal.Decimal(10)
# return len(str(int((((1+sqrt(5))**n - (1-sqrt(5))**n)/(2**n*sqrt(5))))))
# print(binetFibFormula(100))
flag = 0
l = [1, 1]
i = 1
while (flag == 0):
if (len(str(l[i]))) >= 1000:
flag = 1
print(i+1)
else:
l.append(l[i] + l[i-1])
i+=1
|
ad4eb754aa253b059faf8f59cb6ad049f05e48ce
|
himanshuKp/python-practice
|
/challenges/find_common.py
| 671 | 4.15625 | 4 |
# Write a function called common_letters that takes two arguments, string_one and string_two and then returns a list with all of the letters they have in common.
# The letters in the returned list should be unique. For example,
# common_letters("banana", "cream")
# should return ['a'].
def common_letters(string_one,string_two):
length_string_one = len(string_one)
length_string_two = len(string_two)
final_common = []
if length_string_one < length_string_two:
for count in range(len(string_one)):
if (string_one[count] in string_two) and (string_one[count] not in final_common):
final_common.append(string_one[count])
return final_common
|
eef52efd59b653da76902f30bd58723977341a73
|
Lorena-ReyF/CursoPythonOctubre2019
|
/EjemploRandInt.py
| 212 | 3.53125 | 4 |
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 20 10:35:21 2019
@author: yocoy
"""
#from random import randint
#
#print(randint(0,100))
def funcion():
print("Hola")
return 0
x = funcion()
print(x)
|
e709968572f9d74dfcee6c849dd55787116124a3
|
thushanp/CodingPuzzles
|
/mergesort.py
| 774 | 3.75 | 4 |
def msort3(x):
# initialise my results array
result = []
# case for when we get to single elements
if len(x) < 2:
return x
# find middle of the given array
mid = int(len(x) / 2)
# recursively sort lower and upper half
y = msort3(x[:mid])
z = msort3(x[mid:])
# initialise counters
i = 0
j = 0
# iterate through both halves appending to results array
while i < len(y) and j < len(z):
if y[i] > z[j]:
result.append(z[j])
j += 1
else:
result.append(y[i])
i += 1
# concatenate the last part of the other half
result += y[i:]
result += z[j:]
return result
print(msort3([3,5,1,4,6,3,2,6,3,4]))
|
50511769268366390cee3793e072ee8d16f5a5a8
|
co-dh/euler_in_j
|
/set_partition.py
| 175 | 3.5625 | 4 |
def sp(n):
"int -> [ [int] ] "
if n == 1:
yield [1]
return
else:
for a in sp(n-1):
for last in range(1, max(a)+2):
yield a+[last]
print list(sp(4))
|
6814d483932c63d8d9f184a38927b51ba412e0e8
|
LeslieK/PyScheme
|
/modularity.py
| 5,785 | 4.28125 | 4 |
"""
using streams to modularize a program without storing state
each stream value represents a state
successive values represents values over time
streams allow you to go back in time; i.e. roll back state!
Ex. 3.81, 3.82
"""
from pairs import integers_starting_from, integers
from iterStreams import stream_map, stream_ref, cons_stream, stream_car, stream_cdr, \
partial_sums, mul_streams, scale_stream, add_streams
from fractions import gcd
from mutation312 import cesaro_test, rand_update, rand_init, rand
import math, random
ones = cons_stream(1, lambda: ones)
random_numbers = cons_stream(rand_init, lambda: stream_map(rand_update, random_numbers))
cesaro_stream = cons_stream(gcd(int(rand_init), int(stream_ref(random_numbers, 1))) == 1,
lambda: map_successive_pairs(lambda x, y: gcd(x, y) == 1, random_numbers))
def map_successive_pairs(f, s):
"""
f: function
s: stream
"""
return cons_stream(f(stream_car(s), stream_ref(s, 1)),
lambda: map_successive_pairs(f, stream_cdr(stream_cdr(s))))
def monte_carlo(experiment_stream, passed, failed):
def next(passed, failed):
"""
generate next probability
passed, failed: accumulators of 1s and 0s
"""
return cons_stream(passed / (passed + failed),
lambda: monte_carlo(stream_cdr(experiment_stream),
passed, failed))
if stream_car(experiment_stream):
return next(passed + 1, failed)
else:
return next(passed, failed + 1)
pi = stream_map(lambda x: math.sqrt(6 / x), monte_carlo(cesaro_stream, 0, 0))
# Ex. 3.81
# stream of requests: generate, reset, reset, generate, ...
def rand2(s):
"""
s: a stream of requests
produces a stream of random numbers
"""
rs = cons_stream(rand_init,
lambda:
stream_map(lambda x: stream_car(stream_map(rand_update, rs)) if x == 'generate' else rand_init,
s))
return rs
# Ex. 3.5 Monte Carlo Integration
def monte_carlo(trials, experiment):
"""
experiment: returns 0 or 1
produces a fraction: number 1s / number trials (prob of getting a 1)
"""
def iter(trials_remaining, trials_passed):
if trials_remaining == 0:
return trials_passed / trials
else:
return iter(trials_remaining - 1, trials_passed + experiment())
return iter(trials, 0)
def random_in_range(low, high):
return random.uniform(low, high)
# the experiment
def estimate_integral(P, x1, x2, y1, y2, trials):
"""
returns estimate of area of circle defined by P(x, y)
"""
def in_region_test():
return P(random_in_range(x1, x2), random_in_range(y1, y2))
return monte_carlo(trials, in_region_test) * (x2 - x1) * (y2 - y1)
def estimate_pi(trials):
# area = pi * r**2; use unit circle => area = pi
return estimate_integral(lambda x, y: (x - 1)**2 + (y - 1)**2 <= 1, 0, 2, 0, 2, trials)
# Ex. 3.82
# Redo 3.5 on monte carlo integraion in terms of streams. The stream version of estimate-integral
# will not have an argument trials. Instead, it will produce a stream of estimates based on successively
# more trials.
def monte_carlo(experiment_stream):
"""
produces a stream of estimates of circle area / rectangle area
"""
return mul_streams(partial_sums(experiment_stream), stream_map(lambda x: 1 / x, integers))
def estimate_integral(P, x1, x2, y1, y2):
"""
produces a stream of estimates of area of circle defined by P(x, y)
each estimate corresponds to an additional trial
"""
def in_region_test():
return P(random_in_range(x1, x2), random_in_range(y1, y2))
def outcome_stream(test):
return cons_stream(test(), lambda: outcome_stream(test))
es = outcome_stream(in_region_test)
return scale_stream(monte_carlo(es), (x2 - x1) * (y2 - y1))
def pi_estimate():
"""
produce stream of estimates: (unit circle area / area of rectangle) * area of rectangle
"""
return estimate_integral(lambda x, y: (x - 1)**2 + (y - 1)**2 <= 1, 0, 2, 0, 2)
# functional programming view of time
def stream_withdraw(balance, amount_stream):
"""
produces a stream of balances
"""
return cons_stream(balance,
lambda: stream_withdraw(balance - stream_car(amount_stream), stream_cdr(amount_stream)))
#######################
random.seed(rand_init)
if __name__ == "__main__":
s = cons_stream('generate',
lambda: cons_stream('reset',
lambda: cons_stream('generate',
lambda: cons_stream('generate',
lambda: cons_stream('reset',
lambda: 'generate')))))
### Ex. 3.81
rs = rand2(s)
for i in range(6):
x = stream_ref(rs, i)
print(x)
#x = random.uniform(0, 1)
#P = lambda x, y: (x - 1)**2 + (y - 1)**2 <= 1
#def in_region_test():
# return P(random_in_range(0, 2), random_in_range(0, 2))
#def outcome_stream(test):
# return cons_stream(test(), lambda: outcome_stream(test))
#es = outcome_stream(in_region_test)
#ps = partial_sums(es)
#fs = mul_streams(partial_sums(es), stream_map(lambda x: 1 / x, integers))
#for i in range(100):
# print(i + 1, stream_ref(fs, i))
### Ex. 3.82
#pi = estimate_pi(50)
#pi
pi = pi_estimate()
for i in range(60):
print(i + 1, stream_ref(pi, i))
pi
|
acc410f13c7f70349277fae6a80cbf6413fde68a
|
a-utkarsh/python-programs
|
/Numpy/Joining.py
| 1,227 | 3.609375 | 4 |
# Concatenate
import numpy as np
a = np.array([[1,2],[3,4]])
print ('First array:')
print (a)
print ('\n')
b = np.array([[5,6],[7,8]])
print ('Second array:')
print (b)
print ('\n')
# both the arrays are of same dimensions
print ('Joining the two arrays along axis 0:')
print (np.concatenate((a,b)))
print ('\n')
print ('Joining the two arrays along axis 1:')
print (np.concatenate((a,b),axis = 1))
#Stack method
a = np.array([[1,2],[3,4]])
print ('First Array:')
print (a)
print ('\n')
b = np.array([[5,6],[7,8]])
print ('Second Array:')
print (b)
print ('\n')
print ('Stack the two arrays along axis 0:')
print (np.stack((a,b),0) )
print ('\n')
print ('Stack the two arrays along axis 1:')
print (np.stack((a,b),1))
#Hstack method
import numpy as np
a = np.array([[1,2],[3,4]])
print ('First array:')
print (a)
print ('\n')
b = np.array([[5,6],[7,8]])
print ('Second array:')
print (b)
print ('\n')
print ('Horizontal stacking:')
c = (np.hstack((a,b)))
print (c)
print ('\n')
#Vstack
import numpy as np
a = np.array([[1,2],[3,4]])
print ('First array:')
print (a)
print ('\n')
b = np.array([[5,6],[7,8]])
print ('Second array:')
print (b)
print ('\n')
print ('Vertical stacking:' )
c = np.vstack((a,b))
print (c)
|
d0b03677ed4468d54030200f79daf408182661ab
|
jrecuero/pyos
|
/apps/pytres/collision.py
| 505 | 3.5 | 4 |
from point import Point
class CollisionBox:
def __init__(self):
self.box = set()
def add(self, item):
self.box.add(item.hash())
def collision_with(self, other_box):
return self.box.intersection(other_box.box)
def collision_with_upper(self, collision):
upper_box = CollisionBox()
for x, y in collision:
upper_box.add(Point(x, y - 1))
return self.collision_with(upper_box)
def __str__(self):
return str(self.box)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.