blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
ad4331718451489cd2790c8e55d25fecc7fb12a6 | thembela1999/PythonFundamental-Week1-4 | /PYTHON FUNDAMENTALS -(week5)/WEEK 1/Day 2/Activity1.py | 427 | 3.953125 | 4 | # Multi_dot is used to compute the dot product of two or more arrays in a single function call,
# while automatically selecting the fastest evaluation order.
from numpy.linalg import multi_dot
import numpy as np
# calculate the product of the following arrays
A = np.array([ 1.2, 0.5, 1 , 5])
B = np.array([6.2, 0.9, 5, 6])
C = np.array([1, 0, 0, 5])
Result = np.dot(np.dot(A, B), C )
print(Result) |
ba17fb592ca9e510a62caedec08bac1c130e53c3 | ypmoraes/Curso_em_video | /ex052.py | 1,186 | 4.34375 | 4 | '''
########################################################################################
## Enunciado: Faca um programa que leia um numero inteiro e diga se ##
## ele eh ou nao um numero primo ##
## ##
## Criado por: Yuri Moraes ##
## Data:06/06/20 ##
## Email:[email protected] ## ##
########################################################################################
'''
num1=int(input('Digite um numero:'))
cont=0
for c in range(1, num1+1):
if num1 % c ==0:
print("Este numero foi divisivel por {}" .format(c))
cont+=1
else:
print("Este numero nao foi divisivel por {}".format(c))
print("Este numero foi divisivel {} vezes" .format(cont))
if cont == 2:
print("Este numero eh primo")
else:
print("Este numero nao eh primo")
|
fc0a3bdee121f5c523e0d442b2729f53522a78d6 | FitzFrosty/python_work | /auto_boring_1.py | 317 | 3.875 | 4 | print("Hello World")
print("Please, tell me your name: ")
user_name = input()
print("Nice to meet you" + user_name)
print("Did you know the length of your name is: ")
print(len(user_name))
print("How old are you?")
user_age = input()
print("Wow! You will be " + str(int(user_age) +1) + " in a year")
test
|
d04b84ded296861a5736c2411179977dc251adb2 | anhtylee/abx-algorithm-exercices | /src/optimal-division.py | 577 | 3.59375 | 4 | # url https://leetcode.com/problems/optimal-division/
# writtenby:anhty9le
class Solution:
def optimalDivision(self, nums):
"""
:type nums: List[int]
:rtype: str
"""
n = len(nums)
if n == 1:
return str(nums[0])
if n == 2:
return str(nums[0]) + "/" + str(nums[1])
s = ""
s += str(nums[0]) + "/("
i = 1
while i < n - 1:
s += str(nums[i]) + "/"
i += 1
s += str(nums[n - 1]) + ")"
return s
|
4fbf36a903dc7432790b909bddb71bec93de931f | EndIFbiu/python-study | /04-循环/06-continue.py | 152 | 3.828125 | 4 | i = 1
while i <= 5:
if i == 3:
print('发现虫子不吃了')
i += 1
continue
print('吃第%d个苹果' % i)
i += 1
|
5eec8fbd06fa474a377a5edb762fadf36899c8da | khrushv/omd | /omd.py | 5,253 | 3.65625 | 4 | # Stepanov Nikita
from random import randrange
def start():
print(
'У одного из учеников не получается домашка и '
'нужно помочь ему и разобрать ошибки. Для этого есть выход - '
'нам нужен ментон Утка-тив 🦆 🕵️ , поможем?'
)
option = ''
options = {'да': True, 'нет': False}
while option not in options:
print('Выберите: {}/{}'.format(*options))
option = input()
if options[option]:
return quiz()
return stay()
def quiz():
print("Ученик не до конца разобрал первую лекцию и у него есть пара вопросов"
"и нужна помощь, поэтому как говорится - 'Кря-кря'")
score = 0
questions = {"Допускается ли в коде множество длинных строк,"
" и использование табов?.":
{'a': ('\na. Ничего страшного, можно и так оставить. ', False),
'b': ('\nb. Сокращаем до 99 символов строки и делаем 4 пробела', True),
'c': ('\nc. Можно сократить до 77 символов '
'и заменить табуляцию на 4 пробела', True)},
"Утка-тив заметил, что ученик пытается сравнить 2 переменные "
"типа float, можно ли так делать?":
{'a': ('\na. Да, ведь числа можно сравнивать между собой', False),
'b': ('\nb. Нет, ведь некоторая точность теряется', True)},
"Является ли set упорядоченным?":
{'a': ('\na. Да', False), 'b': ('\nb. Нет', True)},
"Почему python называется именно так? ": {
'a': ('\na. Название пошло от семейства пресмыкающихся', False),
'b': ('\nb. Назвали в честь британского телешоу', True)}}
for question, answer_options in questions.items():
user_choice = ''
while user_choice not in answer_options.keys():
print(question)
for answer in answer_options.values():
print(answer[0])
print('Выберите один из вариантов: ', *answer_options)
user_choice = input()
if answer_options[user_choice][1]:
score += 1
print("Благодаря Утка-тиву количество правильных ответов у ученика: ", score)
return web()
def stay():
print(
'Осудительное кря-кря-кря 🦆, '
'Утка-тив является одним из менторов ААА, а как известно менторы в '
'ААА бороться с проблемами, а не избегают их.'
'Так что давай повторим.'
)
return start()
def web():
print('Двигаемся дальше, наши кураторы сообщили о том, что некоторые студенты не могут включить вебкамеры,'
'поэтому нужно помочь им и включить их, для этого нужно написать их номер'
'(X - выключенная,O - включенная), когда закончите введите #')
student_cameras = []
number_of_students = 5
for i in range(number_of_students):
if not randrange(2):
student_cameras.append('X')
else:
student_cameras.append('O')
user_choice = ''
while user_choice != '#':
print(student_cameras)
user_choice = input("Введите порядковый номер студента(с нуля): ")
try:
is_camera_turned_on = student_cameras[int(user_choice)] == 'O'
except (IndexError, ValueError):
continue
if is_camera_turned_on:
student_cameras[int(user_choice)] = 'X'
else:
student_cameras[int(user_choice)] = 'O'
all_cameras_turned_on = True
for student_camera in student_cameras:
if student_camera == 'X':
all_cameras_turned_on = False
break
if all_cameras_turned_on:
print("Спасибо, Утка-тив 🦆 🕵️, вы успешно крякнули все камеры!")
else:
print("Некоторые камеры остались выключенными, точно ли вы Утка-тив?")
print("Отлична работа, Утка-тив, теперь наконец можно зайти в паб, вопрос "
"лишь в том взять ли зонтик ☂️?")
if __name__ == '__main__':
start()
|
90c36e45c2229061c41e6a9c4b3e75ed3a1d9014 | alijafargholi/code_puzzles | /puzzle_05/pile_of_cubes.py | 1,010 | 4.375 | 4 | """
Build a Pile of Cubes
=====================
Your task is to construct a building which will be a pile of n cubes. The cube
at the bottom will have a volume of n^3, the cube above will have volume of
(n-1)^3 and so on until the top which will have a volume of 1^3.
You are given the total volume m of the building. Being given m can you find
the number n of cubes you will have to build?
The parameter of the function findNb (find_nb, find-nb, findNb) will be an
integer m and you have to return the integer n such as
n^3 + (n-1)^3 + ... + 1^3 = m if such a n exists or -1 if there is no such n.
Source
^^^^^^
https://www.codewars.com/kata/build-a-pile-of-cubes/train/python
"""
def find_nb(m: int) -> int:
"""Find the number n of cubes we will have to build"""
n = 2
result = 0
# Clue --> 1^3 + 2^3 + 3^3 + 4^3 + ... n^3 = (1 + 2 + 3 +...n)^2
while result < m:
result = pow(sum(range(n)), 2)
if result == m:
return n-1
n += 1
return -1
|
63ebbfb951093559be7f3e40ce377bb78f2d6315 | MudimukkuSreenath/python | /class.py | 360 | 3.5 | 4 | class First:
def __init__(self,a,b):
self.a = a
self.b = b
print("iam constructor")
def sum(self):
res=self.a+self.b
print(res)
'''def __str__(self):
print("a="+str(self.a)+"b="+str(self.b))'''
def __del__(self):
print("iam destructor")
obj=First(10,20)
print(obj)
obj.sum() |
e930bbeabe7c6de336e0dcc83ba61e081b4b326b | Nyolczas/Python | /MEGA/basics/sliceList.py | 423 | 3.875 | 4 | myList = ["béka", "csöcs", 112]
print(myList[0:2])
print(myList[1:2])
print(myList[1])
print(myList[:2])
print(myList[-2:])
napok = ["hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat", "vasárnap"]
print(napok[0:5])
print(napok[4])
print(napok[4:6])
print(napok[6])
myList.remove(112)
print(myList)
myList.append("szopogatás")
print(myList)
myList.pop(1)
print(myList)
napok.sort()
print(napok)
|
bdf4674dbff21a23286c928d958e90fc4cbb2539 | upasek/python-learning | /array/array_count.py | 467 | 4.34375 | 4 | #Write a Python program to get the number of occurrences of a specified element in an array.
from array import *
array = array('i', [1, 3, 5, 3, 7, 9, 3])
num = int(input("Input the integer : "))
count = 0
for i in array:
if i == num:
count += 1
print("Original array :",array)
print("Number of occurrences of the number %d in the said array: %d"%(num, count))
#print("Number of occurrences of the number 3 in the said array: "+str(array.count(num)))
|
367be05ef8bfcc2dbed50788b68c216a34b4440e | bielvieiralima/Projeto-part1-fis | /code.py | 1,327 | 4.1875 | 4 | from math import *
c = 3*(10**8)
pi = 3.1415
def comprimento_de_onda():
comprimento = float(input("Digite o comprimento de onda: "))
print()
print("Escolha a unidade de medida :")
print("1 - [nm]")
print("2 - [µm]")
print("3 - [mm]")
print("4 - [m]")
print("5 - [km]")
opcao = int(input())
if opcao == 1:
comprimento = comprimento *(10**-9)
print(comprimento)
elif opcao == 2:
comprimento = comprimento *(10**-6)
print(comprimento)
elif opcao == 3:
comprimento = comprimento *(10**-3)
print(comprimento)
elif opcao == 4:
print(comprimento)
elif opcao == 5:
comprimento = comprimento *(10**3)
print(comprimento)
frequencia = comprimento / c
k = (2*pi) / comprimento
w = (2*pi) * c
print("A frequência é igual a: %.3f\n" % frequencia)
print("O número de ondas é igual a: %.3f\n" % k)
print("A frequência angular é igual a: %.3f\n" % w)
def main():
while True:
print("1 - Usar o comprimento de onda")
print("2 - Usar a frequência")
print("0 - Encerrar o programa")
x = int(input())
if x == 1:
comprimento_de_onda()
if x == 2:
funcao2()
if x == 0:
break
main()
|
0b73ac0d84e3b042e6935bc0a260ac5f2fdadda5 | LucasBalbinoSS/Exercicios-Python | /ExerciciosPython/ex007.py | 214 | 3.625 | 4 | n1 = float(input('\033[1;35mDigite a primeira nota: \033[m'))
n2 = float(input('\033[36mDigite a segunda nota: \033[m'))
m = (n1 + n2) / 2
print('\033[1;32mA média entre %.1f e %.1f é %.1f\033[m' % (n1, n2, m))
|
dbc279675b878be174c11f6f1a4187b3edb92d10 | cdgus1514/ML | /KERAS/RNN/keras13_lstm_earlystoping.py | 1,555 | 3.78125 | 4 | from numpy import array
from keras.models import Sequential
from keras.layers import Dense, LSTM
import random
random.seed(1377)
# 1. 데이터
x = array([[1,2,3], [2,3,4], [3,4,5], [4,5,6], [5,6,7], [6,7,8], [7,8,9], [8,9,10], [9,10,11], [10,11,12], [20,30,40], [30,40,50], [40,50,60]])
y = array([4,5,6,7,8,9,10,11,12,13,50,60,70])
print("x.shape : ", x.shape)
print("y.shape : ", y.shape)
# LSTM >> 몇개씩 잘라서 작업 할 것인지
x = x.reshape((x.shape[0], x.shape[1], 1))
print("reshape x.shape : ", x.shape)
# 2. 모델구성
model = Sequential()
model.add(LSTM(10, activation="relu", input_shape=(3,1))) # 컬럼개수, 사용할 개수 >> ((n,3), 1)
model.add(Dense(100))
model.add(Dense(100))
model.add(Dense(100))
model.add(Dense(100))
model.add(Dense(100))
model.add(Dense(100))
model.add(Dense(100))
model.add(Dense(100))
model.add(Dense(100))
model.add(Dense(100))
model.add(Dense(100))
model.add(Dense(100))
model.add(Dense(100))
model.add(Dense(100))
model.add(Dense(100))
model.add(Dense(100))
model.add(Dense(1))
# model.summary()
# 3. 실행
model.compile(optimizer="adam", loss="mse")
## earlystopping >> epochs 제한 필요없음
## monitor 옵션 >> patience 개수만큼 변화 없을 시 학습정지
from keras.callbacks import EarlyStopping
early_stopping = EarlyStopping(monitor="loss", patience=30, mode="auto")
hist = model.fit(x, y, epochs=10000, verbose=1, callbacks=[early_stopping])
x_input = array([25,35,45])
x_input = x_input.reshape(1,3,1)
yhat = model.predict(x_input, verbose=2)
print(yhat)
|
fa927dd339642ef1ec3ae19bda1e9fe1ab5247ed | iaksit/MIN545 | /Lecture1/sandbox.py | 703 | 3.765625 | 4 | # Our first sandbox
# The following counts as a comment
'''x = 0
# a_flag = True
if x is 1:
if a_flag:
print('something')
y = 4
else:
print('something else')
y = 0'''
total = 0
x = None
while x != 0:
x = int(input("Enter a number"))
total += x
print('Total: {0}'.format(total))
mylist = [1.1, 2.3, 5, 4.2, 8, -1.3, 2]
minimum = float('inf')
for fred in mylist:
if fred < minimum:
minimum = fred
print('Minimum: {0}'.format(minimum))
def hello(name, times):
print('hello {0} '.format(name) * times)
return times
def contains(data, target):
for item in data:
if item == target:
return True
return False
|
97dee83e425479b4b3dbc75a300c627b2f6c5c02 | soumyakuruvila/hw3-fa17-student | /hw3.py | 5,646 | 4.125 | 4 | ##################################
# #
# Homework 3 #
# Released: September 26, 2017 #
# Due: October 10, 2017 #
# #
##################################
# Matrix Transpose
#
# Description:
# Given an m x n matrix A, return A^T, that is,
# return the transpose of the matrix A.
#
# Example(s):
#
# Example 1:
# Input:
# A = [[1]]
# Output:
# [[1]]
#
# Example 2:
# Input:
# A = [[1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]]
# Output:
# [[1, 4, 7],
# [2, 5, 8],
# [3, 6, 9]]
#
def matrix_transpose(A):
return [[ A[row][col]
for row in range(0,len(A)) ]
for col in range(0,len(A[0])) ]
# Max Element in 2-D Array
#
# Description:
# Given a 2-d array grid of integers,
# determine the maximum number in grid.
#
# Example(s):
# Example 1:
# Input:
# grid = [[4, 2],
# [3, -1]]
# Output:
# 4
#
# Example 2:
# Input:
# grid = [[-300, -200],
# [-300, -100]]
# Output:
# -100
#
def max_2d_array(grid):
c = -float("inf")
for a in range(len(grid)):
for b in range (len(grid[0])):
if grid[a][b] > c:
c = grid[a][b]
return c
# Binary Search
#
# Description:
# Given a sorted (increasing) array with distinct integers and a
# target integer, determine the index of target in the given array.
# If target is not in the array, return None. Try to use the fact
# that the array is sorted to optimize your algorithm.
#
# Example(s):
#
# Example 1:
# Input:
# arr = [1, 2, 3, 4, 5]
# target = 3
# Output:
# 2
#
# Example 2:
# Input:
# arr = [1, 2, 3, 4, 5]
# target = 0
# Output:
# None
#
def binary_search(arr, target):
for i in range (len(arr)):
if arr[i] == target:
return i
elif arr[i] > target:
return None
return None
# Sorted Matrix Search
#
# Description:
# Given a square 2d array of integers and a target integer
# return the coordinates of the target integer as a tuple
# in the form (row, col) if the element exists in the matrix,
# or None if the element does not exists. The 2d array
# is guaranteed to be sorted ascending row-wise,
# and the zeroth element of each row is strictly larger than
# the last element of the previous row.
#
# Example(s):
# Example 1:
# Input:
# arr = [[1 , 2 , 3],
# [8 , 11, 16],
# [23, 24, 25]]
# target = 8
# Output:
# (1, 0)
#
# Example 2:
# Input:
# arr = [[1 , 2 , 3],
# [8 , 11, 16],
# [23, 24, 25]]
# target = 20
# Output:
# None
#
def search_2d_array(arr, target):
for a in range(len(arr)):
for b in range (len(arr[a])):
if arr[a][b] > target:
return None
elif arr[a][b] == target:
return [a, b]
return None
# Maximum Sum Subarray
#
# Description:
# Given an array of integers, determine the maximum sum of
# a continuous subarray of the given array.
#
# Examples(s):
# Example 1:
# Input:
# arr = [1, 2, 3, 4, 5]
# Ouput:
# 15
#
# Example 2:
# Input:
# arr = [1, -3, 4, 1, -2, 3]
# Output:
# 6
#
def max_sum_subarray(arr):
max = -float("inf")
for a in range (0, len(arr)):
temp = 0
for b in range (a, len(arr)):
temp = temp + arr[b]
if (temp > max):
max = temp
return max
# Maximum Sum Sub-Rectangle
#
# Description:
# Given a 2-d array of integers, determine the
# maximum sub-rectangle sum.
#
# Example(s):
# Example 1:
# Input:
# grid = [[1, 2],
# [3, 4]]
# Output:
# 10
#
# Example 2:
# Input:
# grid = [[1, 2],
# [-3, 0]]
# Ouput:
# 3
#
# Example 3:
# Input:
# grid = [[ 1, -2, 0],
# [-1, 3, 0],
# [ 3, -1, -9]]
# Output:
# 4
#
def max_sum_subrectangle(grid):
max = -float("inf")
for col in range(0, len(grid)):
temp = 0
for row in range(0, len(grid[col])):
for amount in range(0, len(grid)):
temp = temp + max_sum_subarray(grid[amount])
if (temp > max):
max = temp
grid[col][row] = 0
temp = 0;
return max
# Maximum Number of Times an Array can be Flattened
#
# Description:
# Given an array of integers and arrays,
# return the maximum number of times arr can be flattened.
# For example, if arr = [1, 2, [3, 4], 5],
# then arr could be flattened once.
#
# Example(s):
# Example 1:
# Input:
# arr = [1, 2, [3, 4], 5]
# Output:
# 1
#
# Example 2:
# Input:
# arr = [1, 2, 3, 4, 5]
# Output:
# 0
#
def max_array_flatten(arr):
maxi = 0
for i in range (0, len(arr)):
if (isinstance(arr[i], list)):
maxi = maxi + 1
return maxi
|
addd917c0f34b65d4e7fa27f082f3cbe61e90550 | FernandoUrr/PythonProjects | /Learning_Python/learning_python_part1.py | 1,309 | 3.53125 | 4 | #Soluciones de todos los ejercicios en el apéndice D
"""Algoritmo para realizar descenso
del gradiente"""
from matplotlib import cm
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots(subplot_kw = {"projection":"3d"})
#Ahora, definir la función de costos
def f(x, y):
return x**2 + 3*y**2 + 2*x + y
res = 1000
#Se generan los vectores que darán valores a x y y
x = np.linspace(-4, 4, res)
y = np.linspace(-4, 4, res)
x, y = np.meshgrid(x, y)
z = f(x, y)
#Ahora hacer las curvas de nivel
surf = ax.plot_surface(x, y, z, cmap = cm.cool)
fig.colorbar(surf)
level_map = np.linspace(np.min(z), np.max(z), num = res)
plt.contourf(x, y, z, level_map)
plt.title("Descenso del gradiente")
#Seleccionar punto aleatorio entre 0 y 1
p = np.random.rand(2)* 8 - 4
plt.plot(p[0], p[1], "o", c = "k")
h = 0.001
lr = 0.001
def derivada (cp , p):
return (f(cp[0], cp[1]) - f(p[0], p[1]))/h
#Se usa definición de límites de la derivada
def gradiente(p):
grad = np.zeros(2)
for i, val in enumerate(p):
cp = np.copy(p)
cp[i] = cp[i] + h
dp = derivada(cp, p)
grad[i] = dp
return grad
for i in range(1000):
p = p - lr*gradiente(p)
if i%10 == 0:
plt.plot(p[0], p[1], "o", c = "r")
plt.plot(p[0], p[1], "o", c = "w")
|
bb8be50feabc3ec84af6e123870afea927bed763 | shuvamoy1983/Machine-learning-Tutorial | /ReadDataAndTrasformBadvalues.py | 1,077 | 4.0625 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Import the dataset
dataset= pd.read_csv("/Users/shuvamoymondal/Desktop/Machine_Learning_Folder/Part_1_Data_Preprocessing/Data.csv")
## get indipendent variable columms which is also called Features.Means a property of your training data.
##If you put .values, it will convert colum to array format
X = dataset.iloc[: ,:-1].values
X
##get my Dependent column
y= dataset.iloc[:,3].values
##Next to Observe any missing data Nan, replcae it with values. For that, we need Imputer class of skitlearn.
## We will use sklearn.preprocessing import Imputer,axis=0 means , it will look for value of columns for NaN
from sklearn.preprocessing import Imputer
imputer= Imputer(missing_values='NaN', strategy='mean',axis=0)
## fit method is used to best match the curvature of given data points compute the closest match and transform is used to
## transform your data. We can use fit and transform separately or we can use fit_transform.
##imputer.fit(X[:,1:3])
X[:,1:3]=imputer.fit_transform(X[:,1:3])
X[:,1:3]
|
cfcb5442c08d6db17519024ff06f2d9426e8ab05 | fengrenxiaoli/Mypython | /罚球.py | 319 | 3.828125 | 4 | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
from random import choice
print( 'Choose one side to shoot:')
print('left,center,right')
you=input()
print('You kicked '+you)
direction=['left','center','right']
com=choice(direction)
print('Computer saved '+com)
if you!=com:
print('Goal!')
else:
print('Oops...')
|
6a8db65ede2ee897ed5584d40b877a35e58d826b | davidbliu/coding-interview | /arrays/graph_practice.py | 671 | 3.75 | 4 | import Queue
g={1: [2, 3,6], 2: [4, 5], 3: [6, 7],4:[8,9,13]}
def bfs_levels(graph):
keys = graph.keys()
search_queue = Queue.Queue()
for key in keys:
search_queue.put(key)
visited = set()
level_queue = Queue.Queue()
while not search_queue.empty():
curr = search_queue.get()
if curr not in visited:
print curr
visited.add(curr)
if curr in graph.keys():
childs = graph[curr]
for node in childs:
if node not in visited:
level_queue.put(node)
if search_queue.empty():
search_queue = level_queue
level_queue = Queue.Queue()
print '***'
print 'hi'
# return minimum spanning tree (set of edges)
def mst():
pass
bfs_levels(g) |
add1d802aa3a88bf3138013e3a6f9342ccc02899 | beauthi/contests | /training/leetcode/hard/sudoku-solver.py | 2,760 | 3.65625 | 4 | class Solution:
def print(self, board: list) -> None:
for line in board:
for elt in line:
print(elt, end=" ")
print("")
print("-" * 17)
def isValid(self, board) -> bool:
for index_line in range(3):
for index_col in range(3):
block = [l[index_col * 3 : index_col * 3 + 3] for l in board[index_line * 3 : index_line * 3 + 3]]
if "." in block:
return False
for i in range(9):
if not any(str(i + 1) in l for l in block):
return False
for line in board:
if "." in line:
return False
for i in range(9):
if str(i + 1) not in line:
return False
for col in range(9):
c = [l[col] for l in board]
if "." in c:
return False
for i in range(9):
if str(i + 1) not in c:
return False
return True
def solve(self, board):
for x in range(9):
for y in range(9):
if board[x][y] != ".":
continue
block = [l[int(y / 3) * 3 : int(y / 3) * 3 + 3] for l in board[int(x / 3) * 3 : int(x / 3) * 3 + 3]]
line = board[x]
col = [l[y] for l in board]
found = False
for i in range(9):
if any(str(i + 1) in l for l in block) or str(i + 1) in line or str(i + 1) in col:
continue
board[x][y] = str(i + 1)
if not self.solve(board):
board[x][y] = "."
else:
found = True
break
if not found:
return False
return self.isValid(board)
def solveSudoku(self, board: list) -> None:
self.solve(board)
s = Solution()
s.solveSudoku([["5","3",".",".","7",".",".",".","."],["6",".",".","1","9","5",".",".","."],[".","9","8",".",".",".",".","6","."],["8",".",".",".","6",".",".",".","3"],["4",".",".","8",".","3",".",".","1"],["7",".",".",".","2",".",".",".","6"],[".","6",".",".",".",".","2","8","."],[".",".",".","4","1","9",".",".","5"],[".",".",".",".","8",".",".","7","9"]])
s.solveSudoku([[".",".","9","7","4","8",".",".","."],["7",".",".",".",".",".",".",".","."],[".","2",".","1",".","9",".",".","."],[".",".","7",".",".",".","2","4","."],[".","6","4",".","1",".","5","9","."],[".","9","8",".",".",".","3",".","."],[".",".",".","8",".","3",".","2","."],[".",".",".",".",".",".",".",".","6"],[".",".",".","2","7","5","9",".","."]]) |
56b359ae656320ee58f69ee57e98113fea3d9fa9 | JanKesek/wordpress-themes-scraper | /filereader.py | 538 | 3.703125 | 4 | from os import listdir, remove
from os.path import isfile, join
class Reader:
def __init__(self, path):
self.path=path
def getFiles(self):
return [f for f in listdir(self.path) if isfile(join(self.path,f))]
def getFileText(self,filename):
f=open("testDir/"+filename, "r", encoding = "ISO-8859-1")
return f.read()
def deleteFile(self, filename):
remove(self.path+"/"+filename)
def writeToFile(self, filename, text):
f=open("testDir/"+filename, "w")
f.write(text)
|
15e62cb90b17264e05e64ca8dde06d0a1a03f2e6 | huyngopt1994/python-Algorithm | /green/green-08-sort/bai_5_sort_odd_even.py | 995 | 4.25 | 4 | number = int(input())
numbers = list(map(int, input().split()))
def is_odd(number):
# check so le
if number % 2 != 0:
return True
else:
return False
def bubble_sort(numbers):
for i in range(len(numbers) - 1):
if is_odd(numbers[i]):
i_odd = True
else:
i_odd = False
for j in range(i+1, len(numbers)):
if i_odd:
# handle odd number
# Descending
if is_odd(numbers[j]):
# swap them
if numbers[i] < numbers[j]:
numbers[i], numbers[j] = numbers[j], numbers[i]
else:
if not is_odd(numbers[j]):
# ascending
if numbers[i] > numbers[j]:
numbers[i], numbers[j] = numbers[j], numbers[i]
return numbers
numbers = bubble_sort(numbers)
numbers_string = ' '.join(map(str,numbers))
print(numbers_string)
|
660e66c853f635cc5b8866c78e5016cd0d9428c2 | RodrigoNeto/cursopythonyt | /aula5/aula5.py | 643 | 4.34375 | 4 | """
+, *, /, //, **, %, ()
"""
print('Multiplicação *', 10 * 10)
print('Repetição de String *', 10 * 'Rodrigo ')
print('Adição +', 10 + 10)
print('Subtração -', 10 - 10)
print('Divisão /', 10 / 10)
print('Divisão sem sobra //', 25 // 10 )
print('Potenciação **', 2 ** 2 )
print('Módulo/Resto da divisão %', 25 % 10)
idade = 30
#Não é recomendado formatar dessa forma
print('Eu tenho ' + str(idade) + ' anos de idade!') # Fazendo casting na idade convertendo para string
print('Alteração de prescedência das operações ()', 5+2*10)
print('Alteração de prescedência das operações ()', (5+2)*10)
|
7e4aa477f8b80e90a4c88cc8de184d476d39c7d7 | Ivaylo-Atanasov93/The-Learning-Process | /Programming Fundamentals/Lists_Advanced-LAB/The Office.py | 567 | 4.0625 | 4 | string = input().split()
happiness_factor = int(input())
all_employees_happiness = [int(employee) for employee in string]
employees = list(map(lambda x: int(x) * happiness_factor, all_employees_happiness))
greater_happiness_employees = list(filter(lambda x: x >= sum(employees) / len(employees), employees))
if len(greater_happiness_employees) >= len(employees) / 2:
print(f'Score: {len(greater_happiness_employees)}/{len(employees)}. Employees are happy!')
else:
print(f'Score: {len(greater_happiness_employees)}/{len(employees)}. Employees are not happy!') |
c23a76df72b2bdab314f764b289b507046f0cfa4 | dddbuji/hello | /python练习5.py | 167 | 3.78125 | 4 | s=input("请输入车辆行驶的距离: ")
s=eval(s)
t=input("请输入车辆行驶的时间: ")
t=eval(t)
v=s/t
print("车辆行驶的平均速度为{}". format(v))
|
b9a605797c84e14bceaacbb2fb706badef66c8f9 | xiaohaiguicc/CS5001 | /hw07_Chenxi_Cai/id.py | 820 | 3.8125 | 4 | """ Luhn's algorithm"""
class Idnumber:
"""identification numbers"""
def __init__(self, sequence):
"""constructor, sequence is a string"""
self.id_list_reverse = [int(item) for item in reversed(sequence)]
def judge(self):
"""overall procedure"""
self.double()
self.modulu()
def double(self):
"""double value and add them"""
for i in range(1, len(self.id_list_reverse), 2):
new_num = self.id_list_reverse[i] * 2
self.id_list_reverse[i] = new_num // 10 + new_num % 10
def modulu(self):
"""whether resulting sum is divisible by 10"""
result = sum(self.id_list_reverse)
if result % 10 == 0:
print("The sequence is valid")
else:
print("The sequence is not valid")
|
a8eda7bdfc4a951d0d2e01ca78e414a08519b004 | pedireddy/guvi_codekata | /p16.py | 525 | 3.609375 | 4 | def prime(a):
flag=0
for x in range(1,a+1):
if((a%x)==0):
flag=flag+1
return flag
def res(y,z):
list=[]
for x in range(y+1,z):
if(prime(x)==2):
list.append(x)
for x in range(len(list)):
print(list[x])
if(len(list)==0):
print("no primes")
m,n=[int(x) for x in input().split(",")]
if(m>n):
res(n,m)
elif(m<n):
res(m,n)
elif(m<0 and n<0):
print("no primes")
elif(m<0):
res(0,n)
elif(n<0):
res(m,o)
|
fbe465d4d41f20baa4ed15fb03e0e626e10ab6de | botaklolol/Kattis | /bet.py | 1,560 | 3.671875 | 4 | <<<<<<< HEAD
import sys
import math
def choose(a,b):
# a!/(b!(a-b)!)
return math.factorial(a)/(math.factorial(b)*math.factorial(a-b))
def main():
steps = int(sys.stdin.readline())
for i in range(steps):
line = sys.stdin.readline()
line = line.split()
R = int(line[0])
S = int(line[1])
X = int(line[2])
Y = int(line[3])
W = int(line[4])
p = float(S - R + 1)/S # probalibty of binomial success
total_p = 0.0
for i in range(X,Y+1):
curr_p = choose(Y,i)*math.pow(p,i)*math.pow((1-p),(Y-i))
total_p += curr_p
if (total_p*W > 1):
print "yes"
else:
print "no"
if __name__ == '__main__':
main()
=======
import sys
import math
def choose(a,b):
# a!/(b!(a-b)!)
return math.factorial(a)/(math.factorial(b)*math.factorial(a-b))
def main():
steps = int(sys.stdin.readline())
for i in range(steps):
line = sys.stdin.readline()
line = line.split()
R = int(line[0])
S = int(line[1])
X = int(line[2])
Y = int(line[3])
W = int(line[4])
p = float(S - R + 1)/S # probalibty of binomial success
total_p = 0.0
for i in range(X,Y+1):
curr_p = choose(Y,i)*math.pow(p,i)*math.pow((1-p),(Y-i))
total_p += curr_p
if (total_p*W > 1):
print "yes"
else:
print "no"
if __name__ == '__main__':
main()
>>>>>>> f177bf73e7319f758524fdec06543bad31a6230d
|
e9ea50bbf34ad4f74ae759b8211d060a385040d2 | jwstes/BlueLeg | /Receipt.py | 1,265 | 3.546875 | 4 | from datetime import datetime
class Receipt():
def __init__(self, items, customerID):
self.__items = items
self.__customerID = customerID
self.__date = self.generate_date()
self.__totalPrice = self.generate_totalPrice()
def generate_date(self):
y = datetime.now()
x = datetime(y.year, y.month, y.day, y.hour, y.minute, y.second)
return x
def generate_totalPrice(self):
keys = list(self.__items.keys())
totalPrice = 0
for key in keys:
totalPrice = totalPrice + float(self.__items[key][1])
return totalPrice
def get_date(self):
return self.__date
def get_items(self):
return self.__items
def get_totalPrice(self):
return self.__totalPrice
# def get_fullReceipt(self):
# keys = list(self.__items.keys())
# fullReceipt = "FULL RECEIPT:\n"
# for key in keys:
# fullReceipt += f"{key} - S${self.__items[key]}\n"
# fullReceipt += "-END OF RECEIPT-"
# return fullReceipt
def __str__(self):
return f"Receipt: {self.__date.day}-{self.__date.month}-{self.__date.year} Customer ID: ({self.__customerID}): {len(self.__items)} items bought." |
4114e92a5b31f15c5bac53be196bd184e22311eb | aeaziz/CQA-for-primary-keys-Datalog-Rewriter | /datalog.py | 6,347 | 3.515625 | 4 | # Represents an atom
class Atom:
def __init__(self, name):
self.name = name
self.content = []
self.is_key = []
self.is_variable = []
self.consistent = False
self.negative = False
# Returns the variables appearing in this atom
def get_variables(self):
res = []
for i in range(0, len(self.content)):
if self.is_variable[i]:
res.append(self.content[i])
return res
# Returns the constants appearing in this atom
def get_constants(self):
res = []
for i in range(0, len(self.content)):
if not self.is_variable[i]:
res.append(self.content[i])
return res
# Adds a variable
def add_variable(self, value, is_key):
self.content.append(value)
self.is_variable.append(True)
self.is_key.append(is_key)
# Adds a constant
def add_constant(self, value, is_key):
self.content.append(value)
self.is_variable.append(False)
self.is_key.append(is_key)
# The variable becomes a constant
def freeze_variable(self, f):
for var in self.content:
if var == f:
self.is_variable[self.content.index(var)] = False
# Sets if the relation is consistent or not
def set_consistent(self, value):
self.consistent = value
# Creates a copy of this atom
def copy(self):
new = Atom(self.name)
new.content = self.content[:]
new.is_key = self.is_key[:]
new.is_variable = self.is_variable[:]
new.consistent = self.consistent
new.negative = self.negative
return new
# Returns the key-values of this atom
def get_key_values(self):
key_values = []
for i in range(0, len(self.content)):
if self.is_key[i]:
key_values.append(self.content[i])
return key_values
# Returns the key-variables of this atom
def get_key_variables(self):
key_variables = []
for i in range(0, len(self.content)):
if self.is_key[i] and self.is_variable[i]:
key_variables.append(self.content[i])
return key_variables
# Returns the values of this atom that doesn't appear in the key
def get_not_key_values(self):
not_key_values = []
for i in range(0, len(self.content)):
if not self.is_key[i]:
not_key_values.append(self.content[i])
return not_key_values
# String representation when this atom is used as a Datalog Query head
def str_as_head(self):
prev = self.negative
self.negative = False
res = self.__str__()
self.negative = prev
return res
def __eq__(self, other):
return type(self) == type(other) and self.content == other.content and self.name == other.name
def __str__(self):
prefix = ""
if self.negative:
prefix = "not "
if len(self.content) == 0:
return prefix + self.name
res = self.name + '('
for c in self.content:
res = res + c + ", "
return prefix + res[:-2] + ")"
def __repr__(self):
return self.__str__()
# Represents an equality or inequality atom
class EqualityAtom:
def __init__(self, left, right, inequality=False):
self.left = left
self.right = right
self.inequality = inequality
def __str__(self):
if self.inequality:
sign = "!="
else:
sign = "="
return self.left + sign + self.right
def __repr__(self):
return self.__str__()
def __eq__(self, other):
return type(self) == type(other) and self.left == other.left and self.right == other.right
# Represents the min atom used in Datalog
class MinAtom:
def __init__(self, var1, atom, var2):
self.atom = atom
self.var1 = var1
self.var2 = var2
def __str__(self):
return "#min{" + self.var1 + " : " + str(self.atom) + "} = " + self.var2
def __repr__(self):
return self.__str__()
def __eq__(self, other):
return type(self) == type(other) and self.var1 == other.var1 and self.var2 == other.var2 and self.atom == other.atom
# Represents the body of a datalog query
class DatalogBody:
def __init__(self):
self.atoms = []
self.variables = set()
self.constants = set()
# Adds an atom
def add_atom(self, atom):
if atom not in self.atoms:
self.atoms.append(atom)
if type(atom) == Atom:
self.variables = self.variables.union(set(atom.get_variables()))
self.constants = self.constants.union(set(atom.get_constants()))
# Rebuilds the set of variables and constants
def rebuild_sets(self):
self.variables = set()
self.constants = set()
for atom in self.atoms:
self.variables = self.variables.union(set(atom.get_variables()))
self.constants = self.constants.union(set(atom.get_constants()))
# Removes an atom
def remove_atom(self, atom):
self.atoms.remove(atom)
self.rebuild_sets()
# Returns a copy of this body
def copy(self):
new = DatalogBody()
new.atoms = self.atoms.copy()
return new
# Retrieves an atom using his name
def get_atom(self, name):
for atom in self.atoms:
if atom.name == name:
return atom
# The variable becomes a constant
def freeze_variable(self, var):
if var in self.variables:
self.variables.remove(var)
self.constants.add(var)
for atom in self.atoms:
atom.freeze_variable(var)
def __str__(self):
return str(self.atoms).replace("[", "").replace("]", "")
def __repr__(self):
return self.__str__()
# Represents a datalog query
class DatalogQuery:
def __init__(self, name):
self.head = name
self.body = DatalogBody()
# Adds an atom to the body of the query
def add_atom(self, atom):
self.body.add_atom(atom)
def __str__(self):
return self.head.str_as_head() + " :- " + self.body.__str__() + "."
def __repr__(self):
return self.__str__()
|
1582799f95c52edf860ce2891d140747c62dc928 | nanersmariee/Labs_AnnaMarie | /oo-melons/melons.py | 1,826 | 4.03125 | 4 | """Classes for melon orders."""
from random import randint
from datetime import time
class AbstractMelonOrder():
def __init__(self, species, quantity, country_code='USA'):
"""instantiate a melon order"""
self.species = species
self.quantity = quantity
self.shipped = False
self.country_code = country_code
def get_base_price(self):
"""Calculate base price, based on Splurge pricing"""
base_price = randint(5, 9)
return base_price
def rush_hour_total(self):
"""Determine if order is placed between 8-11AM, M-F"""
get_time = datetime.d
def get_total(self):
"""Calculate price, including tax."""
base_price = self.get_base_price()
total = 0
if self.species == 'Christmas':
base_price *= 1.5
if self.order_type == 'international' and self.quantity < 10:
total += 3
total = (1 + self.tax) * self.quantity * base_price
return total
def mark_shipped(self):
"""Record the fact than an order has been shipped."""
self.shipped = True
def get_country_code(self):
"""Return the country code."""
return self.country_code
class DomesticMelonOrder(AbstractMelonOrder):
"""A melon order within the USA."""
order_type = "domestic"
country_code = "USA"
tax = 0.08
class InternationalMelonOrder(AbstractMelonOrder):
"""An international (non-US) melon order."""
order_type = "international"
tax = 0.17
class GovernmentMelonOrder(AbstractMelonOrder):
"""a melon order that is specific to government"""
order_type = "government"
tax = 0
passed_inspection = False
def mark_inspection(self, passed):
if passed:
self.passed_inspection = True
|
b9592d2db51ff82b78534e7b20ed262f63301dd1 | EricksonSiqueira/curso-em-video-python-3 | /Mundo 2 estruturas condicionais e de repeticoes/Aula 13 (for)/Desafio 047 (Contagem de pares).py | 254 | 3.75 | 4 | # Crie um programa que mostre na tela todos os números
# pares que estão no intervalo entre 1 e 50.
i = 0
print('-='*5 + 'Tabela de pares' + '-='*5)
for c in range(0, 51, 2):
if c > 0:
i += 1
print(f"Par[{i}] = {c}")
print('=-'*15)
|
64b69e62bf788c1770f48f508867b2020a19e976 | rishinkaku/Software-University---Software-Engineering | /Python_Advanced/Comprehensions/Heroes Inventory/Heroes Inventory.py | 662 | 3.8125 | 4 | def inventory_(heroes):
inventory = {}
for hero in heroes:
if hero not in inventory:
inventory[hero] = {}
command = input()
while command != 'End':
data = command.split('-')
name = data[0]
item = data[1]
cost = int(data[2])
if name in inventory:
if item not in inventory[name]:
inventory[name][item] = cost
command = input()
return inventory
def print_inventory(heroes):
print(*[f"{name} -> Items: {len(stats)}, Cost: {sum(stats.values())}" for name, stats in heroes.items()], sep='\n')
print_inventory(inventory_(input().split(', ')))
|
41e900d23662969b42fc6e0849bce6589cb1daa0 | paulnicholsen27/Euler | /42 - Coded Triangle Numbers.py | 1,441 | 4.09375 | 4 | '''The nth term of the sequence of triangle numbers is given by, tn = n(n+1) / 2;
so the first ten triangle numbers are:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
By converting each letter in a word to a number corresponding to its alphabetical
position and adding these values we form a word value. For example, the word value
for SKY is 19 + 11 + 25 = 55 = t10. If the word value is a triangle number then we
shall call the word a triangle word.
Using words.txt (right click and 'Save Link/Target As...'), a 16K text file containing
nearly two-thousand common English words, how many are triangle words?'''
import string
from eulertools import letter_scores, get_max_value, triangle_number_list
def make_wordlist(file):
wordlist = []
g = open(file)
for word in g:
unstripped_words = word.split(",")
for word in unstripped_words:
wordlist.append(word[1:-1])
return wordlist
wordlist = make_wordlist('words.txt')
letter_scores = letter_scores()
def get_word_scores(wordlist):
word_scores = {}
for word in wordlist:
score = 0
for letter in word:
score += letter_scores[letter]
word_scores[word] = score
return word_scores
word_scores = get_word_scores(wordlist)
max_word_score = get_max_value(word_scores)[1]
triangle_numbers = triangle_number_list(max_word_score)
triangle_words = []
for word in word_scores:
if word_scores[word] in triangle_numbers:
triangle_words.append(word)
print len(triangle_words) |
eacf357f2a20b1f627104712611144069f116683 | ruoqlng/RobotTeamProject | /libs/robot_controller.py | 9,080 | 3.640625 | 4 | """
Library of EV3 robot functions that are useful in many different applications. For example things
like arm_up, arm_down, driving around, or doing things with the Pixy camera.
Add commands as needed to support the features you'd like to implement. For organizational
purposes try to only write methods into this library that are NOT specific to one tasks, but
rather methods that would be useful regardless of the activity. For example, don't make
a connection to the remote control that sends the arm up if the ir remote control up button
is pressed. That's a specific input --> output task. Maybe some other task would want to use
the IR remote up button for something different. Instead just make a method called arm_up that
could be called. That way it's a generic action that could be used in any task.
"""
import ev3dev.ev3 as ev3
import math
import time
import traceback
class Snatch3r(object):
"""Commands for the Snatch3r robot that might be useful in many different programs."""
# Done: Implement the Snatch3r class as needed when working the sandox exercises
# (and delete these comments)
def __init__(self):
self.left_motor = ev3.LargeMotor(ev3.OUTPUT_B)
self.right_motor = ev3.LargeMotor(ev3.OUTPUT_C)
self.arm_motor = ev3.MediumMotor(ev3.OUTPUT_A)
self.touch_sensor = ev3.TouchSensor()
self.color_sensor = ev3.ColorSensor()
self.ir_sensor = ev3.InfraredSensor()
self.beacon_seeker = ev3.BeaconSeeker(channel=1)
self.pixy = ev3.Sensor(driver_name="pixy-lego")
assert self.pixy
assert self.left_motor.connected
assert self.right_motor.connected
assert self.arm_motor.connected
assert self.touch_sensor.connected
assert self.color_sensor.connected
assert self.ir_sensor.connected
assert self.pixy
def forward(self,left_speed,right_speed):
self.left_motor.run_forever(speed_sp=left_speed)
self.right_motor.run_forever(speed_sp=right_speed)
def back(self,left_speed,right_speed):
self.left_motor.run_forever(speed_sp=-left_speed)
self.right_motor.run_forever(speed_sp=-right_speed)
def stop(self):
self.left_motor.stop(stop_action='brake')
self.right_motor.stop(stop_action='brake')
def left(self,left_speed,right_speed):
self.left_motor.run_forever(speed_sp=-left_speed)
self.right_motor.run_forever(speed_sp=right_speed)
def right(self,left_speed,right_speed):
self.left_motor.run_forever(speed_sp=left_speed)
self.right_motor.run_forever(speed_sp=-right_speed)
def arm_calibration(self):
self.arm_motor.run_forever(speed_sp=900)
while not self.touch_sensor.is_pressed:
time.sleep(0.01)
self.arm_motor.stop(stop_action="brake")
ev3.Sound.beep().wait()
arm_revolutions_for_full_range = 14.2 * 360
self.arm_motor.run_to_rel_pos(position_sp=-arm_revolutions_for_full_range, speed_sp=900,
stop_action=ev3.Motor.STOP_ACTION_BRAKE)
self.arm_motor.wait_while(ev3.Motor.STATE_RUNNING)
ev3.Sound.beep().wait()
self.arm_motor.position = 0
def arm_up(self):
self.arm_motor.run_forever(speed_sp=900)
while True:
time.sleep(0.01)
if self.touch_sensor.is_pressed == 1:
break
self.arm_motor.stop(stop_action='brake')
ev3.Sound.beep()
def arm_down(self):
self.arm_motor.run_to_abs_pos(position_sp=0, speed_sp=900)
self.arm_motor.wait_while(ev3.Motor.STATE_RUNNING)
ev3.Sound.beep()
def loop_forever(self):
# This is a convenience method that I don't really recommend for most programs other than m5.
# This method is only useful if the only input to the robot is coming via mqtt.
# MQTT messages will still call methods, but no other input or output happens.
# This method is given here since the concept might be confusing.
self.running = True
while self.running:
time.sleep(0.1) # Do nothing (except receive MQTT messages) until an MQTT message calls shutdown.
def shutdown(self):
# Modify a variable that will allow the loop_forever method to end. Additionally stop motors and set LEDs green.
# The most important part of this method is given here, but you should add a bit more to stop motors, etc.
self.left_motor.stop(stop_action='brake')
self.right_motor.stop(stop_action='brake')
self.arm_motor.stop(stop_action='brake')
self.running = False
ev3.Leds.set_color(ev3.Leds.LEFT, ev3.Leds.GREEN)
ev3.Leds.set_color(ev3.Leds.RIGHT, ev3.Leds.GREEN)
print("Goodbye!")
ev3.Sound.speak("Goodbye").wait()
def drive_inches(self,inches_target, speed_deg_per_second):
position = inches_target*90
self.left_motor.run_to_rel_pos(position_sp=position, speed_sp=speed_deg_per_second,stop_action='brake')
self.right_motor.run_to_rel_pos(position_sp=position, speed_sp=speed_deg_per_second,stop_action='brake')
self.left_motor.wait_while(ev3.Motor.STATE_RUNNING)
self.right_motor.wait_while(ev3.Motor.STATE_RUNNING)
def turn_degrees(self, degrees_to_turn, turn_speed_sp):
assert self.left_motor.connected
assert self.right_motor.connected
self.left_motor.run_to_rel_pos(position_sp=degrees_to_turn * 470 / 90,speed_sp=turn_speed_sp,stop_action='brake')
self.right_motor.run_to_rel_pos(position_sp=-degrees_to_turn * 470 / 90,speed_sp=turn_speed_sp,stop_action='brake')
self.left_motor.wait_while(ev3.Motor.STATE_RUNNING)
self.right_motor.wait_while(ev3.Motor.STATE_RUNNING)
def seek_beacon(self):
forward_speed = 300
turn_speed = 100
while not self.touch_sensor.is_pressed:
current_heading = self.beacon_seeker.heading # use the beacon_seeker heading
current_distance = self.beacon_seeker.distance # use the beacon_seeker distance
if current_distance == -128:
# If the IR Remote is not found just sit idle for this program until it is moved.
print("IR Remote not found. Distance is -128")
self.stop()
else:
if math.fabs(current_heading) < 2:
print("On the right heading. Distance: ", current_distance)
if current_distance == 0:
print("You have found the beacon!")
self.stop()
time.sleep(0.01)
return True
if current_distance > 0:
print("Drive forward")
self.forward(forward_speed, forward_speed)
if 10 > math.fabs(current_heading) >= 2:
print("Adjusting heading: ", current_heading)
if current_heading < 0:
print("Spin left")
self.left(turn_speed, turn_speed)
if current_heading > 0:
print("Spin right")
self.right(turn_speed, turn_speed)
if math.fabs(current_heading) > 10:
print("Heading is too far off to fix", current_heading)
self.stop()
time.sleep(0.01)
time.sleep(0.2)
print("Abandon ship!")
self.stop()
return False
def jellyfish(self,speed):
ev3.Sound.speak('Let Us Get Jellyfish Patrick').wait()
turn_speed = speed
while not self.touch_sensor.is_pressed:
print("value1: X", self.pixy.value(1))
print("value2: Y", self.pixy.value(2))
self.forward(speed,speed)
if self.pixy.value(3) > 0:
self.turn_degrees(90,turn_speed)
time.sleep(1)
ev3.Sound.beep().wait()
time.sleep(0.25)
ev3.Sound.speak("Jellyfish pickup").wait()
#####################################################
# There are no TODOs in this code.
# Your only edits will be in the Snatch3r class.
#####################################################
try:
while True:
while True:
found_beacon = self.seek_beacon()
if found_beacon:
break
if found_beacon:
ev3.Sound.speak("I got the Jellyfish")
self.arm_up()
time.sleep(1)
self.arm_down()
command = input("Hit enter to seek the Jellyfish again or enter q to quit: ")
if command == "q":
break
except:
traceback.print_exc()
ev3.Sound.speak("Error")
print("Goodbye!")
ev3.Sound.speak("Goodbye").wait()
|
c15339f777a3490c42cfff9b9c5c81775a608710 | wuhaiwqy/MachineLearningPractice | /byhand/01_LinearRegression.py | 2,277 | 3.859375 | 4 | import numpy as np
'''
线性回归模型类
'''
class LinearRegression:
def __init__(self, theta = None):
self.theta = theta
'''
功能:模型训练
输入:
data_x:二维数组,每一行是一条训练数据
data_label:训练数据对应的值
learning_rate:学习率
'''
def train(self, data_x, data_label, learning_rate = 0.001):
if data_x.shape[0] <= 0:
raise Exception('缺少训练数据!')
if data_x.shape[0] != data_label.shape[0]:
raise Exception('训练数据与标签不一致')
# 训练数据添加x0=1项
ones = np.ones(shape=(data_x.shape[0], 1))
x = np.hstack((ones, data_x))
# 初始化参数
self.theta = np.ones(shape=(x.shape[1]))
# 迭代,批梯度下降
new_theta = np.zeros(shape=(x.shape[1]))
while(self.__distance(self.theta, new_theta) > 0.0001):
self.theta = new_theta.copy()
for j in range(self.theta.shape[0]):
new_theta[j] = self.theta[j] - learning_rate * np.sum(np.dot(self.predict(data_x) - data_label, x[:,j]))
'''
功能:预测
输入:
data_x:二维数组,每一行是一条新样本
输出:
预测结果,一维数组,对应data_x的每一条样本的预测值
'''
def predict(self, data_x):
# 数据添加x0=1项
ones = np.ones(shape=(data_x.shape[0], 1))
x = np.hstack((ones, data_x))
return np.dot(x, self.theta)
'''
功能:计算两点之间的几何距离
输入:
a、b:两个向量
'''
def __distance(self, a, b):
return np.sqrt(np.sum((b - a) * (b - a)))
# 模型预测
def demo01():
theta = np.array([1, 2, 3])
model = LinearRegression(theta)
result = model.predict(np.array([[2, 2], [3, 2]]))
print(result)
# 模型训练
def demo02():
data_x = np.array([[1, 2], [3, 3], [4, 2]])
data_label = np.array([9, 16, 15])
model = LinearRegression()
model.train(data_x, data_label, 0.001)
print(model.theta)
print(model.predict(data_x))
if __name__ == '__main__':
demo01()
demo02()
|
78028cd48cd0c7430e9781856c94d93046b195fa | robynfsj/cfg-python-project | /explore.py | 2,945 | 3.828125 | 4 | import manipulate
import statistics
import matplotlib.pyplot as plt
# Print number of night's sleep contained in spreadsheet.
def num_nights():
data = manipulate.duration_in_secs()
print("The spreadsheet contains sleep data for {} nights."
.format(len(data)))
# Print the duration of the longest night's sleep
def longest_sleep():
data = manipulate.duration_in_secs()
longest = max(data)
# Convert seconds to hours and minutes.
hours = int((longest % 86400) / 3600)
minutes = int((longest % 3600 % 3600) / 60)
print("The longest recorded sleep is {} hours and {} minutes long."
.format(hours, minutes))
if hours > 12:
print("WOW! That was an awfully long sleep!")
elif hours < 8:
print("That's not very long for your longest night's sleep!\n"
"You don't value your sleep very much do you!")
else:
print("That's quite sensible for your longest night's sleep.")
# Print average (mean) sleep duration.
def mean_sleep():
data = manipulate.duration_in_secs()
mean = statistics.mean(data)
# Convert seconds to hours and minutes.
hours = int((mean % 86400) / 3600)
minutes = int((mean % 3600 % 3600) / 60)
print("The average nightly sleep is {} hours and {} minutes."
.format(hours, minutes))
if hours > 10:
print("WOW! You sleep an awful lot!")
elif hours < 6:
print("Uh oh! You really need to get some more sleep!")
else:
print("You sleep a sensible amount of time.")
# Plot sleep duration for each night.
def plot_duration():
duration = manipulate.duration_in_secs()
# Plot axes and duration data.
fig, ax = plt.subplots(figsize=(12, 5))
plt.plot(duration, color="salmon")
# Customise plot.
ax.set_title("Sleep duration for each night", color="teal")
ax.set_xlabel("Night", color="teal")
ax.set_ylabel("Sleep duration (seconds)", color="teal")
ax.spines["left"].set_color("teal")
ax.spines["bottom"].set_color("teal")
ax.tick_params(colors="teal")
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.show()
# Plot sleep duration for each night and save the plot to the plots folder with
# a file name inputted by the user.
def save_plot():
plot_name = input("Save as: ")
duration = manipulate.duration_in_secs()
# Plot axes and duration data.
fig, ax = plt.subplots(figsize=(10, 5))
plt.plot(duration, color="salmon")
# Customise plot.
ax.set_title("Sleep duration for each night", color="teal")
ax.set_xlabel("Night", color="teal")
ax.set_ylabel("Sleep duration (seconds)", color="teal")
ax.spines["left"].set_color("teal")
ax.spines["bottom"].set_color("teal")
ax.tick_params(colors="teal")
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
plt.savefig("./plots/" + plot_name + ".png")
|
1f29a341d848c42e557c1610b4d4db1a6d82f137 | reachtomrinal/PythonCoding | /app/CreatingVeriable.py | 763 | 3.984375 | 4 | # Section 1.2: Creating variables and assigning values
# Integer
a = 2
print(a)
# Output: 2
# Integer
b = 9223372036854775807
print(b)
# Output: 9223372036854775807
# Floating point
pi = 3.14
print(pi)
# Output: 3.14
# String
c = 'A'
print(c)
# Output: A
# String
name = 'John Doe'
print(name)
# Output: John Doe
# Boolean
q = True
print(q)
# Output: True
# Empty value or null data type
x = None
print(x)
# Output: None
# list of keywords
import keyword
print(keyword.kwlist)
q = True
print(type(q))
# Output: <type 'bool'>
x = None
print(type(x))
# Output: <type 'NoneType'>
s = """w'o"w"""
print(repr(s))
print(str(s))
print(f"repr func value {eval(repr(s)) == s}") # Output: True
print(f" str func value {eval(str(s)) == s}") # Gives a SyntaxError
|
b8ddbcd866ba11738546c0ec5ec7c71f24479205 | sukritgoyal/pythonFiles | /Python/simpletest.py | 335 | 3.75 | 4 | n = int(input())
i = 0
emps = []
while i < n:
emps.append(input())
i+=1
empsChar = []
for emp in emps:
empChar = []
for letter in emp:
empChar.append(letter)
empsChar.append(empChar)
for chars in empsChar:
if chars != sorted(chars):
print("YES")
else:
print("NO")
|
6da0227b0b44d97ecbd4fe95b2acdf0f4c1562b2 | jyotichauhan20/function_question | /revarse.py | 169 | 3.828125 | 4 | def rev(string):
rev=0
rev=len(string)-1
while rev>=0:
print(string[rev])
rev=rev-1
string=input("enter the input=")
rev(string)
|
c832286dbfeed2faa1ec0a5f8f73aca4e2e1b472 | louispan123/COMP10001-Project-1 | /Part 4.py | 3,811 | 3.921875 | 4 | #Sampling of habitats
'''
Write a function optimise_study() that evaluates the effect that consecutive visits and unseen species thresholds have on the accuracy of diversity estimates. The function takes three parameters:
sample_data is a list of lists of data collected over the course of multiple sampling visits; each item in the main list is a list of species that were observed on that visit;
unseen_species (an int) is the minimum number of previously unseen species that must be observed before a visit is deemed productive; and
consecutive_visits (an int) is the number of consecutive unproductive visits, after the initial visit, that must occur to trigger the stopping rule.
The functon should return a tuple containing:
the number of visits that will occur before the study has stopped; and
the proportion of the total bird species observed by the study at that point, compared to if all sampling visits contained in sample_data had been conducted.
Note that the species listed in each sampling visit indicate only the presence of that species; abundance (the number of observations of that species) is not captured. Thus a species will only appear at most once in the list for a particular sampling visit. It may of course appear again in lists for other sampling visits.
Example function calls:
'''
'''
>>> sample_data = [['magpie', 'yellow robin', 'fantail'], ['magpie', 'fantail', 'friarbird', 'warbler', 'noisy miner'], ['magpie', 'flycatcher', 'pardalote', 'noisy miner', 'superb parrot'], ['magpie', 'yellow robin', 'warbler'], ['magpie', 'thornbill', 'flycatcher', 'kookaburra'], ['magpie', 'pardalote', 'friarbird', 'raven'], ['magpie', 'pardalote', 'dollarbird'], ['magpie', 'flycatcher', 'fantail'], ['magpie', 'superb parrot', 'noisy miner'], ['night parrot']]
>>> optimise_study(sample_data, 2, 2)
(7, 0.9285714285714286)
>>> optimise_study(sample_data, 1, 2)
(9, 0.9285714285714286)
>>> optimise_study(sample_data, 2, 1)
(4, 0.6428571428571429)
'''
#Code
def optimise_study(sample_data, unseen_species, consecutive_visits):
# First we determine the total number of unique species there are
max_observed = [] # stores maximum observed species
for i, sample in enumerate(sample_data):
for specie in sample:
if specie not in max_observed:
max_observed.append(specie)
# which visit simulation ended on:
stopped_after = 0
# observed species until break condition
observed = []
# history of all visits
previous_visits = []
# Next we determine how many unique species they've seen during their
# actual visits:
for i, sample in enumerate(sample_data):
# i increase by 1 for itleration
productive = False
unseen_counter = 0
for specie in sample:
# Tracks amount of new species, and determine if visits should stop
if specie not in observed:
observed.append(specie)
unseen_counter += 1
if unseen_counter >= unseen_species:
productive = True
# This part measures the amount of consecutive unproductive visits and
# determines if new visits should be taken, depending on the value
# of consecutive_visits
previous_visits.append(productive)
if i>0 and all([not a for a in previous_visits[-consecutive_visits:]]):
stopped_after = i + 1
break
# Finally we return the amount of visits and the proportion of the total
# bird species observed by the study to this point.
return (stopped_after, len(observed) / len(max_observed))
|
08ec11d772ace1e68160069cf473de4b78f3c353 | Chary1729/GUVISET7 | /s764.py | 123 | 3.796875 | 4 | inp1,inp2 = input().split()
inp1=int(inp1)
inp2=int(inp2)
sum=inp1+inp2
if(sum%2==0):
print('even')
else:
print('odd')
|
488ec670ce6fa676d96006b4f3d1df09243d4018 | NorthcoteHS/10MCOD-Mosi-JONES | /user/calculator.py | 160 | 3.734375 | 4 |
xString = input("Enter a number: ")
x = int(xString)
yString = input("Enter a second number: ")
y = int(yString)
print('', x, ' + ', y, ' = ',x+y, '.', sep='') |
1b797cf9c4a78102c944fa6214c855d8a2508d7a | yevheniihalkin/Learning | /Hometask 3 - Yevhenii Halkin.py | 4,389 | 4.03125 | 4 | # Задание 1: У вас есть переменная value, тип - int. Написать тернарный оператор для переменной new_value по такому правилу: если value меньше 100, то new_value равно половине значения value, в противном случае - противоположне value число
value = 77
new_value = value / 2 if value < 100 else -value
print(new_value)
#####################################################®
# Задание 2: У вас есть переменная value, тип - int. Написать тернарный оператор для переменной new_value по такому правилу: если value меньше 100, то new_value равно 1, в противном случае - 0
value = 156
new_value = 1 if value < 100 else 0
print(new_value)
#####################################################
# Задание 3: У вас есть переменная value, тип - int. Написать тернарный оператор для переменной new_value по такому правилу: если value меньше 100, то new_value равно True, в противном случае - False
value = 76
new_value = True if value < 100 else False
print(new_value)
#####################################################
# Задание 4: У вас есть переменная my_str, тип - str. Заменить в my_str все маленькие буквы на большие.
my_str = "Hello, my name is Eugene"
my_str = my_str.upper()
print(my_str)
#####################################################
# Задание 5: У вас есть переменная my_str, тип - str. Заменить в my_str все большие буквы на маленькие.
my_str = "Hello, my name is Eugene"
my_str = my_str.lower()
print(my_str)
#####################################################
# Задание 6: У вас есть переменная my_str, тип - str. Если ее длинна меньше 5, то допишите в конец строки себя же. Пример: было - "qwer", стало - "qwerqwer". Если длинна не меньше 5, то оставить строку как есть.
my_str = "Hell"
if len(my_str) < 5:
my_str = 2 * my_str
print(my_str)
else:
my_str
print(my_str)
#####################################################
# Задание 7: У вас есть переменная my_str, тип - str. Если ее длинна меньше 5, то допишите в конец строки перевернутую себя же. Пример: было - "qwer", стало - "qwerrewq". Если длинна не меньше 5, то оставить строку как есть.
my_str = "Hi"
if len(my_str) < 5:
my_str = my_str + my_str[::-1]
print(my_str)
else:
my_str
print(my_str)
#####################################################
# Задание 8: У вас есть переменная my_str, тип - str. Вывести на экран все символы из этой строки, которые являются буквой или цифрой.
my_str = 'Hello, my name is Eugene. I was born in June 1996!'
new_str = ''
for symbol in my_str:
if symbol.isalnum():
new_str += symbol
print(new_str)
#####################################################
# Задание 9: У вас есть переменная my_str, тип - str. Вывести на экран все символы из этой строки, которые не являются буквой или цифрой.
my_str = 'Hello, my name is Eugene. I was born in June 1996!'
new_str = ''
for symbol in my_str:
if not symbol.isalnum():
new_str += symbol
print(new_str)
#####################################################
# Задание 10: У вас есть переменная my_str, тип - str. Вывести на экран все символы из этой строки, которые не являются буквой или цифрой и не пробел.
my_str = 'Hello, my name is Eugene. I was born in June 1996!'
new_str = ''
for symbol in my_str:
if not symbol.isalnum() and symbol != ' ':
new_str += symbol
print(new_str) |
f6a9d45ef27987d505761b40c390103a025e7ca9 | Lennoard/ifpi-ads-algoritmos2020 | /iteracao/while/fabio_3/q5.py | 226 | 3.890625 | 4 | def main():
n = int(input('Insira um numero: '))
if n < 0:
raise Exception("Deve ser positivo")
f = n
for i in reversed(range(1, n)):
f = f * i
print(f'O fatorial de {n} é {f}')
main()
|
619372d811d942096343e91bc86acec9d484d9a6 | AlexTyl/Python-learning | /Taskes/Task1.02.py | 906 | 4.125 | 4 | """Получить все четырехзначные числа, сумма цифр которых равна заданному числу n."""
def summ_of_numerals(number):
sum_numeral = 0
while number != 0:
sum_numeral += number % 10
number //= 10
return sum_numeral
def summ_of_numerals_equals_number(number):
counter_num = 1000
while counter_num < 10000:
if number == summ_of_numerals(counter_num):
print(counter_num)
counter_num += 1
def summ_of_numerals_equals_number_v2(my_list, number):
for i in my_list:
if summ_of_numerals(i) == number:
print(i)
print("Enter the number:")
summ_of_numerals_equals_number(int(input()))
print("Enter start and end of array:")
start = int(input())
end = int(input())
print("Enter the number:")
summ_of_numerals_equals_number_v2(range(start, end), int(input()))
|
b625f704bbafb0ccb29813918470b9a7c0a545c1 | icelnwza/CP3-Chayanut-Lapanaphan | /Lecture71_Chayanut_L.py | 507 | 3.734375 | 4 | menuList = []
priceList = []
def showBill():
print("Food list".center(15,"-"))
for i in range(len(menuList)):
print(menuList[i],"=",priceList[i])
totalPrice()
def totalPrice():
result = 0
for i in priceList:
result = result+i
print("Total Price =",result)
while True:
menuName = input("Plese Enter Menu :")
if(menuName.lower() == "exit"):
break
else: menuPrice = int(input("Price : "))
menuList.append(menuName)
priceList.append(menuPrice)
showBill() |
c5dd9121cf2cba80f3e894d9eec06c21a8c48e52 | MichaelWei1990/GoScheduleAlarm | /core/model/stopTime.py | 929 | 3.703125 | 4 | import time
class StopTime:
__stopID = ""
__arrivalHour = 0
__arrivalMinute = 0
__headSign = ""
def __init__(self, stopID, arrivalHour, arrivalMinute, headSign):
self.__stopID = stopID
self.__arrivalHour = arrivalHour
self.__arrivalMinute = arrivalMinute
self.__headSign = headSign
def get_stop_id(self):
return self.__stopID
def get_arrival_time(self):
return self.__arrivalHour, self.__arrivalMinute
def get_head_sign(self):
return self.__headSign
def __make_time_string(self):
return str(self.__arrivalHour) + ":" + str(self.__arrivalMinute)
def display(self):
print("Stop time -- ID: " + self.__stopID + ", arrival time: " + self.__make_time_string() + ", head sign: " + self.__headSign)
# testStopTime = StopTime("UN", 17, 20, "Union Station 17:20 - Lincolnville GO 18:37")
# testStopTime.display() |
61e054ec52e435ab43a989a23ac36c8f656c92e5 | HagenGaryP/slack-bot-workshop | /bot.py | 2,208 | 3.953125 | 4 | # -*- coding: utf-8 -*-
"""
In this file, we'll create a python Bot Class.
"""
import os
from slackclient import SlackClient
class Bot(object):
""" Instanciates a Bot object to handle Slack interactions."""
def __init__(self):
super(Bot, self).__init__()
# When we instantiate a new bot object, we can access the app
# credentials we set earlier in our local development environment.
self.oauth = {"client_id": os.environ.get("CLIENT_ID"),
"client_secret": os.environ.get("CLIENT_SECRET"),
# Scopes provide and limit permissions to what our app
# can access. It's important to use the most restricted
# scope that your app will need.
"scope": "bot"}
self.verification = os.environ.get("VERIFICATION_TOKEN")
self.client = SlackClient("")
def auth(self, code):
"""
Here we'll create a method to exchange the temporary auth code for an
OAuth token and save it in memory on our Bot object for easier access.
"""
auth_response = self.client.api_call("oauth.access",
client_id=self.oauth['client_id'],
client_secret=self.oauth['client_secret'],
code=code)
# We'll save the bot_user_id to check incoming messages mentioning our bot
self.bot_user_id = auth_response["bot"]["bot_user_id"]
self.client = SlackClient(auth_response["bot"]["bot_access_token"])
def say_hello(self, message):
"""
Here we'll create a method to respond when a user DM's our bot
to say hello!
"""
""" A method to respond to a user who says hello. """
channel = message["channel"]
hello_response = "I want to live! :pray: Please build me <@%s>" % message["user"]
print('IN BOT PYTHON FILE, HELLO RESPONSE ===== ', hello_response, ' channel = ', channel)
self.client.api_call("chat.postMessage",
channel=channel,
text=hello_response)
|
17a07dfcf51032bfbe22e2300e8e36e1df232de0 | piquesel/learn_python | /qcm_simple.py | 3,911 | 3.671875 | 4 | # Simple qcm program
import random
import sys
choice = None
# Questions du qcm
questions = [('What is the average latency with OVP?', '10us'),
('What is the maximum throughput we can reach with AVP?', 'Line rate'),
('In OpenStack, what is Nova in charge of?','Compute'),
('In OpenStack, Horizon is for the...?', 'gui'),
('Most famous cloud solution is?', 'Amazon')]
# List of already asked questions
# We will store the question's id
qcache = []
NB_QUESTIONS = len(questions)
NB_WORDS = len(questions[0]) - 1
#
# Query yes or no
#
def query_yes_no(question, default="yes"):
""" Ask a yes/no question via input() and return the answer.
"Question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning an answer
is required of the user)
The "answer" return value is one of "y":"yes", "ye":"yes", "no":None)
"""
valid = {"yes":"yes", "y":"yes", "ye":"yes",
"no":"no", "n":"no"}
if default == None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("Invalid default answer: '%s'" % default)
while 1:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return default
elif choice in valid.keys():
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "\
"(or 'y' or 'n').\n")
#
# Pick the question at random
#
def select_question_id():
"""Will pick a question at random"""
# generate random numbers 1 - 6
question_nb = random.randint(1, NB_QUESTIONS-1)
return question_nb
#
# Ask the question once chosen
#
def ask_question(question_id):
"""Ask the question to the student"""
print("What is the correct answer?")
for i in range(0, NB_WORDS):
print(i, ") ", questions[question_id][i])
return None
#
# Main meny
#
while choice != "0":
print(
"""
Q&A
0 - Exit
1 - Start the test
2 - Create a test
"""
)
choice = input("What is your choice? ")
print()
# Quit
if choice == "0":
print("Bye!")
# Start a new test
elif choice == "1":
print("We start the test\n")
score = 0
nb_of_questions = int(input("How many questions do you want? "))
for i in range(0, nb_of_questions):
# Pick a question...
question_id = select_question_id()
while question_id in qcache:
question_id = select_question_id()
qcache.append(question_id)
print("Cache content: ", qcache)
# Ask the question
print("Here is question #", question_id)
ask_question(question_id)
# Wait for the user's answer
answer = input("What is your answer? ")
print("The right answer is ", questions[question_id][1])
# Rate the answer
answer = query_yes_no("Do you consider the answer is correct?")
print("You answered %s" % answer)
if answer == "yes":
score += 1
print("You final score is %d/%d" % (score,nb_of_questions))
# Créer un qcm
elif choice == "2":
print("Créer un qcm : pas encore implémenté")
# Choix inconnu
else:
print("Désolé mais le choix ", choice, "n'est pas disponible.")
input("\n\nAppuyer sur la toucher entrer pour quitter.")
#
# TODO
#
# 1) Get rid of the questions in the program and store them in an XML file
# |
f0043c23114a92f5792215a29ef32447e4d6b352 | carwima/FP_PROGJAR | /New folder/gui.py | 1,090 | 3.640625 | 4 | from tkinter import *
mw = Tk()
mw.option_add("*Button.Background", "grey")
mw.option_add("*Button.Foreground", "white")
mw.title('ChatApp')
#You can set the geometry attribute to change the root windows size
mw.geometry("500x500") #You want the size of the app to be 500x500
mw.resizable(0, 0) #Don't allow resizing in the x or y direction
back = Frame(master=mw,bg='grey')
back.pack_propagate(0) #Don't allow the widgets inside to determine the frame's width / height
back.pack(fill=BOTH, expand=1) #Expand the frame to fill the root window
Lb = Listbox(back)
countlb = 0
Lb.pack(side = LEFT, fill=BOTH, expand=1)
scrollbar = Scrollbar(back)
scrollbar.pack(side = RIGHT, fill = BOTH)
Lb.config(yscrollcommand = scrollbar.set)
scrollbar.config(command = Lb.yview)
def getTextInput():
result=textExample.get("1.0","end-1c")
# print(result)
Lb.insert(END, result)
textExample.delete('1.0', END)
textExample=Text(master=mw, height=1)
textExample.pack()
btnRead=Button(master=mw, height=1, width=10, text="Send ", command=getTextInput)
btnRead.pack()
mw.mainloop()
|
42e71a82f71ba0d96bbf0de674a8114e2d10f158 | andipro123/PPL-Assignment | /4_Classes-2/shapes.py | 3,372 | 4.1875 | 4 | from abc import ABC, abstractmethod
from math import sqrt
#Base class
class Shapes:
def __init__(self):
self._Type = '' #Protected member
print("A shape has been created!")
def get_Type(self):
print(self._Type)
def __del__(self):
print('Shape has been destructed!')
@abstractmethod
def get_area(self):
pass
#Triangle
class triangle(Shapes):
def __init__(self):
self._side = 3
#We can modify protected members via base class
def set_type(self):
self._Type = 'Polygon with 3 sides'
#Only member functions can have access to private members
def get_side(self):
print(self._side)
#Equilateral traingle inherited from triangle
class equilateral(triangle):
def __init__(self, length):
self.__length = length
#We can modify protected members via base class
def set_type(self):
self._Type = 'Polygon with 3 sides and all three are equal'
#Only member functions can have access to private members
def get_side(self):
print(self._side)
#We use polymorphism to override the abstract method of the interface.
def get_area(self):
print((sqrt(3) / 4) * (self.__length ** 2))
#Rectangle
class rectangle(Shapes):
def __init__(self):
self.__side = 4
#We can modify protected members via base class
def set_type(self,typ):
self._Type = 'Polygon with 2 equal and 2 unequal sides'
#Only member functions can have access to private members
def get_side(self):
print(self.__side)
#Square inherited from rectangle
class square(rectangle):
def __init__(self):
self.sides = 4
#We can modify protected members via base class
def set_type(self):
self._Type = 'Polygon with 4 sides all of which are equal'
def get_side(self):
#The getter function will throw an error if this is executed as the private member of base class is being accessed
#print(self.__side)
print(self.sides)
#Rhombus inherited from square
class rhombus(square):
def set_type(self):
self._Type = 'Polygon with 4 sides all of which are equal but angles are not 90'
#The base class has a public member in sides so we can access it in the base class and outside
def get_side(self):
print(self.sides)
#Circle
class circle(Shapes):
def __init__(self):
Shapes.__init__(self)
self.__r = 0
self.__eqn = 'x^2 + y^2 = r^2'
def set_type(self):
self._Type = 'Conic'
#Setter function for accessing private member
def set_radius(self,r):
self.__r = r
def get_area(self):
print(3.14 * (self.__r)**2)
#Ellipse
class ellipse(Shapes):
def __init__(self):
self.__a = 0
self.__b = 0
self.__eqn = 'x^2/a^2 + y^2/b^2 = 1'
def set_type(self):
self._Type = 'Conic with a major and minor axis'
#Setter function for accessing private member
def set_radius(self,a,b):
self.__a = a
self.__b = b
def get_area(self):
print(3.14 * self.__a * self__b)
if __name__ == "__main__":
pass |
361bcb64ec3b66cb84ef67d8c225b8f88d83e4c5 | IvanNaka/JornadaByLearn | /JornadaByLearn.py | 791 | 4.09375 | 4 | # Ivan Yudi Oda Nakatani 07/01/2020
primeironumero = int(input('Coloque o primeiro número: '))
segundonumero = int(input('Coloque o segundo número: '))
conta = str(input('Qual operação deseja fazer? '))
soma = primeironumero + segundonumero
subtracao = primeironumero - segundonumero
multiplicacao = primeironumero * segundonumero
divisao = primeironumero / segundonumero
media = (primeironumero + segundonumero) / 2
if conta == 'soma':
print(f'A soma é {soma} ')
elif conta == 'subtração':
print(f'A subtração é {subtracao} ')
elif conta == 'multiplicação':
print(f'A multiplicão é {multiplicacao}')
elif conta == 'divisão':
print(f'A divisão é {divisao}')
elif conta == 'média':
print(f'A média é {media}')
else:
print('Não entendi a operação')
|
64ef59565dea9003268d7105bd88c1218a21289a | skyegrey/mth490project3 | /project1.4.2.py | 4,320 | 3.59375 | 4 | import math
import pandas
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Predictor function based on sigmoid function
# Input: Vector of X variables, Vector of C variables
# Output: Predicted values from the function (between 1 and 0)
def predictor_function(x_vector, c_vector):
exponent = -c_vector[0]
for i in range(0, len(x_vector)):
exponent += -c_vector[i + 1]*x_vector[i]
denominator = 1 + math.exp(exponent)
if denominator != 0:
return 1/denominator
else:
print('Denominator error')
return None
def loss_function(x_vector, y_vector, c_vector, p=predictor_function):
loss = 0
m = len(y_vector)
for i in range(0, len(x_vector)):
#
if y_vector[i] == 0:
loss += -math.log(1 - p(x_vector[i], c_vector))
#
else:
loss += -math.log(p(x_vector[i], c_vector))
loss = loss/m
# print('Loss:', loss)
return loss
def div(h, x_vector, y_vector, c_vector, c_cord, f=loss_function):
c_step = list(c_vector)
c_step[c_cord] += h
# print('c_vecs:', c_step, c_vector)
y1 = f(x_vector, y_vector, c_vector)
y2 = f(x_vector, y_vector, c_step)
return (y2 - y1)/h
# Read in the data
sleep_data_frame = pandas.read_excel("StudySleep.xlsx")
sleep_data = sleep_data_frame.as_matrix()
# print("Sleep data:", sleep_data)
# Change classification to 0 for fail, and 1 for pass
for i in range(0, len(sleep_data)):
if sleep_data[i][2] == 'Fail':
sleep_data[i][2] = 0
else:
sleep_data[i][2] = 1
# Separate out the training data and test data
training_data = sleep_data[:10]
test_data = sleep_data[10:]
# Separate Y training and Y test values/data
y_training_data = training_data[:, 2]
y_test_data = test_data[:, 2]
y_training_data = y_training_data.astype("int")
# Separate X training and X test data/values
x_training_data = training_data[:, [0,1]]
x_test_data = test_data[:, [0,1]]
# print("\nX_training_data:\n", x_training_data)
# Start with a baseline C value
c_weights = [-1, 1, 1]
# c_weights = [-.82, 2.68, -3.01]
# c_weights = [0, 2, 0]
# print(predictor_function([10, 2], [0, 0, 0]))
print('loss before gradient descent:', loss_function(x_training_data, y_training_data, c_weights))
# Gradient Descent
# Numeric Differentiation:
print('c_weights before gradient descent:', c_weights)
# Descend C0
for n in range(0, 3):
loss_last = loss_function(x_training_data, y_training_data, c_weights)
derivative = div(.00001, x_training_data, y_training_data, c_weights, n)
learning_rate = .01
precision = .00001
# print('c_weights before', c_weights)
# Derivative is positive with respect to c0, reduce c0
while abs(derivative) > precision:
if derivative > 0:
c_weights[n] += -learning_rate*derivative
else:
c_weights[n] += -learning_rate*derivative
derivative = div(.001, x_training_data, y_training_data, c_weights, n)
# print('derivative:', derivative)
# tc_weights = [-.82, 2.68, -3.01]
# print('Loss function test:', loss_function(x_training_data, y_training_data, tc_weights))
print('loss after:', loss_function(x_training_data, y_training_data, c_weights))
print('c_weigths after:', c_weights)
grid_x = []
grid_y = []
grid_z = []
for i in range(0, 16):
for n in range(0, 10):
grid_x.append(i)
grid_y.append(n)
grid_z.append(predictor_function([i,n], c_weights))
grid_x = np.asarray(grid_x)
grid_y = np.asarray(grid_y)
grid_z = np.asarray(grid_z)
# grid_matrix = np.matrix(grid)
# print(grid_x)
print('Probability that a person who sleeps 7 hours and studies 12 passes:', predictor_function([12, 7], c_weights))
study_list = []
sleep_list = []
for item in x_training_data:
study_list.append(item[0])
sleep_list.append(item[1])
x2_0 = -c_weights[0]/c_weights[2]
x1_0 = -c_weights[0]/c_weights[1]
plt.ylim([5, 9])
plt.plot([0, x2_0], [x1_0, 0], color='red')
plt.scatter(study_list, sleep_list)
plt.show()
fig = plt.figure()
ax = fig.gca(projection='3d')
# grid_x, grid_y = np.matrix(grid_x, grid_y)
# grid_z = np.array([grid_z])
# print('arrays:', grid_x)
surf = ax.scatter(grid_x, grid_y, grid_z)
plt.show()
# surface = Axes3D.plot_surface(grid_x, grid_y, grid_z) |
599bcabceb8576b7bb96e64e94d69b9519378937 | jeprob/datamining | /dm1_Similarity & Timeseries & Graphs/shortest_path_kernel.py | 1,715 | 3.890625 | 4 | """Skeleton file for your solution to the shortest-path kernel.
Student: Jennifer Probst (16-703-423)"""
import numpy as np
def floyd_warshall(A):
"""Implement the Floyd--Warshall on an adjacency matrix A.
Parameters
----------
A : `np.array` of shape (n, n)
Adjacency matrix of an input graph. If A[i, j] is `1`, an edge
connects nodes `i` and `j`.
"""
import copy
S=copy.deepcopy(A)
#transform the 0s to 10000 except the diagonal
n=len(A)
I = np.identity(n, dtype=bool)
S[S!=0] = 1 #maybe other distance needed
S[S==0] = 10000
S[I]=0
#algorithm as proposed in pseudocode
for k in range(0,n):
for i in range(0,n):
for j in range(0,n):
if S[i,k] + S[k,j] < S[i,j]:
S[i,j]=S[i,k]+S[k,j]
"""
Returns
-------
An `np.array` of shape (n, n), corresponding to the shortest-path
matrix obtained from A.
"""
return S
def sp_kernel(S1, S2):
"""Calculate shortest-path kernel from two shortest-path matrices.
Parameters
----------
S1: `np.array` of shape (n, n)
Shortest-path matrix of the first input graph.
S2: `np.array` of shape (m, m)
Shortest-path matrix of the second input graph.
"""
sim=0.0
n=len(S1)
m=len(S2)
for ir in range(0, n):
for ic in range(ir,n):
for jr in range(0,m):
for jc in range(jr, m):
if S1[ir,ic]==S2[jr,jc] and S1[ir,ic]!=0:
sim+=1
"""
Returns
-------
A single `float`, corresponding to the kernel value of the two
shortest-path matrices
"""
return sim
|
331373437ed315c5f06f9aa32a8da6ad498a8f6d | Itumeleng-1/function_101_assignment | /Square-root-function.py | 2,035 | 4.0625 | 4 |
#Creating square-root function and calculating differences with the in-built math functions
def mysqrt( a, x , e):
""" Estimates the square root of a selected number 'a' from an initial estimate 'x', that is within an epsilon 'e' error margin"""
while True:
print(x)
y = ( x + a/x)/2
if abs(y -x) < e:
break
x = y
#Rest of table values (non-tabular form)
Difference = x - math.sqrt(a)
print('square root estimate is ', x)
print('actual square-root is ', math.sqrt(a))
print('Difference is ', Difference)
#Static Prototype of the real deal
def table():
header = 'a\t|\tmysqrt(a, x, e)\t|\tmath.sqrt(a)\t|\tDifference'
print(header)
print('---' * len(header))
print('1.0' + '\t|\t' + '1.0' + '\t\t|\t' + '1.0' + '\t\t|\t' + '0.0')
print('2.0' + '\t|\t' + '1.41421356237' + '\t|\t' + '1.41421356237' + '\t|\t' + '2.22044604925e-16')
print('3.0' + '\t|\t' + '1.73205080757' + '\t|\t' + '1.73205080757' + '\t|\t' + '0.0')
print('4.0' + '\t|\t' + '2.0' + '\t\t|\t' + '2.0' + '\t\t|\t' + '0.0')
print('5.0' + '\t|\t' + '2.2360679775' + '\t|\t' + '2.2360679775' + '\t|\t' + '0.0')
print('6.0' + '\t|\t' + '2.44948974278' + '\t|\t' + '2.44948974278' + '\t|\t' + '0.0')
print('7.0' + '\t|\t' + '2.64575131106' + '\t|\t' + '2.64575131106' + '\t|\t' + '0.0')
print('8.0' + '\t|\t' + '2.82842712475' + '\t|\t' + '2.82842712475' + '\t|\t' + '4.4408920985e-16')
print('9.0' + '\t|\t' + '3.0' + '\t\t|\t' + '3.0' + '\t\t|\t' + '0.0')
#Attempt at Dynamic working prototype
import math
def table():
header = 'a\t|\tmysqrt(a, x, e)\t|\tmath.sqrt(a)\t|\tDifference'
print(header)
print('---' * len(header))
x=5
e = 0.0000000000000001
a = 9
while a > 0:
print(str(a) + '\t|\t' + str(mysqrt( a, x , e)) + '\t\t|\t' + str(math.sqrt(a)) + '\t\t|\t' + str(mysqrt( a, x , e) - math.sqrt(a)))
break
a = a -1
|
4e1d636d6e9983baa23d0d1b9769839a9c251142 | Leewongi0731/DailyCodeTest | /[백준 골드2] 1655번.py | 815 | 3.6875 | 4 | # 1655번: 가운데를 말해요
# binary search, insert 조합으로 하면 시간초과.
# 배열의 item추가 시간복잡도를 줄이기 위해 좌(maxHeap), 우(minHeap)으로 구현
import sys
import heapq
N = int(input())
mid = int(input())
print( mid )
# 항상 len( left ) = len(right) or len( left ) = len( right ) + 1
left = [] # 가장 큰 값 -> maxHeap
right = [] # 가장 작은 값 -> minHeap
for _ in range(N-1):
item = int( sys.stdin.readline() )
if mid > item: heapq.heappush( left, -item )
else: heapq.heappush( right, item )
if len( left ) > len( right ):
heapq.heappush( right, mid )
mid = -heapq.heappop( left )
elif len( left ) + 1 < len( right ):
heapq.heappush( left, -mid )
mid = heapq.heappop( right )
print( mid ) |
5c9183141128ca2d00b9bda0bfa3e0b11150c0d7 | JaiIrkal/Stone-Paper-Scissors-Game | /gamemodule.py | 2,874 | 4.15625 | 4 | from random import choice
def game():
computer_choice = ['stone', 'paper', 'scissors']
computer_turn = choice(computer_choice)
player_choice = input("Enter stone, paper or scissors: ").lower()
if player_choice != 'stone' and player_choice != 'scissors' and player_choice != 'paper':
print("Enter a valid value!")
if player_choice == 'stone' and computer_turn == 'scissors':
print('The computer chooses ', computer_turn)
print("You Win!!!")
elif player_choice == 'paper' and computer_turn == 'stone':
print('The computer chooses ', computer_turn)
print("You Win!!!")
elif player_choice == 'scissors' and computer_turn == 'paper':
print('The computer chooses ', computer_turn)
print("You Win!!!")
elif player_choice == computer_turn:
print('The computer chooses ', computer_turn)
print("Draw")
elif player_choice == 'paper' and computer_turn == 'scissors':
print('The computer chooses ', computer_turn)
print("You Lose")
elif player_choice == 'stone' and computer_turn == 'paper':
print('The computer chooses ', computer_turn)
print("You Lose")
elif player_choice == 'scissors' and computer_turn == 'stone':
print('The computer chooses ', computer_turn)
print("You Lose")
player_choice = input("Do you want to play again (y or n)").lower()
while player_choice == 'y':
player_choice = input("Enter stone, paper or scissors: ").lower()
if player_choice != 'stone' and player_choice != 'scissors' and player_choice != 'paper':
print("Enter a valid value!")
if player_choice == 'stone' and computer_turn == 'scissors':
print('The computer chooses ', computer_turn)
print("You Win!!!")
elif player_choice == 'paper' and computer_turn == 'stone':
print('The computer chooses ', computer_turn)
print("You Win!!!")
elif player_choice == 'scissors' and computer_turn == 'paper':
print('The computer chooses ', computer_turn)
print("You Win!!!")
elif player_choice == computer_turn:
print('The computer chooses ', computer_turn)
print("Draw")
elif player_choice == 'paper' and computer_turn == 'scissors':
print('The computer chooses ', computer_turn)
print("You Lose")
elif player_choice == 'stone' and computer_turn == 'paper':
print('The computer chooses ', computer_turn)
print("You Lose")
elif player_choice == 'scissors' and computer_turn == 'stone':
print('The computer chooses ', computer_turn)
print("You Lose")
player_choice = input("Do you want to play again (y or n)").lower()
|
d8e1ab6c84901181ef7450866caf871b775429f1 | Gameatron/python-things | /CS1/Turtles/random_walk.py | 1,301 | 4.09375 | 4 | from turtle import *
from random import randint, choice
##############################
#a way of going to the home point with out making marks
def go_home(t):
t.penup()
t.home()
t.pendown()
def rand_walk(t, steps):
for i in range(steps):
#generate randome number
direction = randint(0, 3)
#have turtle face a random direction
if direction == 0:
t.seth(0)
t.color('blue')
if direction == 1:
t.seth(90)
t.color('green')
if direction == 2:
t.seth(180)
t.color('white')
if direction == 3:
t.seth(270)
t.color('yellow')
#move forward
t.fd(50)
#making the turtle stay inside the margins
if t.xcor() > 350:
go_home(t)
if t.xcor() < -350:
go_home(t)
if t.ycor() > 350:
go_home(t)
if t.ycor() < -350:
go_home(t)
#############################################
colors = ('red', 'blue', 'green', 'white')
bgcolor('black')
t= Turtle()
t.speed(0)
rand_walk(t, 1000) |
f3e18581bc32a0e163d937a5d24cc0d75ffdba49 | knwlim/leetcode | /week_1/Reverse_Linked_List.py | 998 | 4.03125 | 4 | class Stack_Solution:
def reverseList(self, head: 'ListNode') -> 'ListNode':
# save current listked list to stack
stack = []
node_for_stack = head
while node_for_stack is not None:
stack.append(node_for_stack.val)
node_for_stack = node_for_stack.next
result = head # to save head so we can return
for val in reversed(stack):
result.val = val=
result = result.next
return head
# O(1) Space Solution
# it needs 3 pointers
class Solution:
def reverseList(self, head: 'ListNode') -> 'ListNode':
prev_node = None
current = head
next_node = head
while current:
next_node = next_node.next # save before we brake connection
current.next = prev_node # break it and reconnect to prev node
prev_node = current
current = next_node # move on to next node to repeat
return prev_node
|
5dd0a8ae8f01093ccf008631f0a969f43cbf09ab | ggwg/MultiplayerSnake | /Specimen.py | 6,051 | 4.15625 | 4 | # Simple Snake Game in Python 3 for Beginners
# By @TokyoEdTech
import turtle
import time
import random
delay = 0.1
# Score
score = 0
high_score = 0
class Gamestate:
def __init__(self):
self.wn = turtle.Screen()
self.wn.title("Snake Game by @TokyoEdTech")
self.wn.bgcolor("green")
self.wn.setup(width=1000, height=1000)
self.wn.tracer(0) # Turns off the screen updates
# Game statistics pen
self.pen = turtle.Turtle()
self.pen.speed(0)
self.pen.shape("square")
self.pen.color("white")
self.pen.penup()
self.pen.hideturtle()
self.pen.goto(0, 260)
self.pen.write("Score: 0 High Score: 0", align="center", font=("Courier", 24, "normal"))
# Food
self.food = turtle.Turtle()
self.food.speed(0)
self.food.shape("circle")
self.food.color("red")
self.food.penup()
self.food.goto(0,100)
# Players
self.p1 = Snake()
# Segments
def start(self):
global score, high_score, delay
# Keyboard bindings
self.wn.listen()
self.wn.onkeypress(self.p1.go_up, "w")
self.wn.onkeypress(self.p1.go_down, "s")
self.wn.onkeypress(self.p1.go_left, "a")
self.wn.onkeypress(self.p1.go_right, "d")
# Main game loop
while True:
self.wn.update()
# Check for a collision with the border
if self.p1.getXPos()>500 or self.p1.getXPos()<-500 or self.p1.getYPos()>500 or self.p1.getYPos()<-500:
time.sleep(1)
self.p1.head.goto(0,0)
head.direction = "stop"
# Hide the segments
for segment in self.p1.segments:
segment.goto(1000, 1000)
# Clear the segments list
self.p1.segments.clear()
# Reset the score
score = 0
# Reset the delay
delay = 0.1
pen.clear()
pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))
# Check for a collision with the food
if self.p1.head.distance(self.food) < 20:
# Move the food to a random spot
x = random.randint(-290, 290)
y = random.randint(-290, 290)
self.food.goto(x,y)
# Add a segment
new_segment = turtle.Turtle()
new_segment.speed(0)
new_segment.shape("square")
new_segment.color("grey")
new_segment.penup()
self.p1.segments.append(new_segment)
# Shorten the delay
delay -= 0.001
# Increase the score
score += 10
if score > high_score:
high_score = score
self.pen.clear()
self.pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))
# Move the end segments first in reverse order
for index in range(len(self.p1.segments)-1, 0, -1):
x = self.p1.segments[index-1].xcor()
y = self.p1.segments[index-1].ycor()
self.p1.segments[index].goto(x, y)
# Move segment 0 to where the head is
if len(self.p1.segments) > 0:
x = self.p1.getXPos()
y = self.p1.getYPos()
self.p1.segments[0].goto(x,y)
self.p1.move()
# Check for head collision with the body segments
for segment in self.p1.segments:
if segment.distance(self.p1.head) < 20:
time.sleep(1)
self.p1.head.goto(0,0)
self.head.direction = "stop"
# Hide the segments
for segment in self.p1.segments:
segment.goto(1000, 1000)
# Clear the segments list
self.p1.segments.clear()
# Reset the score
score = 0
# Reset the delay
delay = 0.1
# Update the score display
pen.clear()
pen.write("Score: {} High Score: {}".format(score, high_score), align="center", font=("Courier", 24, "normal"))
time.sleep(delay)
self.wn.mainloop()
class Snake:
def __init__(self):
self.head = turtle.Turtle()
self.head.speed(0)
self.head.shape("square")
self.head.color("black")
self.head.penup()
self.head.goto(0,0)
self.head.direction = "stop"
# Snake segments
self.segments = []
def getXPos(self):
return self.head.xcor()
def getYPos(self):
return self.head.ycor()
# Functions
def go_up(self):
if self.head.direction != "down":
self.head.direction = "up"
def go_down(self):
if self.head.direction != "up":
self.head.direction = "down"
def go_left(self):
if self.head.direction != "right":
self.head.direction = "left"
def go_right(self):
if self.head.direction != "left":
self.head.direction = "right"
def move(self):
if self.head.direction == "up":
y = self.head.ycor()
self.head.sety(y + 20)
if self.head.direction == "down":
y = self.head.ycor()
self.head.sety(y - 20)
if self.head.direction == "left":
x = self.head.xcor()
self.head.setx(x - 20)
if self.head.direction == "right":
x = self.head.xcor()
self.head.setx(x + 20)
newGame = Gamestate()
newGame.start() |
03c6915848c840e23ef80b8f1a8cb5f79fdd2f6c | jessapp/coding-challenges | /printllreverse.py | 157 | 4 | 4 | # Print elements in a linked list in reverse order
def reverse_ll(head):
if head == None:
return
reverse_ll(head.next)
print head.data |
0f6723dd320e75b0e8b0b16973589d7280d745b2 | nervaishere/DashTeam | /python/HOMEWORK/5th_Session/Answers/Class/3/(3).py | 132 | 3.625 | 4 | x=input("enter your text:")
y=len(x)
print(y)
if y%2==0:
print(x[int(y/2)])
else:
print(x[int((y-1)/2)])
|
a8128c02d17d3aa19de9ee6249c129080505450c | Hoodythree/LeetCode_By_Tag | /Data_Structure_and_Alogrithm/Compute_conponent.py | 466 | 3.859375 | 4 | def power(base,exp):
res = 1 # 保存结果
while exp: # 当指数不为0
if exp & 1: # 判断二进制最低位是否为1,如果为1,就把之前的幂乘到结果中。
res *= base
base *= base # 一直累乘,构造 base^2 -> base^4 -> base^8 -> base^16 -> ...
exp = exp >> 1 # 去掉指数的二进制最低位,继续判断
return res
n = input()
print('2^{0} = {1}'.format(int(n), power(2, int(n)))) |
921832e008a17ed1eae446d1042e68f24110e192 | nkatynski/NicoleCode | /Delimiter_check/stack_delimiter.py | 1,715 | 4.25 | 4 | # Program to confirm proper bracket/brace/parenthesis delimiting in a stringLength
# Stack implemented using collections module
from collections import deque
def balanceCheck(userInput):
counter = 0
isBalanced = True
delimStack = deque() # our stack is technically a deque, but whatever
for i in userInput: # iterate through user input string
if userInput[counter] == ('[' or '{' or '('): # detect opening delimiting character
delimStack.append(userInput[counter]) # push opening delimiting character to stack
elif userInput[counter] == (']' or '}' or ')'): # detect closing delimiting character
if not delimStack:
isBalanced = False # a closing bracket with an empty stack means automatic failure
# remove matching delimiting characters - there has got to be a more graceful way to do that
elif ((delimStack[-1] == '[') and (userInput[counter] == ']')) or (delimStack[-1] == '{') and (userInput[counter] == '}') or (delimStack[-1] == '(') and (userInput[counter] == ')'):
delimStack.pop()
counter += 1
if delimStack: # any elements remaining after matching/popping is finished indicates failure
isBalanced = False
return isBalanced
# poll user for phrase to check
userInput = input("Enter a string delimited by brackets, parentheses, or braces: ")
if(balanceCheck(userInput)): # run balance check function
print("This string is properly delimited.")
else:
print("This string is NOT properly delimited.")
|
0fbf576bdc686928c82c5f9507bab4aa705035f2 | HugoBahman/Assignment | /Revision, Development and Stretch and Challenge Excercises/Development Excercise 3.py | 435 | 4.28125 | 4 | #Hugo
#Development Excercise 3
#16/09/14
print("This program takes your height and weight in inches and stones and then converts them to cm and kg.")
inches_height = float(input("Please enter your height in inches: "))
stones_weight = float(input("Please enter your weight in stones: "))
cm_height = inches_height*2.54
kg_weight = stones_weight*6.364
print("You are {0}cm tall and weigh {1}kg".format(cm_height, kg_weight))
|
bc5367efb7f254368a865238266da72924473ef8 | twistby/python-project-lvl2 | /gendiff/diff_finder.py | 1,492 | 3.609375 | 4 | """Find differencies."""
from typing import Any, Tuple
ADDED = 'added'
REMOVED = 'removed'
NESTED = 'nested'
UNCHANGED = 'unchanged'
UPDATED = 'updated'
def get_diff_node(
diff_kind: str,
first_value: Any,
second_value: Any = None,
) -> Tuple:
"""Packs the difference in the dictionary."""
return (
first_value,
second_value,
diff_kind,
)
def find_diff(first_data: dict, second_data: dict) -> dict:
"""Create dict with differences between two dictionaries."""
first_dict_keys = set(first_data)
second_dict_keys = set(second_data)
diff = {}
for dict_key in first_dict_keys.union(second_dict_keys):
first_value = first_data.get(dict_key)
second_value = second_data.get(dict_key)
if first_value == second_value:
diff_node = get_diff_node(UNCHANGED, first_value)
elif dict_key not in first_dict_keys:
diff_node = get_diff_node(ADDED, second_value)
elif dict_key not in second_dict_keys:
diff_node = get_diff_node(REMOVED, first_value)
elif isinstance(first_value, dict) and isinstance(second_value, dict):
diff_node = get_diff_node(
NESTED,
find_diff(first_value, second_value),
)
else:
diff_node = get_diff_node(
UPDATED,
first_value,
second_value,
)
diff[dict_key] = diff_node
return diff
|
8b9ac54cf15648e5c5bb315fbd2e2d3bcffb5b9c | howraniheeresj/Programming-for-Everybody-Python-P4E-Coursera-Files | /Básicos/PygLatin.py | 775 | 4.4375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#o objetivo deste programa é mover a primeira letra da palavra para o final e adicionar ay.
#Dessa forma, a palavra Batata vira atatabay
pyg = 'ay'
#primeiro define-se ay
original = raw_input('Escolha uma palavra: ')
#deixa um espaço para colocar uma palavra
if len(original) > 0 and original.isalpha():
#a palavra deve ter mais que 0 letras e ser composta somente por letras (isalpha)
print "A palabra escolhida foi: ", original
word = original.lower
first = word[0]
#primeira letra da palavra já com as letras minúsculas
new_word = word + first + pyg
new_word = new_word[1:len(new_word)]
#cortamos aqui a primeira letra da palavra
print "Sua tradução em PygLatin é: ", new_word
else:
print "Vazio!" |
1f709c4c27fc09efc82f9b444d3a9a878b928ce1 | LindaSithole/git-basic-ex | /Level 0/Task4.0.py | 272 | 4.125 | 4 |
def even_or_odd():
user_input = int(input("Enter Your Number: "))
even_numbers = [1,2,4,6,8,10]
odd_numbers = [1,3,5,7,9,11]
if user_input in even_numbers:
print("even")
elif user_input in odd_numbers:
print("odd")
even_or_odd() |
98d0598345a87f62b43f4426a75764f486904ded | tedrepo/Algorithm | /Data structure and algorithm/2018-11-27-二分查找四个变形.py | 2,482 | 3.765625 | 4 | # -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2018-11-27 10:57:45
# @Last Modified by: 何睿
# @Last Modified time: 2018-11-27 11:28:11
import random
import time
numbers = random.choices(range(0, 10), k=15)
numbers.sort()
def find_first(numbers, x):
left, right = 0, len(numbers)-1
while left <= right:
middle = left+((right-left) >> 1)
if numbers[middle] == x:
if middle == 0:
return 0
elif numbers[middle-1] != x:
return middle
elif numbers[middle-1] == x:
right = middle-1
elif numbers[middle] > x:
right = middle-1
elif numbers[middle] < x:
left = middle+1
return None
def find_last(numbers, x):
left, right = 0, len(numbers)-1
while left <= right:
middle = left+((right-left) >> 1)
if numbers[middle] == x:
if middle == len(numbers)-1:
return middle
elif numbers[middle+1] != x:
return middle
elif numbers[middle+1] == x:
left = middle+1
elif numbers[middle] > x:
right = middle-1
elif numbers[middle] < x:
left = middle+1
return None
def find_first_greater(numbers, x):
left, right = 0, len(numbers)-1
while left <= right:
middle = left+((right-left) >> 1)
if numbers[middle] >= x:
if middle == 0:
return 0
elif numbers[middle-1] < x:
return middle
elif numbers[middle-1] >= x:
right = middle-1
elif numbers[middle] < x:
left = middle+1
return None
def find_last_less(numbers, x):
left, right = 0, len(numbers)-1
while left <= right:
middle = left+((right-left) >> 1)
if numbers[middle] <= x:
if middle == len(numbers)-1:
return middle
elif numbers[middle+1] > x:
return middle
elif numbers[middle+1] <= x:
left = middle+1
elif numbers[middle] > x:
right = middle-1
return None
if __name__ == "__main__":
x = 5
print(numbers)
print("Find First", x, find_first(numbers, x))
print("Find Last", x, find_last(numbers, x))
print("Find First Greater", x, find_first_greater(numbers, x))
print("Find Last Less ", x, find_last_less(numbers, x))
|
4db4d468b7e4e8befd8b0d6078ac5049fe4d54ab | dpalma9/trainings | /katas_python/20181020/src/poker/hand.py | 2,945 | 3.578125 | 4 | # -*- coding: utf-8 -*-
from poker.card import Card
from poker.exceptions import DuplicatedCardError
class Hand(object):
def __init__(self,hand):
hand=hand.split(" ")
self.hand=hand
self.check_cards_in_hand()
self.rank()
def rank(self):
self.check_if_rep_cards()
self.high_card()
def check_cards_in_hand(self):
for card in self.hand:
card=Card(card)
def check_if_rep_cards(self):
hand_=[]
rep_hand=[]
for i in self.hand:
if i not in hand_:
hand_.append(i)
else:
if i not in rep_hand:
rep_hand.append(i)
if len(rep_hand) > 0:
raise DuplicatedCardError()
def high_card(self):
order=['2','3','4','5','6','7','8','9','J','Q','K','A']
#suits=['S','H','C','D']
new=[]
#hand=hand[0].split(" ")
for i in self.hand:
new.append(i[0])
ordenado=sorted(new, key=lambda new: order.index(new[0]))
high=ordenado[len(ordenado)-1]
for i in self.hand:
if high == i[0]:
highC=i
return highC
# class DuplicatedError(Exception):
# pass
# def Hand(hand):
# # TO DO
# #for i in len(hand):
# # Check_card(hand[i].split(" "))
# hand1=hand[0].split(" ")
# hand2=hand[1].split(" ")
# Check_card(hand1)
# Check_card(hand2)
# #print ("Hand1: " + str(hand1))
# #print ("Hand2: " + str(hand2))
# if card_rep(hand1,hand2):
# print ("Jugada válida")
# print ("High Card: " + str(highCard(hand1)))
# else:
# print ("Mierda pa' ti, tramposo")
# def Check_card(hand):
# for card in hand:
# Card(card)
# def card_rep(hand1, hand2):
# rep=[i for i, j in zip(hand1,hand2) if i == j]
# hand_1=[]
# rep_hand_1=[]
# hand_2=[]
# rep_hand_2=[]
# for i in hand1:
# if i not in hand_1:
# hand_1.append(i)
# else:
# if i not in rep_hand_1:
# rep_hand_1.append(i)
# for i in hand2:
# if i not in hand_2:
# hand_2.append(i)
# else:
# if i not in rep_hand_2:
# rep_hand_2.append(i)
# if not rep_hand_1 and not rep_hand_2 and not rep:
# return True
# else:
# return False
# def highCard(hand):
# order=['2','3','4','5','6','7','8','9','J','Q','K','A']
# #suits=['S','H','C','D']
# new=[]
# #hand=hand[0].split(" ")
# for i in hand:
# new.append(i[0])
# ordenado=sorted(new, key=lambda new: order.index(new[0]))
# high=ordenado[len(ordenado)-1]
# for i in hand:
# if high == i[0]:
# highC=i
# return highC
#hand=['2D 2S 4Q 4K 4K','2D 2S 4Q 6K 4Q']
#Hand(hand)
#hand=["2S 3D 4D KH QD", "2H 4S 3H 7D 8D"]
#Hand(hand) |
dd9f17a68a3b5774e05f822f5bf11cae054a5609 | weshao/LeetCode | /321.拼接最大数.py | 2,483 | 3.53125 | 4 | #
# @lc app=leetcode.cn id=321 lang=python3
#
# [321] 拼接最大数
#
# https://leetcode-cn.com/problems/create-maximum-number/description/
#
# algorithms
# Hard (43.13%)
# Likes: 338
# Dislikes: 0
# Total Accepted: 21.9K
# Total Submissions: 50.9K
# Testcase Example: '[3,4,6,5]\n[9,1,2,5,8,3]\n5'
#
# 给定长度分别为 m 和 n 的两个数组,其元素由 0-9 构成,表示两个自然数各位上的数字。现在从这两个数组中选出 k (k <= m + n)
# 个数字拼接成一个新的数,要求从同一个数组中取出的数字保持其在原数组中的相对顺序。
#
# 求满足该条件的最大数。结果返回一个表示该最大数的长度为 k 的数组。
#
# 说明: 请尽可能地优化你算法的时间和空间复杂度。
#
# 示例 1:
#
# 输入:
# nums1 = [3, 4, 6, 5]
# nums2 = [9, 1, 2, 5, 8, 3]
# k = 5
# 输出:
# [9, 8, 6, 5, 3]
#
# 示例 2:
#
# 输入:
# nums1 = [6, 7]
# nums2 = [6, 0, 4]
# k = 5
# 输出:
# [6, 7, 6, 0, 4]
#
# 示例 3:
#
# 输入:
# nums1 = [3, 9]
# nums2 = [8, 9]
# k = 3
# 输出:
# [9, 8, 9]
#
#
from typing import List
# @lc code=start
class Solution:
def maxNumber(self, nums1: List[int], nums2: List[int], k: int) -> List[int]:
maxRes = []
for i in range(k+1):
j = k - i
newNums1 = self.topk(nums1, i)
newNums2 = self.topk(nums2, j)
mergeRes = self.merge(newNums1, newNums2)
if len(mergeRes) > len(maxRes):
maxRes = mergeRes
elif len(mergeRes) == len(maxRes):
maxRes = max(maxRes, mergeRes)
return maxRes
def merge(self, nums1, nums2):
i, j = 0, 0
nums = []
while i < len(nums1) and j < len(nums2):
if nums1[i:] > nums2[j:]:
nums.append(nums1[i])
i += 1
else:
nums.append(nums2[j])
j += 1
if i < len(nums1):
nums += nums1[i:]
else:
nums += nums2[j:]
return nums
def topk(self, nums, k):
stack = []
for i in range(len(nums)):
while stack and nums[i] > stack[-1] and len(nums) - i > k:
stack.pop()
k += 1
if k > 0:
stack.append(nums[i])
k -= 1
return stack
# @lc code=end
so = Solution()
ans = so.maxNumber([3, 4, 6, 5], [9, 1, 2, 5, 8, 3], 5)
print(ans)
|
f7e50e963a5ec6c11bf047a9b7e08e84b4b5deae | edlorencetti/Python-3 | /ex075.py | 529 | 4.03125 | 4 | num =(int(input('Digite o primeiro numero: ')),
int(input('Digite o segundo numero: ')),
int(input('Digite o terceiro numero: ')),
int(input('Digite o quarto numero: ')))
print(f'Vc digitou os numeros: {num}')
print(f'O valor 9 apareceu {num.count(9)} vezes')
if 3 in num:
print(f'O valor 3 apareceu na {num.index(3)+1} posicao')
else:
print('O valor 3 nao foi digitado em nenhuma posicao')
print('Os valores pares digitados foram :', end=' ')
for n in num:
if n % 2 == 0:
print(n, end=' ')
|
78eb149bf0078b29df0b388f8d58d85e885776b3 | Alyriant/pie | /dnd_char.py | 2,639 | 3.515625 | 4 | import heapq
import math
import random
import typing
NUM_STATS = 6
POPULATION_SIZE = 10_000_000
NUM_TO_FIND = 10
class Character:
def __init__(self):
self.stats = []
self.simple_weight = 0
self.rms_weight = 0
self.roll()
def roll(self):
for i in range(NUM_STATS):
s = random.randrange(1,7) + random.randrange(1,7) + random.randrange(1,7)
self.stats.append(s)
self.simple_weight += s
self.rms_weight += s**2
self.rms_weight = math.sqrt(self.rms_weight / NUM_STATS)
def print_stats(self, char_num):
s = self.stats
print(f"({char_num:3}) "
f"Str {s[0]:2} Int {s[1]:2} Wis {s[2]:2} Dex {s[3]:2} Con {s[4]:2} Chr {s[5]:2} "
f"Weight: {self.simple_weight/NUM_STATS:.1f} RMS: {self.rms_weight:.1f}")
def find_top_characters(num_total, num_to_find):
if num_total < num_to_find:
num_to_find = num_total
# priority queues of found character weights
pq = []
rpq = []
# dict of priority -> characters at that priority
found_pq = {}
found_rpq = {}
def add_character(char, weight, found_chars, pq):
if len(pq) == num_to_find and weight < pq[0]:
return #optimization
else:
char_set = found_chars.get(weight)
if char_set:
char_set.add(char)
else:
char_set = {char,}
found_chars[weight] = char_set
if len(pq) < num_to_find:
heapq.heappush(pq, weight)
elif pq[0] < weight:
removed = heapq.heapreplace(pq, weight)
found_chars.pop(removed)
def create_characters():
for i in range(num_total+1):
c = Character()
add_character(c, c.simple_weight, found_pq, pq)
add_character(c, c.rms_weight, found_rpq, rpq)
def print_characters(pq, found_chars, label):
pq.sort()
pq.reverse()
num_printed = 0
print(label)
for weight in pq:
for char in found_chars[weight]:
num_printed += 1
char.print_stats(num_printed)
if num_printed >= num_to_find:
break
create_characters()
print_characters(pq, found_pq, "Top characters by simple weight:")
print_characters(rpq, found_rpq, "Top RMS characters:")
if __name__ == "__main__":
find_top_characters(num_total=POPULATION_SIZE, num_to_find=NUM_TO_FIND)
|
f191ba454b3b2dc50632d90883b19a4fab148c8b | ShailChoksi/text2digits | /text2digits/text2digits.py | 6,179 | 3.828125 | 4 | from typing import List
from text2digits.tokens_basic import Token, WordType
from text2digits.rules import CombinationRule, ConcatenationRule
from text2digits.text_processing_helpers import split_glues, find_similar_word
class Text2Digits(object):
def __init__(self, similarity_threshold=1.0, convert_ordinals=True, add_ordinal_ending=False):
"""
This class can be used to convert text representations of numbers to digits. That is, it replaces all occurrences of numbers (e.g. forty-two) to the digit representation (e.g. 42).
Basic usage:
>>> from text2digits import text2digits
>>> t2d = text2digits.Text2Digits()
>>> t2d.convert("twenty ten and twenty one")
>>> 2010 and 21
:param similarity_threshold: Used for spelling correction. It specifies the minimal similarity in the range [0, 1] of a word to one of the number words. 0 inidcates that every other word is similar and 1 requires a perfect match, i.e. no spelling correction is performed with a value of 1.
:param convert_ordinals: Whether to convert ordinal numbers (e.g. third --> 3).
:param add_ordinal_ending: Whether to add the ordinal ending to the converted ordinal number (e.g. twentieth --> 20th). Implies convert_ordinals=True.
"""
self.similarity_threshold = similarity_threshold
if self.similarity_threshold < 0 or self.similarity_threshold > 1:
raise ValueError('The similarity_threshold must be in the range [0, 1]')
self.convert_ordinals = convert_ordinals
self.add_ordinal_ending = add_ordinal_ending
# Keeping the ordinal ending implies that we convert ordinal numbers
if self.add_ordinal_ending:
self.convert_ordinals = True
def convert(self, text: str) -> str:
"""
Converts all number representations to digits.
:param text: The input string.
:return: The input string with all numbers replaced with their corresponding digit representation.
"""
# Tokenize the input string by assigning a type to each word (e.g. representing the number type like units (e.g. one) or teens (twelve))
# This makes it easier for the subsequent steps to decide which parts of the sentence need to be combined
# e.g. I like forty-two apples --> I [WordType.Other] like [WordType.Other] forty [WordType.TENS] two [WordType.UNITS] apples [WordType.Other]
tokens = self._lex(text)
# Apply a set of rules to the tokens to combine the numeric tokens and replace them with the corresponding digit
# e.g. I [WordType.Other] like [WordType.Other] 42 [ConcatenatedToken] apples [WordType.Other] (it merged the TENS and UNITS tokens)
text = self._parse(tokens)
return text
def _lex(self, text: str) -> List[Token]:
"""
This function takes an arbitrary input string, splits it into tokens (words) and assigns each token a type corresponding to the role in the sentence.
:param text: The input string.
:return: The tokenized input string.
"""
tokens = []
conjunctions = []
for i, (word, glue) in enumerate(split_glues(text)):
# Address spelling corrections
if self.similarity_threshold != 1:
matched_num = find_similar_word(word, Token.numwords.keys(), self.similarity_threshold)
if matched_num is not None:
word = matched_num
token = Token(word, glue)
tokens.append(token)
# Conjunctions need special treatment since they can be used for both, to combine numbers or to combine other parts in the sentence
if token.type == WordType.CONJUNCTION:
conjunctions.append(i)
# A word should only have the type WordType.CONJUNCTION when it actually combines two digits and not some other words in the sentence
for i in conjunctions:
if i >= len(tokens) - 1 or tokens[i + 1].type in [WordType.CONJUNCTION, WordType.OTHER]:
tokens[i].type = WordType.OTHER
return tokens
def _parse(self, tokens: List[Token]) -> str:
"""
Parses the tokenized input based on predefined rules which combine certain tokens to find the correct digit representation of the textual number description.
:param tokens: The tokenized input string.
:return: The transformed input string.
"""
rules = [CombinationRule(), ConcatenationRule()]
# Apply each rule to process the tokens
for rule in rules:
new_tokens = []
i = 0
while i < len(tokens):
if tokens[i].is_ordinal() and not self.convert_ordinals:
# When keeping ordinal numbers, treat the whole number (which may consists of multiple parts, e.g. ninety-seventh) as a normal word
tokens[i].type = WordType.OTHER
if tokens[i].type != WordType.OTHER:
# Check how many tokens this rule wants to process...
n_match = rule.match(tokens[i:])
if n_match > 0:
# ... and then merge these tokens into a new one (e.g. a token representing the digit)
token = rule.action(tokens[i:i + n_match])
new_tokens.append(token)
i += n_match
else:
new_tokens.append(tokens[i])
i += 1
else:
new_tokens.append(tokens[i])
i += 1
tokens = new_tokens
# Combine the tokens back to a string (with special handling of ordinal numbers)
text = ''
for token in tokens:
if token.is_ordinal() and not self.convert_ordinals:
text += token.word_raw
else:
text += token.text()
if token.is_ordinal() and self.add_ordinal_ending:
text += token.ordinal_ending
text += token.glue
return text
|
c71c6583c8591d5c2293daa37ebc4305361b0c7d | yaserahmedn/Leetcode---May-30-Day-Challenge | /day24.py | 1,557 | 4.28125 | 4 | #Construct Binary Search Tree from Preorder Traversal
#Solution
#Return the root node of a binary search tree that matches the given preorder traversal.
#(Recall that a binary search tree is a binary tree where for every node, any descendant of node.left has a value < node.val, and any descendant of node.right has a value > node.val. Also recall that a preorder traversal displays the value of the node first, then traverses node.left, then traverses node.right.)
#It's guaranteed that for the given test cases there is always possible to find a binary search tree with the given requirements.
#Example 1:
#Input: [8,5,1,7,10,12]
#Output: [8,5,10,1,7,null,12]
# 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 bstFromPreorder(self, preorder: List[int]) -> TreeNode:
def makeTree(root, value):
if root:
if root.val>value:
if root.left:
makeTree(root.left,value)
else:
root.left=TreeNode(value)
else:
if root.right:
makeTree(root.right,value)
else:
root.right=TreeNode(value)
root=TreeNode(preorder[0])
for i in range(1,len(preorder)):
makeTree(root,preorder[i])
return root
|
19e69d15dcd426f7ae222cfc7c03f4e264afbca6 | xxbeam/leetcode-python | /answers/DeleteDuplicates.py | 1,830 | 3.671875 | 4 | # 82. 删除排序链表中的重复元素 II
import ListNode
class Solution:
def deleteDuplicates(self, head: ListNode.ListNode) -> ListNode.ListNode:
# 如果列表为空或者只有一个元素,直接返回
if not head or head.next is None:
return head
first = head
has_dup = False
head = head.next
# 排除头部重复数据
while head:
if first.val == head.val:
if not has_dup:
has_dup = True
head = head.next
continue
else:
if has_dup:
first = head
head = head.next
has_dup = False
else:
break
# 从头到尾都是重复的
if has_dup:
return None
# 如果第二个节点或者第三个节点为空 则返回
if not head or not head.next:
return first
node = first
sec = head
head = head.next
while head:
if sec.val == head.val:
if not has_dup:
has_dup = True
head = head.next
else:
if has_dup:
first.next = head
has_dup = False
else:
first = sec
sec = head
head = head.next
if has_dup:
first.next = None
return node
if __name__ == '__main__':
node1 = ListNode.ListNode(1)
node2 = ListNode.ListNode(2)
node3 = ListNode.ListNode(3)
node4 = ListNode.ListNode(3)
node5 = ListNode.ListNode(4)
node6 = ListNode.ListNode(4)
node7 = ListNode.ListNode(5)
node1.next = node2
node2.next = node3
|
7fef1d2e7b76b66403577fa23e79aa787323ebf2 | AvinciClub/python_lesson | /Jonathan/HW4/happybirthday.py | 293 | 3.78125 | 4 | #!/usr/bin/env python3
def singHappyBirthday(name):
print("Happy Brithday to you")
print("Happy Brithday to you")
print("Happy Brithday to %s. " %name)
print("Happy Brithday to you")
print(" ")
inputName = input ("Enter the name to sing happy birthday: ")
singHappyBirthday(inputName)
|
4a5e8eda453f32a36b33afb18e6bcbd7a47ad30a | Besij/Coffee_Machine | /Coffee Machine/task/machine/coffe_machine_with_classes.py | 4,959 | 4.125 | 4 | class Coffemachine:
running = False
money_inside = 550
water_inside = 400
milk_inside = 540
beans_inside = 120
cups_inside = 9
e_water = 250
e_beans = 16
e_price = 4
l_water = 350
l_milk = 75
l_beans = 20
l_price = 7
c_water = 200
c_milk = 100
c_beans = 12
c_price = 6
def __init__(self, money_inside, water_inside, milk_inside, beans_inside, cups_inside):
self.money_inside = money_inside
self.water_inside = water_inside
self.milk_inside = milk_inside
self.beans_inside = beans_inside
self.cups_inside = cups_inside
if not Coffemachine.running:
self.start()
def start(self):
self.running = True
print()
action = input("Write action (buy, fill, take, remaining, exit)\n")
if action == "buy":
self.buy()
elif action == "fill":
self.fill()
elif action == "take":
self.take()
elif action == "remaining":
self.remaining()
else:
self.exit()
def buy(self):
print()
choose = input("What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:\n")
if choose == "1":
if self.water_inside < self.e_water:
print("Sorry, not enough water!")
self.start()
elif self.beans_inside < self.e_beans:
print("Sorry, not enough coffee beans!")
self.start()
elif self.cups_inside < 1:
print("Sorry, not enough disposable cups!")
self.start()
else:
self.water_inside -= self.e_water
self.beans_inside -= self.e_beans
self.cups_inside -= 1
self.money_inside += self.e_price
print("I have enough resources, making you a coffee!")
self.start()
elif choose == "2":
if self.water_inside < self.l_water:
print("Sorry, not enough water!")
self.start()
elif self.beans_inside < self.l_beans:
print("Sorry, not enough coffee beans!")
self.start()
elif self.cups_inside < 1:
print("Sorry, not enough disposable cups!")
self.start()
elif self.milk_inside < self.l_milk:
print("Sorry, not enough milk!")
self.start()
else:
self.water_inside -= self.l_water
self.beans_inside -= self.l_beans
self.milk_inside -= self.l_milk
self.cups_inside -= 1
self.money_inside += self.l_price
print("I have enough resources, making you a coffee!")
self.start()
elif choose == "3":
if self.water_inside < self.c_water:
print("Sorry, not enough water!")
self.start()
elif self.beans_inside < self.c_beans:
print("Sorry, not enough coffee beans!")
self.start()
elif self.cups_inside < 1:
print("Sorry, not enough disposable cups!")
self.start()
elif self.milk_inside < self.c_milk:
print("Sorry, not enough milk!")
self.start()
else:
self.water_inside -= self.c_water
self.beans_inside -= self.c_beans
self.milk_inside -= self.c_milk
self.cups_inside -= 1
self.money_inside += self.c_price
print("I have enough resources, making you a coffee!")
self.start()
elif choose == "back":
self.start()
def fill(self):
add_water = int(input("Write how many ml of water do you want to add:\n"))
add_milk = int(input("Write how many ml of milk do you want to add:\n"))
add_beans = int(input("Write how many grams of coffee beans do you want to add:\n"))
add_cups = int(input("Write how many disposable cups do you want to add:\n"))
self.water_inside += add_water
self.milk_inside += add_milk
self.beans_inside += add_beans
self.cups_inside += add_cups
self.start()
def take(self):
print(f'I gave you ${self.money_inside}')
self.money_inside = 0
self.start()
def remaining(self):
print()
print(f'The coffee machine has:')
print(f'{self.water_inside} of water')
print(f'{self.milk_inside} of milk')
print(f'{self.beans_inside} of coffee beans')
print(f'{self.cups_inside} of disposable cups')
print(f'${self.money_inside} of money')
self.start()
def exit(self):
self.running = False
machine1 = Coffemachine(550, 400, 540, 120, 9)
|
4fe872405cdbea48c53b693864b4f70bb2f2b080 | Aasthaengg/IBMdataset | /Python_codes/p03407/s330898319.py | 120 | 3.515625 | 4 | l1 = input('').split()
a = int(l1[0])
b = int(l1[1])
c = int(l1[2])
if (a+b)>= c:
print('Yes')
else:
print('No') |
ebdb4611d8371587d6675b697d038a0e636ec64f | rowand7906/cti110 | /M5HW1_TestGrades_DANTEROWAN.py | 348 | 3.890625 | 4 | #M5HW1_TestGrades_DanteRowan
#June 27,2017
#CTI 110 M5HW1 Test Average And Grade
#Dante' Rowan
#This program displays a letter grade for each score and the average test score.
#run the code
for all in range(100, 90, 80, 70, 60):
print('Enter five test scores')
for all in range(A, B, C, D, F):
print('Enter five test scores')
|
f2d0327b85ebbf13d90dcc150c59c82c59f0b46e | emilyemorehouse/Python-Babies | /weather.py | 705 | 3.78125 | 4 | #! /usr/bin/env python3
import requests
from lxml import etree
""" Baby script to scrape the current weather."""
def get_etree(url):
urltext = requests.get(url).text
return etree.HTML(urltext)
def weather():
print ("Input the 3 character city symbol. Type 'exit' to quit.")
city = input().strip()
while city != "exit":
url = "http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=" + city
tree = get_etree(url)
current_temp_xpath = '//current_observation/temperature_string//text()'
current_temp = tree.xpath(current_temp_xpath)
print (current_temp)
city = input().strip()
if __name__ == '__main__':
weather()
|
3ace4594020f38b4ed61c9b2221a642c75ec1e66 | zerobell-lee/baekjoon-algorithm-study | /lcm.py | 356 | 3.625 | 4 | import sys
def lcm(a, b):
if b > a:
a, b = b, a
def gcd(a, b):
return a if b == 0 else gcd(b, a % b)
g = gcd(a, b)
return a * b // g
num = int(sys.stdin.readline())
result = ''
for i in range(num):
a, b = map(int, sys.stdin.readline().rstrip().split())
result += str(lcm(a,b)) + '\n'
sys.stdout.write(result) |
4b52c350f588550884997024046b68f0b7b2c0f3 | nunezisrael/Movie-Trailer-Website | /media.py | 966 | 3.65625 | 4 | import webbrowser
class Video():
"""This class defines what a video and also provides a method for playing a trailer of the video."""
def __init__(self, title, storyline, poster_image, trailer_youtube):
self.title = title
self.storyline = storyline
self.poster_image_url = poster_image
self.trailer_youtube_url = trailer_youtube
def showtrailer(self):
webbrowser.open(self.trailer_youtube_url)
class Movie(Video):
"""This is a child class of the Video class, it inherits all of the parent's class attributes with the addition of the attributes
CAST, RELEASE DATE AND DURATION"""
def __init__(self, title, storyline, poster_image, trailer_youtube, rating, cast, release_date, lenght):
Video.__init__(self, title, storyline, poster_image, trailer_youtube)
self.rating = rating
self.actors = cast
self.release_date = release_date
self.duration = lenght
|
c5ee6e53a7d5946089c3f127b0d6cab3837b8f09 | akimi-yano/python-stack | /python_fundamentals/for_loop_basic_1/for_loop_basic1.py | 1,203 | 4 | 4 | # 1.Basic - Print all integers from 0 to 150.
# for num in range (151):
# print(num)
# 2.Multiples of Five - Print all the multiples of 5 from 5 to 1,000
# for num in range (5, 1001, 5):
# print(num)
# 3.Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead.
# If divisible by 10, print "Coding Dojo".
# for num in range(1,101):
# if num%10==0:
# print("Coind Dojo")
# elif num%5==0:
# print("Coding")
# else:
# print(num)
# 4.Whoa. That Sucker's Huge - Add odd integers from 0 to 500,000, and print the final sum.
# sum = 0
# for num in range(500000):
# sum += num
# print(sum)
# 5.Countdown by Fours - Print positive numbers starting at 2018, counting down by fours.
# for num in range(2018,0,-4):
# print(num)
# 6.Flexible Counter - Set three variables: lowNum, highNum, mult. Starting at lowNum and going through highNum, print only the integers that are a multiple of mult.
# For example, if lowNum=2, highNum=9, and mult=3, the loop should print 3, 6, 9 (on successive lines)
# lowNum = 2
# highNum = 9
# mult = 3
# for num in range(lowNum, highNum+1):
# if num%mult ==0:
# print(num)
|
e58f2b2882a8aec2c5df8531c71b1fd13f8e6066 | MarlonVictor/pyRepo | /Aula02/at01.py | 293 | 4.03125 | 4 | ## Faça um programa que dado o valor da temperatura em graus FARENHEIT, calcular e escrever o valor da temperatura em graus CELSIUS.
F = int(input('Digite uma temperatura em graus FARENHEIT: '))
C = 5/9 * (F - 32)
print('{0} graus FARENHEIT é equivalente a {1} graus CELSIUS'.format(F, C)) |
f162aebd2dce58853e01f1102e4d796694d0747d | Andrew-C-Stoops/pandas-challenge | /Final_hereos_of_Pymoli.py | 8,894 | 3.515625 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
# In[2]:
import numpy as np
# In[3]:
pd.read_csv("Resources/purchase_data.csv")
# In[4]:
purchasedata_df = pd.read_csv("Resources/purchase_data.csv")
# In[5]:
purchasedata_df
# In[6]:
#
#Player Count
#Display the total number of players
total_players = len(purchasedata_df['SN'].value_counts())
Total_Players = pd.DataFrame({"Total Players": total_players}, index=[0])
Total_Players
# In[7]:
#Purchasing Analysis (Total)
#Run basic calculations to obtain number of unique items, average price, etc.
#Create a summary data frame to hold the results
#$Optional: give the displayed data cleaner formatting
#Display the summary data frame
unique_items = len(purchasedata_df['Item ID'].value_counts())
average_price = purchasedata_df['Price'].mean()
total_purchases = purchasedata_df['Item Name'].count()
total_revenue = purchasedata_df['Price'].sum()
purchasing_analysis = pd.DataFrame({"Number of Unique Items": [unique_items],
"Average Price": [average_price],
"Total Purchases": [total_purchases],
"Total Revenue": [total_revenue],
})
# In[8]:
purchasing_analysis = purchasing_analysis[["Number of Unique Items", "Average Price","Total Purchases", "Total Revenue"]]
# In[9]:
purchasing_analysis
# In[10]:
purchasing_analysis["Average Price"] = purchasing_analysis["Average Price"].map("${0:,.2f}".format)
purchasing_analysis["Total Revenue"] = purchasing_analysis["Total Revenue"].map("${0:,.2f}".format)
# In[11]:
purchasing_analysis
# In[12]:
#Gender Demographics¶
#Percentage and Count of Male Players
#Percentage and Count of Female Players
#Percentage and Count of Other / Non-Disclosed
gender_count_df = purchasedata_df.groupby("Gender")["SN"].nunique()
gender_count_df.head()
# In[13]:
gender_percentage_df = gender_count_df/573
gender_percentage_df.round(2)
gender_demographics = pd.DataFrame({"TOTAL COUNT": gender_count_df,
"TOTAL PERCENTAGE OF PLAYERS": gender_percentage_df})
gender_demographics["TOTAL PERCENTAGE OF PLAYERS"] = gender_demographics["TOTAL PERCENTAGE OF PLAYERS"].map("{:.2%}".format)
gender_demographics
# In[14]:
#Purchasing Analysis (Gender)
#Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. by gender
#Create a summary data frame to hold the results
#Optional: give the displayed data cleaner formatting
#Display the summary data frame
gender_df = purchasedata_df.groupby('Gender')
male_purchase_count = gender_df.count().Age.Male
female_purchase_count = gender_df.count().Age.Female
other_purchase_count = gender_df.count().Age["Other / Non-Disclosed"]
f_avg_purchase_price = gender_df.mean().Price.Female
m_avg_purchase_price = gender_df.mean().Price.Male
o_avg_purchase_price = gender_df.mean().Price["Other / Non-Disclosed"]
f_total_purchase_value = gender_df.sum().Price.Female
m_total_purchase_value = gender_df.sum().Price.Male
o_total_purchase_value = gender_df.sum().Price["Other / Non-Disclosed"]
purchasing_analysis = {
"Gender": ["Female", "Male", "Other / Non-Disclosed"],
"Purchase Count": [female_purchase_count, male_purchase_count, other_purchase_count],
"Average Purchase Price": [f_avg_purchase_price, m_avg_purchase_price, o_avg_purchase_price],
"Total Purchase Value": [f_total_purchase_value, m_total_purchase_value, o_total_purchase_value],}
purchasing_analysis_df = pd.DataFrame(purchasing_analysis).set_index("Gender")
purchasing_analysis_df['Average Purchase Price'] = purchasing_analysis_df['Average Purchase Price'].map('${0:,.2f}'.format)
purchasing_analysis_df['Total Purchase Value'] = purchasing_analysis_df['Total Purchase Value'].map('${0:,.2f}'.format)
purchasing_analysis_df
# In[15]:
#Age Demographics
#Establish bins for ages
#Categorize the existing players using the age bins. Hint: use pd.cut()
#Calculate the numbers and percentages by age group
#Create a summary data frame to hold the results
#Optional: round the percentage column to two decimal points
#Display Age Demographics Table
group_names=["<10", "10-14", "15-19", "20-24", "25-29", "30-34", "35-39", "40+"]
bins=[0,9,14,19,24,29,34,39,120]
purchasedata_df["Age Group"]=pd.cut(purchasedata_df["Age"],bins, labels=group_names)
group_age=purchasedata_df.groupby("Age Group")
age_total=group_age["SN"].count().rename("Total Count")
age_demographics_df=pd.DataFrame(age_total)
age_demographics_df["Percentage of Players"]=age_demographics_df["Total Count"]*100/age_demographics_df["Total Count"].sum()
age_demographics_df["Percentage of Players"]=age_demographics_df["Percentage of Players"].round(2)
age_demographics_df=age_demographics_df[["Percentage of Players", "Total Count"]]
age_demographics_df["Percentage of Players"] = age_demographics_df["Percentage of Players"].map("{:.2f}%".format)
age_demographics_df
# In[18]:
#Purchasing Analysis (Age)
#Bin the purchase_data data frame by age
#Run basic calculations to obtain purchase count, avg. purchase price, avg. purchase total per person etc. in the table below
#Create a summary data frame to hold the results
#Optional: give the displayed data cleaner formatting
#Display the summary data frame
bins=[0,9,14,19,24,29,34,39,120]
Age_ranges = ["<10", "10-14", "15-19", "20-24", "25-29", "30-34", "35-39", "40+"]
pd.cut(purchasedata_df["Age"], bins, labels = Age_ranges).head()
purchasedata_df["Age Range"] = pd.cut(purchasedata_df["Age"],bins,labels = Age_ranges)
group = purchasedata_df.groupby("Age Range")
sn_count = purchasedata_df.groupby(["Age Range"]).count()["Age"]
average_price = purchasedata_df.groupby(["Age Range"]).mean()["Price"]
total_purch_v = purchasedata_df.groupby(["Age Range"]).sum()["Price"]
table = pd.DataFrame({"Purchase Count": sn_count,
"Total Purchase Value": total_purch_v,
"Average Purchase Value": average_price, })
table["Average Purchase Value"] = table["Average Purchase Value"].map("${:.2f}".format)
table["Total Purchase Value"] = table["Total Purchase Value"].map("${:.2f}".format)
table
# In[20]:
#Top Spenders
#Run basic calculations to obtain the results in the table below
#Create a summary data frame to hold the results
#Sort the total purchase value column in descending order
#Optional: give the displayed data cleaner formatting
#Display a preview of the summary data frame
opurchase_data_df = pd.DataFrame(purchasedata_df)
gSNtopspendor_df = opurchase_data_df.groupby("SN")
analysis_df = pd.DataFrame(gSNtopspendor_df["Purchase ID"].count())
tpurchasevalueSN = gSNtopspendor_df["Price"].sum()
avg_purchase_price_SN = gSNtopspendor_df["Price"].mean()
dlr_avg_purchase_price_SN = avg_purchase_price_SN.map("${:,.2f}".format)
analysis_by_SPENDOR_df["Average Purchase Price"] = dlr_avg_purchase_price_SN
analysis_by_SPENDOR_df["Total Purchase Value"] = total_purchase_value_SN
SUM_SN_purchased_data_df = analysis_by_SPENDOR_df.rename(columns={"Purchase ID":"Purchase Count"})
TOP5_spendors_df=SUM_SN_purchased_data_df.sort_values("Total Purchase Value", ascending=False)
dlr_total_purchase_value_SN = total_purchase_value_SN.map("${:,.2f}".format)
TOP5_spendors_df["Total Purchase Value"] = dlr_total_purchase_value_SN
TOP5_spendors_df.head()
# In[28]:
#Most Popular Items¶
#Retrieve the Item ID, Item Name, and Item Price columns
#Group by Item ID and Item Name. Perform calculations to obtain purchase count, item price, and total purchase value
#Create a summary data frame to hold the results
#Sort the purchase count column in descending order
#Optional: give the displayed data cleaner formatting
#Display a preview of the summary data frame
pop_items=purchasedata_df[["Item ID", "Item Name", "Price"]]
pop_items_grp=pop_items.groupby(["Item ID", "Item Name"])
pop_count=pop_items_grp["Item ID"].count()
pop_totals=pop_items_grp["Price"].sum()
pop_price=pop_totals/pop_count
pop_df=pd.concat([pop_count, pop_price, pop_totals], axis=1)
pop_df.columns=["Purchase Count", "Item Price", "Total Purchase Value"]
sort_df=pop_df.sort_values("Purchase Count", ascending=False)
sort_df["Item Price"]=sort_df["Item Price"].map("${:,.2f}".format)
sort_df["Total Purchase Value"]=sort_df["Total Purchase Value"].map("${:,.2f}".format)
sort_df
# In[31]:
#Most Profitable Items
#Sort the above table by total purchase value in descending order
#Optional: give the displayed data cleaner formatting
#Display a preview of the data frame
profit_df=pop_df.sort_values("Total Purchase Value", ascending=False)
profit_df["Item Price"]=profit_df["Item Price"].map("${:,.2f}".format)
profit_df["Total Purchase Value"]=profit_df["Total Purchase Value"].map("${:,.2f}".format)
profit_df
# In[ ]:
|
c93517ea5cf74a110bbf85b656b008d86035db34 | projectman/algorithms | /bubble_sort.py | 1,379 | 3.625 | 4 | """
procedure bubbleSort( A : list of sortable items )
n = length(A)
repeat
swapped = false
for i = 1 to n-1 inclusive do
/* if this pair is out of order */
if A[i-1] > A[i] then
/* swap them and remember something changed */
swap( A[i-1], A[i] )
swapped = true
end if
end for
until not swapped
end procedure
"""
from random import sample
def random_list(max_num=50, length_l=10):
""" Create list of random chosen unical digits
from the range from 0 to max_num."""
res_list = sample(range(max_num), length_l)
return res_list
def bubble_sort(list_in):
""" Process list_in with bubble sort algorithm and return updated list."""
swapped = True
while swapped:
swapped = False # To know that swapp was happend
for idx in range(1, len(list_in)):
if list_in[idx-1] > list_in[idx]:
list_in[idx], list_in[idx-1] = list_in[idx-1], list_in[idx]
swapped = True
return list_in
def is_sorted(list_in):
""" Return True if list is sorted. """
sorted_l = list_in.sort()
print (list_in)
print (sorted_l)
print (sorted_l == list_in)
test = random_list()
print (test)
bubble_sort(test)
print (test)
print (is_sorted(test))
print (is_sorted(random_list()))
|
d444e21ca7ced50acc6b9a31f53de355e8885ce4 | wenboshi08/leetcode-everyday | /1740-FindDistanceinaBinaryTree.py | 1,136 | 3.84375 | 4 | # 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 findDistance(self, root: TreeNode, p: int, q: int) -> int:
def findLCA(node):
if not node:
return
if node.val == p or node.val == q:
return node
left = findLCA(node.left)
right = findLCA(node.right)
if left and right:
return node
return left or right
def distance(LCA, target):
distance = 0
queue = [LCA]
while queue:
next = []
for n in queue:
if n.val == target:
return distance
if n.left:
next.append(n.left)
if n.right:
next.append(n.right)
distance += 1
queue = next
LCA = findLCA(root)
return distance(LCA, p) + distance(LCA, q) |
6f453dd67875763447a31575a562cc5f8b84d685 | anhyonchul/python | /ch02/calk_age.py | 232 | 3.625 | 4 | #나이 계산 프로그램
currentYear = 2021
birthYear = int(input("태어난 연도를 입력하세요 : "))
age = currentYear - birthYear + 1
print("%d년에 태어난 당신의 나이는 %d세 입니다" % (birthYear, age))
|
8ae06544660bc8d6a9332fb7e641ccdcec6e86a6 | trofik00777/EgeInformatics | /probn/22.06/15.py | 289 | 3.65625 | 4 | def f(x, y, a):
return (2 * x + 3 * y != 72) or ((a > x) and (a > y))
for a in range(100):
fl = True
for x in range(100):
for y in range(100):
if not f(x, y, a):
fl = False
break
if fl:
print(a)
break
|
bf9f16bdebbb6c7739f4a82f7592f11df8d61d88 | alexisbdr/face_recognition | /face_rec/test.py | 4,476 | 3.734375 | 4 | #!/usr/bin/python
# The contents of this file are in the public domain. See LICENSE_FOR_EXAMPLE_PROGRAMS.txt
#
# This example shows how to use dlib's face recognition tool. This tool maps
# an image of a human face to a 128 dimensional vector space where images of
# the same person are near to each other and images from different people are
# far apart. Therefore, you can perform face recognition by mapping faces to
# the 128D space and then checking if their Euclidean distance is small
# enough.
#
# When using a distance threshold of 0.6, the dlib model obtains an accuracy
# of 99.38% on the standard LFW face recognition benchmark, which is
# comparable to other state-of-the-art methods for face recognition as of
# February 2017. This accuracy means that, when presented with a pair of face
# images, the tool will correctly identify if the pair belongs to the same
# person or is from different people 99.38% of the time.
#
# Finally, for an in-depth discussion of how dlib's tool works you should
# refer to the C++ example program dnn_face_recognition_ex.cpp and the
# attendant documentation referenced therein.
#
#
#
#
# COMPILING/INSTALLING THE DLIB PYTHON INTERFACE
# You can install dlib using the command:
# pip install dlib
#
# Alternatively, if you want to compile dlib yourself then go into the dlib
# root folder and run:
# python setup.py install
#
# Compiling dlib should work on any operating system so long as you have
# CMake installed. On Ubuntu, this can be done easily by running the
# command:
# sudo apt-get install cmake
#
# Also note that this example requires Numpy which can be installed
# via the command:
# pip install numpy
import sys
import os
import dlib
import glob
import cv2
import numpy as np
import math
from imutils import face_utils
def euclidean_distance(vector_x, vector_y):
if len(vector_x) != len(vector_y):
raise Exception('Vectors must be same dimensions')
return math.sqrt(sum((vector_x[dim] - vector_y[dim]) ** 2 for dim in range(len(vector_x))))
predictor_path = sys.argv[1]
face_rec_model_path = sys.argv[2]
# Load all the models we need: a detector to find the faces, a shape predictor
# to find face landmarks so we can precisely localize the face, and finally the
# face recognition model.
detector = dlib.get_frontal_face_detector()
sp = dlib.shape_predictor(predictor_path)
facerec = dlib.face_recognition_model_v1(face_rec_model_path)
cap = cv2.VideoCapture(0)
faces = []
# Now process all the images
while True:
ret, frame = cap.read()
cv2.imshow("input", frame)
# Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
img = frame[:, :, ::-1]
# Ask the detector to find the bounding boxes of each face. The 1 in the
# second argument indicates that we should upsample the image 1 time. This
# will make everything bigger and allow us to detect more faces.
dets = detector(img, 1)
print("Number of faces detected: {}".format(len(dets)))
# Now process each face we found.
for k, d in enumerate(dets):
print("Detection {}: Left: {} Top: {} Right: {} Bottom: {}".format(
k, d.left(), d.top(), d.right(), d.bottom()))
# Get the landmarks/parts for the face in box d.
shape = sp(img, d)
(x,y,w,h) = face_utils.rect_to_bb(d)
cv2.rectangle(frame, (x,y), (x+w, y+h), (0,0,255),1)
# Compute the 128D vector that describes the face in img identified by
# shape. In general, if two face descriptor vectors have a Euclidean
# distance between them less than 0.6 then they are from the same
# person, otherwise they are from different people. Here we just print
# the vector to the screen.
face_descriptor = facerec.compute_face_descriptor(img, shape)
match_found = False
for i, f in enumerate(faces):
if euclidean_distance(face_descriptor, f) < 0.6:
match_found = True
print("Found match with face: ", i)
cv2.putText(frame, str(i), (x + 6, y - 6), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), 1)
break
if not match_found:
faces.append(face_descriptor)
print("added new face, now have ", len(faces))
cv2.imshow("frame", frame)
cv2.waitKey(10)
|
6521d8dcb5e4b5ab0f760eda53916103490b89fe | prkpro/BST | /BST.py | 3,878 | 4.125 | 4 | # Binary Search Tree
class Node:
def __init__(self, val=None):
self.value = val
self.left = None
self.right = None
class BST:
def __init__(self):
self.root = None
def add(self, value):
"""
Insert value iterating through either child if exists
:param value:
:return:
"""
if self.root is None:
self.root = Node(value)
return
pos = self.root
while pos:
if value < pos.value:
if pos.left is not None:
pos = pos.left
else:
pos.left = Node(value)
return
elif value > pos.value:
if pos.right is not None:
pos = pos.right
else:
pos.right = Node(value)
return
else: # value already exists
return
def delete(self, value):
"""
Total of 3 scenarios :
1. When node is leaf
2. When node has either of child
3. When node have both of its children
:param value:
:return:
"""
prev = None
pos = self.root
while pos is not None and pos.value != value:
"""Iterating to the node to delete"""
prev = pos
if value < pos.value:
pos = pos.left
else:
pos = pos.right
if pos is None: return # return if tree was empty
if pos.left is None or pos.right is None:
"""Covering case 1 & 2 both"""
new_node = None
if pos.left is None: # checking if either child exists
new_node = pos.right
else:
new_node = pos.left
if prev is None: pos = new_node # if root node is value then making the only existing child as root
if pos == prev.left: # checking which pointer to unlink
prev.left = new_node
else:
prev.right = new_node
else:
"""Covering case 3"""
parent = None
tmp = pos.right # temporary subtree
while tmp.left is not None: # iterating to smallest node on the right subtree
parent = tmp
tmp = tmp.left
if parent is None: # if true than promote the right subtree
pos.right = tmp.right
else: # else promote the right subtree from left subtree
parent.left = tmp.right
pos.value = tmp.value # finally copy the node value (which was unlinked) to the deleted one
def inorder(self):
"""
Steps:
1. Append locations of nodes till left most child is reached
2. Append popped locations value and iterate to right child
3. Go to Step 1
:return:
"""
pos = self.root
tmp, bst = [], []
while True:
if pos is not None: # keep appending till end is reached on left most
tmp.append(pos) # appending location of nodes
pos = pos.left
elif tmp: # check if tmp list is not empty
pos = tmp.pop()
bst.append(pos.value)
pos = pos.right # covering the right child when exists
else: # when tmp list empty and right most child is reached
break
return str(bst)
def __str__(self):
return str(self.inorder())
def test():
bt = BST()
l = [6, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12]
for i in l:
bt.add(i)
print(bt)
if __name__ == "__main__":
test()
|
0a7c96690922b443f90ee92cf9a9316932553b65 | ClayPalmerOPHS/Y11-Python | /selection005.py | 453 | 3.90625 | 4 | #Selection005
#Clay Palmer
raining = str(input("Is it raining? (Yes/No) ")).lower()
if raining == 'yes':
windy = str(input("Is it windy? (Yes/No) ")).lower()
if windy == 'yes':
print("It is too windy for an umbrella")
elif windy == 'no':
print("Take an umbrella")
else:
print("Invalid input, restart questions.")
elif raining == 'no':
print("Enjoy your day")
else:
print("Invalid input, restart questions.")
|
c8ccd14895a57879ee51ad098f1cbe3f75d802a0 | thenickrj/Problem-Solving | /Distribute Candies.py | 793 | 4.0625 | 4 | # Distribute Candies
"""
Alice has n candies, where the ith candy is of type candyType[i].
Alice noticed that she started to gain weight, so she visited a doctor.
The doctor advised Alice to only eat n / 2 of the candies she has (n is always even).
Alice likes her candies very much, and
she wants to eat the maximum number of different types of candies while still following the doctor's advice.
Given the integer array candyType of length n,
return the maximum number of different types of candies she can eat if she only eats n / 2 of them
"""
class Solution:
def distributeCandies(self, candyType: List[int]) -> int:
n=len(candyType)//2
x=len(set(candyType))
if x<n:
return x
else:
return n
|
6386cc4ec830f86654e404037be56550f108e001 | AsyaAndKo/RTSlab1.1 | /lab1.py | 1,132 | 3.8125 | 4 | import numpy as np
import random
from math import sin
import matplotlib.pyplot as plt
# expected value
def expectation(x, N):
return np.sum(x)/N
# standard deviation
def dispersion(x, mx, N):
return np.sum((x - mx)**2)/N
def frequency(n, w):
return w - n * number
# values for 11 variant
n = 10
w = 1500
N = 256
number = w/(n - 1)
# frequency
w_values = [frequency(n, w) for n in range(n)]
harmonics = np.zeros((n, N))
resulted = np.array([])
# generating harmonics
for n in range(n):
amplitude = random.choice([i for i in range(-10, 10) if i != 0])
phi = random.randint(-360, 360)
for t in range(N):
harmonics[n, t] = amplitude * sin(w_values[n] * t + phi)
# this part is showing plots for all generated harmonics, we don't really need them but still
# for i in harmonics:
# plt.plot(i)
# plt.show()
# last harmony
for i in harmonics.T:
resulted = np.append(resulted, np.sum(i))
plt.figure(figsize=(20, 15))
plt.plot(resulted)
plt.grid(True)
plt.show()
mx = expectation(resulted, N)
dx = dispersion(resulted, mx, N)
print(f"Expected value: {mx}")
print(f"Deviation: {dx}")
|
d1fe9b218d4f4ba388797837146e63444093c638 | Rudresh17/GfG | /try.py | 365 | 3.59375 | 4 | cases=int(input(""))
for m in range(0,cases):
size=int(input(""))
results=[]
numbers=list(map(int, input (). split ()))
for a in range(1,size-1):
if(numbers[a]>numbers[a-1] and numbers[a]<numbers[a+1]):
results.append(numbers[a])
if(len(results)>0):
print(results[0])
else:
print("-1")
results.clear() |
5457412acee1ae989e7d2bac13caf331d09a847e | mnovak17/wojf | /lab02/sequence.py | 276 | 3.890625 | 4 | #sequence.py
#prints all squares down to 1 from a givenn number
# Mitch Novak
#1/7/09
def main():
start = eval(input("Enter a number:"))
print ("Squares from", start, "down to 1:")
for i in range(start, 1, -1):
print(i*i, ",", end = " ")
print ("1")
main() |
1adfeef3a61c6f8310feb6617a2eca522af5f2ca | allandelarosa/practice | /arrays-and-strings/integer-to-english-words/solution.py | 1,859 | 3.546875 | 4 | class Solution(object):
def numberToWords(self, num):
"""
:type num: int
:rtype: str
"""
# consider digits 3 at a time
# add hundreds to string if valid
# consider last two digits case by case
# - 100 > x >= 20: _-ty _
# - 20 > x >= 13: _-teen
# - 13 > x: just get names
# append thousand, million, or billion as necessary
if num == 0:
return 'Zero'
names = {
1: 'One ', 2: 'Two ', 3: 'Three ', 4: 'Four ', 5: 'Five ',
6: 'Six ', 7: 'Seven ', 8: 'Eight ', 9: 'Nine ',
10: 'Ten ', 11: 'Eleven ', 12: 'Twelve ',
}
teens = {
3: 'Thir', 4: 'Four', 5: 'Fif', 6: 'Six',
7: 'Seven', 8: 'Eigh', 9: 'Nine',
}
tys = {
2: 'Twen', 3: 'Thir', 4: 'For', 5: 'Fif',
6: 'Six', 7: 'Seven', 8: 'Eigh', 9: 'Nine'
}
groups = {0: '', 1: 'Thousand ', 2: 'Million ', 3: 'Billion '}
english = ''
group = 0
while num > 0:
trip = num % 1000
temp = ''
if trip > 99:
temp += names[trip // 100] + 'Hundred '
trip %= 100
if trip > 0:
if trip >= 20:
temp += tys[trip // 10] + 'ty '
trip %= 10
if trip > 0:
temp += names[trip]
elif trip >= 13:
temp += teens[trip % 10] + 'teen '
else:
temp += names[trip]
if temp:
temp += groups[group]
english = temp + english
group += 1
num //= 1000
return english.strip() |
70fe63de265dabbc48ab39c38cd0012dbb36b268 | paglenn/random | /python/538/heatfd.py | 1,811 | 3.59375 | 4 | # Program 8.1 Forward difference method for heat equation
# Input: space interval [xl,xr], time interval [yb,yt],
# number of space steps M, number of time steps N
# Output: array w such that w[i-1,j] approximates solution at
# (xl+i*(xr-xl)/M, yb+j*(yt-yb)/N) where 1 <= i <= M-1, 0 <= j <= N
# Example usage: w=heatfd(0.,1.,0.,1.,1,0,250)
import numpy as np
from numpy import *
def heatfd(xl=None, xr=None, yb=None, yt=None, M=None, N=None):
c = 1. # diffusion coefficient
h = (xr-xl)/M; k = (yt-yb)/N; m = M-1; n = N
sigma = c*k/(h*h)
a = (1-2*sigma)*diag(ones(m),k=0) + sigma*diag(ones(m-1),k=-1) + sigma*diag(ones(m-1),k=+1)
lside = l(linspace(yb,yt,N+1)); rside = r(linspace(yb,yt,N+1))
w = empty([m,N+1]) # initialize array w
w[:,0] = f(linspace(xl+h,xl+m*h,m)) # initial conditions
for j in range(0,N):
w[:,j+1] = dot(a,w[:,j]) + sigma*hstack([lside[j],zeros(m-2),rside[j]])
return w
def f(x=None):
u = (sin(2*pi*x)) ** 2
return u
def l(t=None):
u = 0*t
return u
def r(t=None):
u = 0*t
return u
xl=0.; xr=1.; yb=0.; yt=1.; M=10; N=250
w = heatfd(xl,xr,yb,yt,M,N)
print 'w=',w
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = Axes3D(fig)
xvals = linspace(xl,xr,M+1,endpoint=True)
yvals = linspace(yb,yt,N+1,endpoint=True)
X = empty([M+1,N+1])
Y = empty([M+1,N+1])
W = empty([M+1,N+1])
for j in range(N+1):
X[:,j] = xvals
for i in range(M+1):
Y[i,:] = yvals
for i in range(1,M):
for j in range(N+1):
W[i,j] = w[i-1,j]
W[0,:]=l(yvals)
W[M,:]=r(yvals)
ax.plot_wireframe(X, Y, W, rstride=1, cstride=1)
plt.show()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.