blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
bff790e5a9b5828431838523c0d22b350f3978a0 | PatZino/CADE_Project | /random_samples.py | 781 | 3.65625 | 4 | import numpy as np
from numpy import array
A = array([[1, 3, 0], [3, 2, 0], [0, 2, 1], [1, 1, 4], [3, 2, 2], [0, 1, 0], [1, 3, 1], [0, 4, 1], [2, 4, 2],
[3, 3, 1]])
idx = np.random.randint(10, size=3)
print("idx: ", idx, "\n")
print("A[idx, :] : ", A[idx, :])
print("A.shape: ", A.shape)
print("A[np.random.randint(A.shape[0], size=2), :] : ", A[np.random.randint(A.shape[0], size=2), :])
print("A[np.random.choice(A.shape[0], 2, replace=False), :] : ", A[np.random.choice(A.shape[0], 2, replace=False), :])
"""
def all_even():
n = 0
while True:
yield n
n += 2
for a in all_even():
print("even number: ", a)
"""
def squares():
for number in range(10):
yield number ** 2
for a in squares():
print("squares: ", a)
|
fd9f18e70413a127bbc081b749f271407a5fb1ff | ronicst/advpyDec2020 | /interactions.py | 335 | 4.0625 | 4 | import sys
# sys.path.append() # we could add extra places for python to look
entry = input('Enter name and age ') # assume a comma
fn, age = entry.split(', ')
if not fn.isalpha():
print(f'{fn} needs to be alphabetic')
sys.exit(-1)
if not age.isdigit():
print(f'{age} needs to be numeric')
sys.exit(-1)
print(fn, age)
|
310630a2d5e42b7ee88868f259a79044d9c90faf | ChiragSinghai/450-Questions | /Chirag/Matrix/spiral matrix.py | 744 | 3.6875 | 4 | def spiral(L):
r=len(L)
if r==0:
return 0
c=len(L[0])
row=column=0
while row<r and column<c:
for i in range(column,c):
print(L[row][i],end=' ')
row+=1
for i in range(row,r):
print(L[i][c-1],end=' ')
c-=1
if not(row<r and column<c):
break
if row<r:
for i in range(c-1,column-1,-1):
print(L[r-1][i],end=' ')
r-=1
if column<c:
for i in range(r-1,row-1,-1):
print(L[i][column],end=' ')
column+=1
if __name__=='__main__':
L=[[1,2,3,4,5],
[14,15,16,17,6],
[13,20,19,18,7]]
#[12,11,10,9,8]]
spiral(L)
|
115b1156793dbf505ebebd60ec0d1931fc820740 | N-a-n-a/shiyanlou-code | /jump7.py | 144 | 3.75 | 4 | a=0
int(a)
while a <= 100:
a += 1
if a%10 == 7 or a%7 == 0 or a//10 == 7:
continue
if a == 101:
break
print(a)
|
bb54272543ab426c8c34bbbe2703558a13217285 | sheilapaiva/LabProg1 | /Unidade4/classifica_letra/classifica_letra.py | 394 | 3.671875 | 4 | # coding: utf-8
# Aluna: Sheila Maria Mendes Paiva
# Matrícula: 118210186
# Unidade 4 Questão: Classifica Letra
palavra = raw_input()
for i in range(len(palavra)):
letra = palavra[i]
if letra == "a" or letra == "e" or letra == "i" or letra == "o" or letra == "u" or letra == "A" or letra == "E" or letra == "I" or letra == "O" or letra == "U":
print "<%s> sim" % letra
else:
print "<%s> nao" % letra
|
bf5a8bcf168a41d61ae97573df52de22c698e4ff | OhenebaAduhene/globalcode-classbook2019 | /even_list.py | 131 | 3.71875 | 4 | def even_list(x,y):
result = []
for i in range(x,y):
if i%2==0:
result.append(i)
return result |
8d24536c863727ff2fc516f339193e283e06b39d | uglyboxer/challenge_submissions | /compress_challenge_cole.py | 1,303 | 3.84375 | 4 | """ Written by Cole Howard
Takes a string of characters and compresses them if possible
"""
import sys
def compress_string(str1):
"""Take a string
return the string or a compressed one
"""
new_string = ""
for i in str1:
a = [i, str1.count(i)]
if str1.count(i) > 2 and i not in new_string:
new_string += (i + str(a[1]))
elif a[1] > 2 and i in new_string:
pass
else:
new_string += i
return new_string
def break_string(str1):
"""Takes string
returns list of strings, broken by like
"""
i, j = 1, 0
letter_strs = [str1[0]]
while i < len(str1):
if str1[i] == str1[i-1]:
letter_strs[j] += str1[i]
else:
letter_strs.append(str1[i])
j += 1
i += 1
return letter_strs
def full_compress(str1):
"""Takes a string
returns it compressed as new string if possible
"""
lst = break_string(str1)
answer_lst = [compress_string(i) for i in lst]
answer = "".join(answer_lst)
print(answer)
return answer
if __name__ == '__main__':
assert compress_string('AAA') == 'A3'
assert break_string('AAABAAA') == ['AAA', 'B', 'AAA']
assert full_compress('AABBAA') == 'AABBAA'
full_compress(sys.argv[1])
|
d531376d79516b07afb0109c98c441fbd200e545 | lmun/competitiveProgramingSolutions | /kattis/judgingmoose.py | 157 | 3.734375 | 4 | from math import *
x,y=map(int,input().split())
eve=""
if x==y:
if x==0:
print("Not a moose")
exit(0)
eve="Even"
else:
eve="Odd"
print(eve,2*max(x,y)) |
5d91a8b0c663ef1e08ebd2c845dcecefdd45f521 | yorkypy/selise-intervie | /string/split.py | 336 | 3.859375 | 4 | def splt(str):
arr = list(str.split(' '))
print(arr)
splt('nina nvisd vsdnvs')
string = '''nin sinids ninvsd nindsvm\nnsdinsd insdvn nn\nnvdsinvs vsdv svd\nvnsd vsinv vnisnv vnisn'''
print(string.splitlines())
string = 'Hello 1 World 2'
vowels = ('a','e','i','o','u')
print(''.join([c for c in string if c not in vowels])) |
a671d9f69c9ebbc471b4254e75112f4bf03d58aa | KritoCC/Sword | /ex28.py | 7,175 | 4.34375 | 4 | # 习题二十八
# 上题我们学习了不少逻辑表达式,但是他们还有另一个更正式的名字——布尔逻辑表达式(boolean logic expression)。
# 它们无处不在非常重要,所以本题将要练习它们。
# 我们要做的是判断下列表达式的结果是 True 还是 False,并在 python 环境中验证结果:
# True and True
# False and True
# 1 == 1 and 2 == 1
# “test” == “test”
# 1 == 1 or 2 != 1
# True and 1 == 1
# False and 0 != 0
# True or 1 == 1
# “test” == “testing”
# 1 != 0 and 2 == 1
# “test” != “testing”
# “test” == 1
# not (True and False)
# not (1 == 1 and 0 != 1)
# not (10 == 1 or 1000 == 1000)
# not (1 != 10 or 3 == 4)
# not (“testing” == “testing” and “Zed” == “Cool Guy”)
# 1 == 1 and not (“testing” == 1 or 1 == 0)
# “chunky” == “bacon” and not (3 == 4 or 3 == 3)
# 3 == 3 and not (“testing” == “testing” or “Python” == “Fun”)
# 1. True and True
print('True and True' + '是真是假?我的答案是' + 'True')
print(True and True, "\n" * 2)
# 2. False and True
print('False and True' + '是真是假?我的答案是' + 'False')
print(False and True, "\n" * 2)
# 3. 1 == 1 and 2 == 1
print('1 == 1 and 2 == 1' + '是真是假?我的答案是' + 'False')
print(1 == 1 and 2 == 1, "\n" * 2)
# 4. "test" == "test"
print('"test" == "test"' + '是真是假?我的答案是' + 'True')
print("test" == "test", "\n" * 2)
# 5. 1 == 1 or 2 != 1
print('1 == 1 or 2 != 1' + '是真是假?我的答案是' + 'True')
print(1 == 1 or 2 != 1, "\n" * 2)
# 6. True and 1 == 1
print('True and 1 == 1' + '是真是假?我的答案是' + 'True')
print(True and 1 == 1, "\n" * 2)
# 7. False and 0 != 0
print('False and 0 != 0' + '是真是假?我的答案是' + 'False')
print(False and 0 != 0, "\n" * 2)
# 8. True or 1 == 1
print('True or 1 == 1' + '是真是假?我的答案是' + 'True')
print(True or 1 == 1, "\n" * 2)
# 9. "test" =="testing"
print('"test" == "testing"' + '是真是假?我的答案是' + 'False')
print("test" == "testing", "\n" * 2)
# 10. 1 != 0 and 2 == 1
print('1 != 0 and 2 == 1' + '是真是假?我的答案是' + 'False')
print(1 != 0 and 2 == 1, "\n" * 2)
# 11. "test" != "testing"
print('"test" != "testing"' + '是真是假?我的答案是' + 'True')
print("test" != "testing", "\n" * 2)
# 12. "test" == 1
print('"test" == 1' + '是真是假?我的答案是' + 'False')
print("test" == 1, "\n" * 2)
# 13. not (True and False)
print('not (True and False)' + '是真是假?我的答案是' + 'True')
print(not (True and False), "\n" * 2)
# 14. not (1 == 1 or 0 != 1)
print('not (1 == 1 or 0 != 1)' + '是真是假?我的答案是' + 'False')
print(not (1 == 1 or 0 != 1), "\n" * 2)
# 15. not (10 == 1 or 1000 == 1000)
print('not (10 == 1 or 1000 == 1000)' + '是真是假?我的答案是' + 'False')
print(not (10 == 1 or 1000 == 1000), "\n" * 2)
# 16. not (1 != 10 or 3 == 4)
print('not (1 != 10 or 3 == 4)' + '是真是假?我的答案是' + 'False')
print(not (1 != 10 or 3 == 4), "\n" * 2)
# 17. not ("testing" == "testing" and "Zed" == "Cool Guy")
print('not ("testing" == "testing" and "Zed" == "Cool Guy")' + '是真是假?我的答案是' + 'True')
print(not ("testing" == "testing" and "Zed" == "Cool Guy"), "\n" * 2)
# 18. 1 == 1 and not ("testing" == 1 or 1 == 0)
print('1 == 1 and not ("testing" == 1 or 1 == 0)' + '是真是假?我的答案是' + 'True')
print(1 == 1 and not ("testing" == 1 or 1 == 0), "\n" * 2)
# 19. "chunky" == "bacon" and not (3 == 4 or 3 == 3)
print('"chunky" == "bacon" and not (3 == 4 or 3 == 3)' + '是真是假?我的答案是' + 'False')
print("chunky" == "bacon" and not (3 == 4 or 3 == 3), "\n" * 2)
# 20. 3 == 3 and not ("testing" == "testing" or "Python" == "Fun")
print('3 == 3 and not ("testing" == "testing" or "Python" == "Fun")' + '是真是假?我的答案是' + 'False')
print(3 == 3 and not ("testing" == "testing" or "Python" == "Fun"), "\n" * 2)
# 比较运算符 名字
# == 等于
# != 不等于
# < 小于
# > 大于
# <= 小于等于
# >= 大于等于
# 例子
print(False and 1)
print(False and True)
print(True and 1)
print(True or 1)
print(False or 1)
print(True + True)
print('' or 5 or 0)
# 出现以上情况的原因是什么呢?
print(bool('')) # False
print(bool(0)) # False
# 所有变量的位操作都是通过强制转换成bool(布尔类型)实现的,并且表达式的值是从左到右第一个能够确定表达式的值的变量。
# ('' or 5 or 0) == (False or True or False),
# 当遇到第一个True的时候,表达式的值等于True这个变量(5)的值,并且不会再去管后面是什么,所以返回5.
# 原则
# 1. 在纯and语句中,如果每一个表达式都不是假的话,那么返回最后一个,因为需要一直匹配直到最后一个。
# 如果有一个是假,那么返回假
# 2. 在纯or语句中,只要有一个表达式不是假的话,那么就返回这个表达式的值。只有所有都是假,才返回假
# 3. 在or和and语句比较难表达,总而言之,碰到and就往后匹配,碰到or如果or左边的为真,那么就返回or左边的那个值,
# 如果or左边为假,继续匹配or右边的参数。
# (False or 1) 输出1
# (1 or False) 输出1
# (True or 1) 输出前者
# (1 or True) 输出前者
# (True and 1) 输出后者
# (1 and True) 输出后者
# (False and 1) 输出False
# (1 and False) 输出False
# 对python而言
# 其一, 在不加括号时候, and优先级大于or
# and运算有假则取假,如果没有假则取最后一个真(需要保证为真,则需要运算打最后一个真)
# or运算会取从左到右的第一个真,如果没有就取假
# 其二, x or y 的值只可能是x或y. x为真就是x, x为假就是y
# 第三, x and y 的值只可能是x或y. x为真就是y, x为假就是x
# 显然,
# 对于, 1 or 5 and 4: 先算5 and 4, 5为真, 值为4. 再算1 or 4, 1 为真,值为1
# 对于, (1 or 5) and 4: 先算1 or 5, 1为真, 值为1. 再算1 and 4, 1为真,值为4
# 在Python中,空字符串为假,非空字符串为真。非零的数为真。
# 数字和字符串之间、字符串之间的逻辑操作规律是:
# 对于and操作符:
# 只要左边的表达式为真,整个表达式返回的值是右边表达式的值,否则,返回左边表达式的值
print(2 and 1)
print(2 and '')
print(1 and 2)
print(0 and 1)
# 对于or操作符:
# 只要两边的表达式为真,整个表达式的结果是左边表达式的值。
print(1 or 2)
print(True or 1)
# 如果是一真一假,返回真值表达式的值
print('' or 5)
print(5 or '')
print(0 or 5)
print(5 or 0)
# 如果两个都是假,比如空值和0,返回的是右边的值。(空值或0)
print('' or False)
print(False or '')
print('' or 0)
print(0 or '')
# 总结一句话就是:无论操作符是哪个,最后的结果一定是按照计算顺序能最快判断出结果的那个表达式决定的
|
ea6de24be4a8583c0d581305f44da9bb982b3373 | arthurDz/algorithm-studies | /leetcode/palindrome_pairs.py | 1,188 | 3.90625 | 4 | # Given a list of unique words, find all pairs of distinct indices (i, j) in the given list, so that the concatenation of the two words, i.e. words[i] + words[j] is a palindrome.
# Example 1:
# Input: ["abcd","dcba","lls","s","sssll"]
# Output: [[0,1],[1,0],[3,2],[2,4]]
# Explanation: The palindromes are ["dcbaabcd","abcddcba","slls","llssssll"]
# Example 2:
# Input: ["bat","tab","cat"]
# Output: [[0,1],[1,0]]
# Explanation: The palindromes are ["battab","tabbat"]
def palindromePairs(self, words):
def is_palindrome(check):
return check == check[::-1]
words = {word: i for i, word in enumerate(words)}
valid_pals = []
for word, k in words.iteritems():
n = len(word)
for j in range(n+1):
pref = word[:j]
suf = word[j:]
if is_palindrome(pref):
back = suf[::-1]
if back != word and back in words:
valid_pals.append([words[back], k])
if j != n and is_palindrome(suf):
back = pref[::-1]
if back != word and back in words:
valid_pals.append([k, words[back]])
return valid_pals |
9509ba9d8c00023ebb546ffd0cdd7741ea92ff00 | lisboa-prog/Ocean_Exercicio_11_2020 | /Exercicio20.py | 2,197 | 3.953125 | 4 | """
Exercício 20
Nome: Números primos
Objetivo: Criar um for (loop) para detectar se um número é primo ou não.
Dificuldade: Avançado
Os números primos são aqueles números divisíveis APENAS por ele mesmo e por um.
Ele NÃO PODE ser divisível por qualquer número entre esses.
Por exemplo:
2 é primo pois ele é divisível apenas por 1 e por 2.
3 é primo pois ele é divisível apenas por 1 e por 3.
4 não é primo pois ele é divisível por 1, por 2 e por 4.
E assim por diante.
Para checar se um número é primo na programação, precisamos checar se ele é divisível por cada número que está entre
ele e 1, para isso, utilizamos o 'for'.
1 - Crie um programa que receba um número digitado pelo usuário e execute um 'for' pelo exato número de vezes do número
digitado.
2 - Para cada vez que o 'for' rodar, cheque se o número principal que foi digitado é divisível por aquele número que
está no for em questão.
Para saber se um número é divisível pelo outro, saiba que o resto da divisão inteira deve resultar em 0 (zero).
Dica: Crie uma variável chamada 'contador' e para cada vez que um número for divisível pelo outro, acrescente 1
(um) ao valor do contador, se ao final da execução do loop, o contador for igual a 2, significa que o número é
primo, caso contrário (3 ou mais) o número NÃO é primo.
Outra dica: Quando o range é utilizado, o for começa a ser executado a partir do índice 0, por tanto, o número
que você terá que começar a realizar a divisão é 1.
"""
def teste(numero=13):
lista = []
for indice in range(numero):
lista.append(indice)
lista = lista[2:]
contador = 0
for indice in lista:
if (numero % indice == 0) and (numero / numero == 1) and (numero / 1 == numero):
contador = +1
if contador == 0:
print(f"Numero {numero} é primo")
else:
print(f"Numero {numero} não é primo")
lista_numeros_usuario = []
lista = []
numero_digitado = int(input("Digite um numero: "))
for indice in range(numero_digitado):
lista_numeros_usuario.append(indice)
lista.append(indice+1)
print(f"\n{lista}")
teste(numero_digitado) |
533204143900d3529b6522961ca3e1129ccc19ea | tranngocanh91/python | /pythonfull/bai 4.py | 151 | 3.5625 | 4 | from math import pi
r= float(input('ban kinh hinh trong = '))
print(r)
print('dien tich hinh tron co ban kinh ' + str(r) + ' la '+ str(pi*r**2)) |
2c3418bdadbc70d6c003a945bec394771a9cbd67 | desamsetti/Python | /WhileLoop.py | 330 | 4.125 | 4 | x = 0
while x < 10:
print("X is currently: ",x)
x+=1
else:
print("All done")
x = 0
while x < 10:
print("X is currently: ",x)
print("X is still less than 10, adding 1 to x")
x+=1
if x==3:
print("Hey x equals 3!")
else:
print("Continuing...")
continue |
dae36bdb39f6fdabae07c6fae91134ac7e9b704c | NicolasBologna/frro-soporte-2019-27 | /practico_04/ejercicio01.py | 2,604 | 3.96875 | 4 | ## 1 Ejercicio Hacer un formulario tkinter que es una calculadora, tiene 2 entry para ingresar los valores V1 y V2.
## Y 4 botones de operaciones para las operaciones respectivas + , - , * , / ,
## al cliquearlos muestre el resultado de aplicar el operador respectivo en los V1 y V2 .
import tkinter as tk
calculadora = tk.Tk()
calculadora.title('Calculadora')
def pide_cerrar():
calculadora.destroy()
calculadora.quit()
calculadora.protocol("WM_DELETE_WINDOW", pide_cerrar)
label = tk.Label(calculadora, text="Primer Operando: ")
label2 = tk.Label(calculadora, text="Segundo Operando: ")
label.grid(column=1, row=1, padx=(50,50), pady=(10,10))
label2.grid(column=2, row=1, padx=(40,40), pady=(10,5))
evar1 = tk.DoubleVar()
evar1.set('')
evar2 = tk.DoubleVar()
evar2.set('')
res = tk.DoubleVar()
entry1 = tk.Entry(calculadora,textvariable = evar1)
entry2 = tk.Entry(calculadora,textvariable = evar2)
entry1.grid(column=1, row=2)
entry2.grid(column=2, row=2)
btn_mas = tk.Button(calculadora, text="+")
def sumar(event):
try:
res.set(evar1.get() + evar2.get())
evar1.set('')
evar2.set('')
print(res.get())
lbl_res['text'] = res.get() #permite cambiar atributos mientras está corriendo
except:
lbl_res['text'] = 'Error'
btn_mas.bind("<Button-1>", sumar)
btn_menos = tk.Button(calculadora, text="-")
def restar(event):
try:
res.set(evar1.get() - evar2.get())
evar1.set('')
evar2.set('')
print(res.get())
lbl_res['text'] = res.get()
except:
lbl_res['text'] = 'Error'
btn_menos.bind("<Button-1>", restar)
btn_por = tk.Button(calculadora, text="*")
def multiplicar(event):
try:
res.set(evar1.get() * evar2.get())
evar1.set('')
evar2.set('')
print(res.get())
lbl_res['text'] = res.get()
except:
lbl_res['text'] = 'Error'
btn_por.bind("<Button-1>", multiplicar)
btn_div = tk.Button(calculadora, text="/")
def dividir(event):
try:
res.set(evar1.get() / evar2.get())
evar1.set('')
evar2.set('')
print(res.get())
lbl_res['text'] = res.get()
except:
lbl_res['text'] = 'Error'
btn_div.bind("<Button-1>", dividir)
lbl_res = tk.Label(calculadora, text=res.get())
btn_mas.grid(column=3, row=2, padx=(5,5), pady=(10,5))
btn_menos.grid(column=4, row=2, padx=(5,5), pady=(10,5))
btn_por.grid(column=5, row=2, padx=(5,5), pady=(10,5))
btn_div.grid(column=6, row=2, padx=(5,5), pady=(10,5))
lbl_res.grid(column=3, row=3, padx=(5,5), pady=(10,5))
calculadora.mainloop()
|
a997b0f7ef118adba269f81b3931f850890dbe9e | keemsunguk/PythonTutorial | /quiz1-3.py | 520 | 3.546875 | 4 | def kthDigit(n, k):
if n < 0:
n = -1*n
#print(n)
res = 0
upper = (n//(10**(k+1)))*(10**(k+1))
lower = n-upper
res = lower//(10**k)
return res
def testKthDigit():
print("Testing kthDigit()...", end="")
assert(kthDigit(0,0) == 0)
assert(kthDigit(789, 0) == 9)
assert(kthDigit(789, 1) == 8)
assert(kthDigit(789, 2) == 7)
assert(kthDigit(789, 3) == 0)
assert(kthDigit(-1234, 3) == 1)
assert(kthDigit(-3, 1) == 0)
print("Passed!")
testKthDigit() |
308ff83c6f7dd87edb09b4aa07832b3d4194e40a | ShanEllis/pythonbook | /_build/jupyter_execute/content/05-classes/practice.py | 10,150 | 4.3125 | 4 | # Practice: Classes
In this set of practice problems, it's all about classes, really putting together everything discussed up to this point, including how to create our own classes of objects, with their own associated attributes and methods.
As for all practice sections, each question will include a handful of `assert` statements. After you write and execute the code to each question, each `assert` should "pass silently" (meaning: should give no output upon execution) indicating that you are on the right track. After you've written your code and run the `assert`s, you can always check your answers, as the answers to these questions are included in the "Answers" chapter of this book.
## Objects
**Objects Q1**. `isalnum()` is a string method that determines if all the characters in a string are alphanumeric (meaning letters or numbers: A-Z, a-z, 0-9).
Use the `isalnum()` method on two strings (of your choosing) below to create two variables:
- `true_var` | should store the value `True`
- `false_var` | should store the value `False`
Checks you can use to see if you're on the right track:
assert true_var
assert not false_var
**Objects Q2**. Here, `site_days` and `days_of_week` have been provided for you.
- `site_days`: is a (totally made up) list of days on which people received their vaccinations
- `days_of_week`: a tuple containing the days of the week
Note: `count()` is a list method that counts the number of appearances of a specified element in a list.
Using the `count()` method, code constructs discussed in class, and referencing the two variables provided, generate a dictionary:
- `days_summary` | whose keys are each of the days of the week in `days_of_week` and whose corresponding values are the number of times each day shows up in `site_days`.
Variables provided:
```python
site_days = ['M', 'M', 'M', 'M']
days_of_week = ('M', 'Tu', 'W', 'Th', 'F', 'Sa', 'Su')
```
assert list(days_summary.keys()) == ['M', 'Tu', 'W', 'Th',
'F', 'Sa', 'Su']
assert list(days_summary.values()) == [4, 0, 0, 0, 0, 0, 0]
**Objects Q3**. Here, import the `random` module so that you can use the `choice` function from the module. (Note: the `choice` function from the `random` module returns a single value from a collection at random.)
Use the `choice` function from the `random` module to randomly choose a value from `range(0,10)`.
Store the output from this operation in the variable `rand_int`.
Checks you can use to see if you're on the right track:
assert isinstance(rand_int, int)
assert rand_int in range(0,10)
## Classes
**Classes Q1**. Define a class `ClassRoster()` that meets the following specifications:
- has two instance attributes:
- `students`; initialized as an empty list
- `course`; which the user specifies when creating a `ClassRoster()` object
- a single method `add_student()`, which will have `pid` and `name` as arguments, and will add these two inputs as a dictionary with `pid` as the key and the student's `name` as the value to the `students` list each time the method is called
Checks you can use to see if you're on the right track:
assert my_course.course == 'COGS 18'
assert my_course.students == []
my_course.add_student(pid='A12345', name='Shannon')
my_course.add_student(pid='A56789', name='Josh')
assert my_course.students == [{'A12345':'Shannon'}, {'A56789': 'Josh'}]
**Classes Q2**. Define a class `ToDo()` to keep track of your to do list.
This should have a single instance attribute: `to_do`, which is initialized as an empty list.
It will then have two methods: `add_item` and `remove_item`.
`add_item()`:
- will have two parameters `item`, and `top` (`top` takes the default value `True`)
- if `top` is `True`:
the string in `item` will be added to the top of `to_do`:
- if `top` is not true:
the string it `item` will be added to the end of `to_do`
`remove_item()`:
- will have a single parameter `item`
- will remove the item specified from `to_do`
Note: there is a list method `insert()`, which operates in place to add a value to a list at the index specified with the general syntax `my_list.insert(index, item_to_add)`.
Checks you can use to see if you're on the right track:
my_todo_list = ToDo()
assert my_todo_list.to_do == []
my_todo_list.add_item('A')
my_todo_list.add_item('B')
assert my_todo_list.to_do == ['B','A']
my_todo_list.add_item('C', top=False)
assert my_todo_list.to_do == ['B','A', 'C']
my_todo_list.remove_item('A')
assert my_todo_list.to_do == ['B', 'C']
**Classes Q3**. For this question, let's create a class to celebrate the Lunar New Year!
Here, define a class `NewYear()`.
This class should have:
- **one class attribute**: `zodiac_signs` that stores the dictionary `zodiac_signs` specified below. This dictionary contains the zodiac sign as the key and the birth years that correspond to that sign.
- **one instance attribute**: `year` that takes the birth `year` as input from the user upon creation of a `NewYear` type object.
This class will also have a method `return_sign()`. This method should `return` (*not* just `print`) a string, similar to:
```
'You were born in the year of the Dragon!'
```
...where 'Dragon' corresponds to the key from the `zodiac_signs` corresponding to the value stored in the `year` attribute. (Be sure captitalization and punctuation match the string specified here. The only thing that should change is the last word in the string.)
For example `NewYear(year=2021).return_sign()` should return 'You were born in the year of the Ox!', since 2021 is a value in the `zodiac_signs` dictionary for the key 'Ox'.
Variable provided:
```python
zodiac_signs = {
'Ox' : [1937, 1949, 1961, 1973, 1985, 1997, 2009, 2021],
'Tiger' : [1938, 1950, 1962, 1974, 1986, 1998, 2010, 2022],
'Rabbit' : [1939, 1951, 1963, 1975, 1987, 1999, 2011, 2023],
'Dragon' : [1940, 1952, 1964, 1976, 1988, 2000, 2012, 2024],
'Snake' : [1941, 1953, 1965, 1977, 1989, 2001, 2013, 2025],
'Horse' : [1942, 1954, 1966, 1978, 1990, 2002, 2014, 2026],
'Goat/Sheep' : [1943, 1955, 1967, 1979, 1991, 2003, 2015, 2027],
'Monkey' : [1944, 1956, 1968, 1980, 1992, 2004, 2016, 2028],
'Rooster' : [1945, 1957, 1969, 1981, 1993, 2005, 2017, 2029],
'Dog' : [1946, 1958, 1970, 1982, 1994, 2006, 2018, 2030],
'Pig' : [1947, 1959, 1971, 1983, 1995, 2007, 2019, 2031],
'Rat' : [1936, 1948, 1960, 1972, 1984, 1996, 2008, 2020]
}
```
Checks you can use to see if you're on the right track:
dragon = NewYear(1988)
assert isinstance(dragon, NewYear)
assert dragon.year == 1988
assert dragon.return_sign() == 'You were born in the year of the Dragon!'
assert isinstance(dragon.zodiac_signs, dict)
assert 'Ox' in dragon.zodiac_signs.keys()
**Classes Q4**.
Part I.
For this question, imagine you want to create a video game with a handful of characters. You want this game to have a royal kingdom theme.
Here, define a class `Kingdom()`.
This class should have two instance attributes: `name` and `title`, which will be strings specifying the name and title of the character (in that order).
This class will also have a method `introduce()`. This method should `return` (*not* just `print`) a string, similar to:
```
'Hello, my name is Ferdinand, and I am a King.'
```
...where 'Ferdinand' corresponds to whatever is stored in `Kingdom()` object's `name` attribute is and 'King' corresponds to whatever is stored in the `Kingdom()` object's `title` attribute.
Checks you can use to see if you're on the right track:
queen = Kingdom('Elizabeth', 'Queen')
assert isinstance(queen, Kingdom)
assert queen.name == 'Elizabeth'
assert queen.title == 'Queen'
assert callable(queen.introduce)
assert isinstance(queen.introduce(), str)
Part II.
Generate a class called `CourtJester()`.
This object should inherit all attributes and methods from `Kingdom()`.
Additionally, the `CourtJester()` object should have:
- a class attribute `headwear`, storing the value `'fool's cap'`
- a method `tell_a_joke()` that should `return` a joke at random from the list provided below
(Note: You'll likely want to import from the `random` module here. Use of a function from that module will likely be helpful in `tell_a_joke()`.)
Variable provided:
```python
joke_list = ['A clown held the door open for me yesterday. I thought it was a nice jester',
'How does the court jester address the King of Ducks? Mal’Lard',
'What did the court jester call the balding crown prince? The Heir Apparent with no Hair Apparent',
'What do you call a joke made by using sign language? A jester']
```
Checks you can use to see if you're on the right track:
jester = CourtJester('Barney', 'Jester')
assert jester.headwear == "fool's cap"
assert jester.name == 'Barney'
assert jester.title == 'Jester'
joke_list = ['A clown held the door open for me yesterday. I thought it was a nice jester',
'How does the court jester address the King of Ducks? Mal’Lard',
'What did the court jester call the balding crown prince? The Heir Apparent with no Hair Apparent',
'What do you call a joke made by using sign language? A jester']
assert jester.tell_a_joke() in joke_list
**Classes Q5**. Generate a class called `StudentInfo`.
This class should have four *instance attributes*: `name`, `year`, `school`, and `proj_grade`.
This class must also have a single method: `follow_up`. This method should determine if `proj_grade` is 65 or below. If `proj_grade` is 65 or below, the method should return the name of the student as the key and their proj_grade as the value in a dictionary. (If the student has a grade above 65, this method should return an empty dictionary.)
Checks you can use to see if you're on the right track:
student1 = StudentInfo(name='Shannon', year='sophomore', school='UCSD', proj_grade=63)
student2 = StudentInfo(name='Josh', year='senior', school='UCSD', proj_grade=88)
# test attributes
assert student1.name == 'Shannon'
assert student1.school == 'UCSD'
assert student2.year == 'senior'
assert student2.proj_grade == 88
assert student1.follow_up() == {'Shannon': 63}
assert student2.follow_up() == {} |
e4c05bf23ddd9c3b9ddbf9130bf4fe15ced964ba | lovekeshmanhas/PythonWork | /PythonTut/tutorial26.py | 357 | 3.75 | 4 | # Time module
import time
t = time.time()
print(t)
i=0
while (i<5):
print("test performance")
i+=1
print("while loop time in", time.time() - t)
t2 = time.time()
for i in range(5):
# time.sleep(1)
print("test performance")
print("For loop time in", time.time() - t2)
localtime = time.asctime(time.localtime(time.time()))
print(localtime) |
a099891555ed7bda2b61bc9db2865cbc502bec0f | AayushSabharwal/SocialSimulations | /InfectionSimulation/utility.py | 1,475 | 3.671875 | 4 | from enum import Enum
from typing import Tuple
class InfectionState(Enum):
"""
Enum to represent possible states of an agent
"""
SUS = 1 # susceptible
INF = 2 # infected
REC = 3 # recovered (immune)
VAC = 4 # vaccinated (also immune)
def sqr_toroidal_distance(a: Tuple[int, int], b: Tuple[int, int], grid_width: int, grid_height: int):
"""
Function to get square of toroidal distance between two grid points
Parameters
----------
a, b : GridXY
Points between which sqr toroidal distance should be calculated
grid_width, grid_height: int
Grid dimensions
Returns
-------
float
Square of toroidal distance between a and b
"""
xdelta = abs(a[0] - b[0])
if xdelta > grid_width / 2:
xdelta = grid_width / 2 - xdelta
ydelta = abs(a[1] - b[1])
if ydelta > grid_height / 2:
ydelta = grid_height / 2 - ydelta
return xdelta**2 + ydelta**2
def toroidal_distance(a: Tuple[int, int], b: Tuple[int, int], grid_width: int, grid_height: int):
"""
Function to get toroidal distance between two grid points
Parameters
----------
a, b : Tuple[int, int]
Points between which toroidal distance should be calculated
grid_width, grid_height: int
Grid dimensions
Returns
-------
float
Toroidal distance between a and b
"""
return sqr_toroidal_distance(a, b, grid_width, grid_height) ** 0.5
|
dc390acbd29caf5a1a9ff350147b44a6e450eb66 | hpatel86/string_exercises | /count_words.py | 755 | 3.6875 | 4 | import sys
import string
from collections import defaultdict
DELIMITER = " "
ALPHABET = set([
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
'u', 'v', 'w', 'x', 'y', 'z'
])
def count_words(lines):
word_count = defaultdict(int)
for line in lines:
word = ""
for char in line:
if char == DELIMITER:
word_count[word] += 1
word = ""
else:
char = char.lower()
if char in ALPHABET:
word += char
if word != "":
word_count[word] += 1
return sorted(word_count.items(), key=lambda items: (-items[1], items[0]))
if __name__ == '__main__':
stream = sys.stdin
lines = sys.stdin.readlines()
for word, count in count_words(lines):
print word, count
|
7d481b424be7bce96fef0782f8725be293d11265 | changchingchen/leetcode | /725_SplitLinkedListInParts/solution.py | 1,001 | 3.65625 | 4 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def splitListToParts(self, root: ListNode, k: int) -> List[ListNode]:
new_list = [None] * k
if not root:
return new_list
size = 0
node = root
while node:
size += 1
node = node.next
quotient = size // k
remainder = size % k
node = root
for i in range(k):
sublist_size = quotient
if remainder > 0:
sublist_size += 1
remainder -= 1
size -= sublist_size
new_list[i] = node
while sublist_size > 1:
node = node.next
sublist_size -= 1
next_node = node.next
node.next = None
node = next_node
if size <= 0:
break
return new_list
|
e40cf69be89cc034bcf8f956e7cc99d673c9852e | chrisxue815/leetcode_python | /problems/test_0726.py | 2,433 | 3.671875 | 4 | import unittest
import collections
def _read_element(formula, i):
i += 1
while i < len(formula) and formula[i].islower():
i += 1
return i
def _read_num(formula, i):
num = ord(formula[i]) - ord('0')
i += 1
while i < len(formula) and formula[i].isdigit():
num = num * 10 + ord(formula[i]) - ord('0')
i += 1
return i, num
def _mul(stack, num):
brackets = 1
i = len(stack) - 2
while i >= 0:
if stack[i] == '(':
if brackets == 1:
break
brackets -= 1
i -= 1
elif stack[i] == ')':
brackets += 1
i -= 1
else:
stack[i] *= num
i -= 2
def _count(stack):
counter = collections.Counter()
i = 0
while i < len(stack):
item = stack[i]
if item == '(' or item == ')':
i += 1
continue
counter[item] += stack[i + 1]
i += 2
return ''.join(element + (str(num) if num > 1 else '') for element, num in sorted(counter.items()))
# O(n) time. O(n) space. Iteration.
class Solution:
def countOfAtoms(self, formula):
"""
:type formula: str
:rtype: str
"""
stack = []
i = 0
while i < len(formula):
ch = formula[i]
if ch.isupper():
hi = _read_element(formula, i)
stack.append(formula[i:hi])
stack.append(1)
i = hi
elif ch.isdigit():
hi, num = _read_num(formula, i)
stack[-1] = num
i = hi
elif ch == '(':
stack.append('(')
i += 1
else:
stack.append(')')
if i + 1 < len(formula) and formula[i + 1].isdigit():
hi, num = _read_num(formula, i + 1)
_mul(stack, num)
i = hi
else:
i += 1
return _count(stack)
class Test(unittest.TestCase):
def test(self):
self._test('H2O', 'H2O')
self._test('Mg(OH)2', 'H2MgO2')
self._test('K4(ON(SO3)2)2', 'K4N2O14S4')
self._test('Mg12', 'Mg12')
def _test(self, formula, expected):
actual = Solution().countOfAtoms(formula)
self.assertEqual(expected, actual)
if __name__ == '__main__':
unittest.main()
|
7a119268ab8b32a0d80328d07bae02aab69286f8 | TheNetRunner/filtermath-django | /filtermath.py | 1,426 | 3.5625 | 4 | from django import template
register = template.Library()
@register.filter(name='intconvertion')
def convert_to_int(number):
return int(number)
@register.filter(name='floatconvertion')
def convert_to_int(number):
return float(number)
@register.filter(name='add')
def add(number_one, number_two):
return number_one + number_two
@register.filter(name='subtract')
def subtract(number_one, number_two):
return number_one - number_two
@register.filter(name='multiply')
def multiply(number_one, number_two):
return number_one * number_two
@register.filter(name='divide')
def divide(numerator, denominator):
return numerator / denominator
# Returns the remainder
@register.filter(name='modulus')
def modulus(numerator, denominator):
return numerator % denominator
# The base is the large number or the number that is being multiplied lots of times
# The exponent is the small number or the number of times the base is being multiplied
@register.filter(name='exponent')
def power_of(base, exponent):
return base ** exponent
@register.filter(name='floordivision')
def floor_division(numerator, denominator):
return numerator // denominator
# This rounds a floating point number to the number of digits you set in the digits
@register.filter(name='round')
def round_num(number, digits):
return round(number, digits)
|
7b8bbfde106271dc0721a5b3c200922b99326c66 | qmnguyenw/python_py4e | /geeksforgeeks/python/medium/15_15.py | 2,803 | 4.5 | 4 | Python | Get all substrings of given string
There are many problems in which we require to get all substrings of a string.
This particular utility is very popular in competitive programming and having
shorthands to solve this problem can always be handy. Let’s discuss certain
ways in which this problem can be solved.
**Method #1 : Using list comprehension + string slicing**
The combination of list comprehension and string slicing can be used to
perform this particular task. This is just brute force method to perform this
task.
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Get all substrings of string
# Using list comprehension + string slicing
# initializing string
test_str = "Geeks"
# printing original string
print("The original string is : " + str(test_str))
# Get all substrings of string
# Using list comprehension + string slicing
res = [test_str[i: j] for i in range(len(test_str))
for j in range(i + 1, len(test_str) + 1)]
# printing result
print("All substrings of string are : " + str(res))
---
__
__
**Output :**
> The original string is : Geeks
> All substrings of string are : [‘G’, ‘Ge’, ‘Gee’, ‘Geek’, ‘Geeks’, ‘e’,
> ‘ee’, ‘eek’, ‘eeks’, ‘e’, ‘ek’, ‘eks’, ‘k’, ‘ks’, ‘s’]
**Method #2 : Usingitertools.combinations()**
This particular task can also be performed using the inbuilt function of
combinations, which helps to get all the possible combinations i.e the
substrings from a string.
__
__
__
__
__
__
__
# Python3 code to demonstrate working of
# Get all substrings of string
# Using itertools.combinations()
from itertools import combinations
# initializing string
test_str = "Geeks"
# printing original string
print("The original string is : " + str(test_str))
# Get all substrings of string
# Using itertools.combinations()
res = [test_str[x:y] for x, y in combinations(
range(len(test_str) + 1), r = 2)]
# printing result
print("All substrings of string are : " + str(res))
---
__
__
**Output :**
> The original string is : Geeks
> All substrings of string are : [‘G’, ‘Ge’, ‘Gee’, ‘Geek’, ‘Geeks’, ‘e’,
> ‘ee’, ‘eek’, ‘eeks’, ‘e’, ‘ek’, ‘eks’, ‘k’, ‘ks’, ‘s’]
Attention geek! Strengthen your foundations with the **Python Programming
Foundation** Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures
concepts with the **Python DS** Course.
My Personal Notes _arrow_drop_up_
Save
|
606429528517e46cb10a651b388eb0b4a85b7f37 | Rony82012/Python_proj | /sorting/binarysearch.py | 414 | 3.890625 | 4 | def binarysearch(alist, num):
if len(alist) == 0:
return False
else:
midpoint = len(alist)//2
if alist[midpoint] == num:
return True
else:
if num<alist[midpoint]:
return binarysearch(alist[:midpoint],num)
else:
return binarysearch(alist[midpoint+1:],num)
testlist = [90, 11, 32, 28, 13, 47, 19, 2, 22,]
print(binarysearch(sorted(testlist), 3))
print(binarysearch(sorted(testlist), 13)) |
e102891436604d12ebaab57a81ab34c57d1848a6 | fabianr8a/ProyectosOperacionalYNumericos | /Proyectos/Juan_Buendia-Fernanda_Toloza-David_Paez/Código RK/RK4-SegundaOpcion.py | 599 | 3.53125 | 4 | #Implementación del método RK4 y algunos casos de salida
import numpy as np
import matplotlib.pyplot as plt
def test1(x, y): # dy/dx = x^2 - 3y
return x**2 - 3*y
def f(x, y): #dy/dx = y - x^2 +1
return y-x**2+10
def RK4(f, a, b, y0, h):
x = np.arange(a, b+h, h)
n = len(x)
y = np.zeros(n)
y[0] = y0
for i in range(0, n-1):
k1 = f(x[i], y[i])
k2 = f(x[i]+h/2, y[i]+k1*h/2)
k3 = f(x[i]+h/2, y[i]+k2*h/2)
k4 = f(x[i]+h, y[i]+k3*h)
w = y[i+1] = y[i]+(h/6)*(k1+2*k2+2*k3+k4)
plt.plot(x, y)
plt.show()
# dy/dx= y - x^2 +1, a=0, b=5, y0=1, h=0.01
RK4(f, 0, 5, 1, 0.01)
|
2322dc67b8d83ccca8ead34e578b318dff8d4b2e | venkateshmoganti/Python-Programes | /Task21.py | 166 | 3.90625 | 4 | # Exponent
def find_exponent(base, exp):
i = 1
result = 1
while i <= exp:
result *= base
i += 1
print(result)
find_exponent(23, 2)
|
825f08ce57335fde4fa43a13bd6e7381ed7a79b9 | SR0-ALPHA1/hackerrank-tasks | /ProjectEuler/005_smallest_multiple.py | 679 | 3.515625 | 4 | """
Task: Project Euler #5:
"""
def find_delims(n, a={}):
for i in range(2,n):
if n % i == 0:
if i not in a:
a[i] = 0
a[i] += 1
return find_delims(n/i, a)
if n not in a:
a[n] = 0
a[n] += 1
return a
def smallest_multiple(N):
i = 1
mltpl = 1
delims = {}
while i < N:
i += 1
i_delims = {}
i_delims = find_delims(i, {})
for j in i_delims:
if j not in delims or delims[j] < i_delims[j]:
delims[j] = i_delims[j]
for j in delims:
mltpl *= pow(j, delims[j])
return mltpl
print smallest_multiple(10)
|
8715937ea81e82dcbd55b71299ab195fc380ac8d | avinash3699/NPTEL-The-Joy-of-Computing-using-Python | /Week 11/Programming Assignment 3 Numbers.py | 395 | 4.15625 | 4 | # Programming Assignment-3: Numbers
'''
Question : Write a program, which will find all such numbers between m and n
(both included) such that each digit of the number is an even number.
'''
# Code
a=input().strip()
m,n=map(int,a.split(","))
l=[]
for i in range(m,n+1):
i=str(i)
for j in i:
if int(j)%2!=0:
break
else:
l.append(i)
print(*l,sep=",") |
411756724c7d1a3e8942c0eb1384b6fc46e8391e | upasek/python-learning | /string/string4.py | 250 | 3.859375 | 4 | #Write a Python function to get a string made of 4 copies of the last two characters of a specified string (length must be at least 2).
def char(string):
return string[-2:]*4
string = input("Input the word :")
print("new string :",char(string))
|
0192459cf9941d10841bc3f70eb89ce4734d11a0 | AlanRoMC/claseAlfas | /clase1.py | 812 | 3.921875 | 4 | '''
# Entrada de datos
nombre = input("Ingresa tú nombre: ")
edad = int(input("Ingresa tú edad: "))
print("Hola ", nombre, " tu edad es: ", edad)
print("Tú edad en 10 años será: ", (edad+10))'''
'''
# Variables globales y locales
x = "global"
def miFuncion():
x = "local"
global x
x = "CD"
print("Hola soy una Variable", x)
miFuncion()
print("Hola soy una Variable", x)
# Estructura de dato (for, while)
año = 2000
while(año < 2020):
print("Año: ", str(año))
año += 1
for variable in range(0,10):
print(variable)
string = "Hola Mundo"
for letra in string:
print(letra)
'''
'''
listas = [[1,2,3],[4,5,6],[7,8,9]]
string = ""
for lista in listas:
#print(lista)
for numero in lista:
#print(numero)
string += str(numero) + " "
print(string)
'''
|
b7fdd3728c3ee4cf8439eabe529e0cdf6c0b0390 | ReDI-School/redi-python-intro | /theory/Lesson6-Dictionaries/code/sets_operations.py | 866 | 4.34375 | 4 | # Lesson6: Sets
# source: code/sets_operations.py
# Input data
python_languages = ['russian', 'french', 'arabic', 'arabic', 'arabic', 'arabic', 'farsi']
java_languages = ['english', 'kurdish', 'arabic', 'arabic', 'french']
# How many different languages do we have in each class?
python_set = set(python_languages)
java_set = set(java_languages)
print('Python:', len(python_set), 'Java:', len(java_set))
# What are the languages spoken in both classes?
print('All languages:', python_set | java_set)
# What are common languages between the two classes?
print('Common languages:', python_set & java_set)
# What are the languages that are found in only one class (not in both)?
print('One-class languages:', python_set ^ java_set)
# What are languages found in Python class but not in Java class?
print('Python class specific languages:', python_set - java_set)
|
7966e38c11b6d1855f52be65f5738d51d11877dc | iryna-pak/Python_GB | /Lesson05_Teacher/Task1_Teacher.py | 542 | 4.25 | 4 | """
1. Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем.
Об окончании ввода данных свидетельствует пустая строка.
"""
input_str = input("Введите следующую строку: ")
with open("File", "a") as file:
while input_str:
file.write(input_str+'\n')
input_str = input("Введите следующую строку: ") |
77e7aa46bb65c41a572708e77e2f221f6cbab241 | rare-potato/wumpus | /Map.py | 10,082 | 3.78125 | 4 | ########################################################################
## PROBLEM : Create a text based game that is based off of Hunt the Wumpus
##
## ALGORITHM :
## 1. Magic
##
## ERROR HANDLING:
## Checks to see if the person has valid inputs
## Checks to see if the person attempts to go off of the map and stops them from doing so
##
## OTHER COMMENTS:
## Any special comments
##
########################################################################
"""File Requirements
class Map: manages the entire map, assigns values to cells, reports status of map cells
Data:
self.grid
Methods:
__init__(self)
onGrid(self, r, c)
offGrid(self, r, c)
reset(self)
isBreezy(self, r, c)
isSmelly(self, r, c)
isGlinty(self, r, c)
hasWumpus(self, r, c)
hasPit(self, r, c)
"""
""" Game facts:
Pits == 5 && != 0,0
Wumpus == 1 && != 0,0
5 <= Breeze <= 12
Gold == 1 && != 0,0
Glint == Gold
2 <= Stench <= 4
Ladder == 0, 0
25 total "squares"
"""
import random
#An Error used to catch if a player attempts to go off the map
class OffMapError(Exception):
def __init__(self):
Off_map = True
#Contains the values for each characteristic for the cells
class Cell(object):
def __init__(self):
self.hasWumpus = False
self.hasGold = False
self.hasPit = False
self.hasBreeze = False
self.hasStench = False
#Creates the play field and holds the information of each cell
class Map:
def __init__(self):
#Defines the Grid width
self.width = 5
self.height = 5
self.grid = {}
#creates the grid
for row in range(self.height):
for col in range(self.width):
self.grid[(row, col)] = Cell()
g_row = 0
g_col = 0
w_row = 0
w_col = 0
#generates the coordinates for the gold and the wumpus and then adds them to the grid.
while g_row == 0 and g_col == 0:
g_row = random.randint(0, 4)
g_col = random.randint(0, 4)
while w_row == 0 and w_col == 0:
w_row = random.randint(0,4)
w_col = random.randint(0,4)
self.grid[(g_row, g_col)].hasGold = True
self.grid[(w_row, w_col)].hasWumpus = True
#Generates the coordinates for the 5 pits.
pits_dict = {}
for pit in range(5):
p_row = 0
p_col = 0
while p_row == 0 and p_col == 0:
p_row = random.randint(0,4)
p_col = random.randint(0,4)
if not(p_row == 0) or not(p_col == 0):
if not((p_row,p_col) in pits_dict.keys()):
pits_dict[(p_row,p_col)] = pit
else:
p_row = 0
p_col = 0
#Takes the coordinates for the pits and adds them to the grid.
for pit in pits_dict.keys():
self.grid[pit].hasPit = True
self.stench_dict = {}
#Creates the coordinates for all possible points to have a stench
s_up = (w_row + 1, w_col)
s_down = (w_row - 1, w_col)
s_east = (w_row, w_col + 1)
s_west = (w_row, w_col - 1)
#Check to see if the points are in the area of the grid and if they are add them to the dictionary
if s_up in self.grid.keys():
self.stench_dict[s_up] = 1
if s_down in self.grid.keys():
self.stench_dict[s_down] = 1
if s_east in self.grid.keys():
self.stench_dict[s_east] = 1
if s_west in self.grid.keys():
self.stench_dict[s_west] = 1
#Add the points from the dictionary into the grid
for stench in self.stench_dict.keys():
self.grid[stench].hasStench = True
breezy_dict ={}
#Calculate all the possible locations for a breeze and check to see if they are on the graph
#Also does not add the breeze characteristic if it overlaps with a pit
for pit in pits_dict:
x_row, y_col = pit
b_up = (x_row + 1, y_col)
b_down = (x_row - 1, y_col)
b_east = (x_row, y_col + 1)
b_west = (x_row, y_col - 1)
if not(b_up in pits_dict.keys()):
if b_up in self.grid.keys():
breezy_dict[b_up] = 1
if not(b_down in pits_dict.keys()):
if b_down in self.grid.keys():
breezy_dict[b_down] = 1
if not(b_east in pits_dict.keys()):
if b_east in self.grid.keys():
breezy_dict[b_east] = 1
if not(b_west in pits_dict.keys()):
if b_west in self.grid.keys():
breezy_dict[b_west] = 1
#Add the hasBreeze attribute to all of the Cells that should have a Breeze
for breeze in breezy_dict.keys():
self.grid[breeze].hasBreeze = True
# r == row, c == col
def onGrid(self, r, c):
#Checks to see if the coordinates are on the grid
if (r,c) in self.grid.keys():
return True
def offGrid(self, r, c):
#Checks to see if the coordinates are not on the grid
if not((r,c) in self.grid.keys()):
raise OffMapError
def reset(self):
#Resets the grid
self.grid = {}
# creates the grid
for row in range(self.height):
for col in range(self.width):
self.grid[(row, col)] = Cell()
g_row = 0
g_col = 0
w_row = 0
w_col = 0
# generates the coordinates for the gold and the wumpus and then adds them to the grid.
while g_row == 0 and g_col == 0:
g_row = random.randint(0, 4)
g_col = random.randint(0, 4)
while w_row == 0 and w_col == 0:
w_row = random.randint(0, 4)
w_col = random.randint(0, 4)
self.grid[(g_row, g_col)].hasGold = True
self.grid[(w_row, w_col)].hasWumpus = True
# Generates the coordinates for the 5 pits.
pits_dict = {}
for pit in range(5):
p_row = 0
p_col = 0
while p_row == 0 and p_col == 0:
p_row = random.randint(0, 4)
p_col = random.randint(0, 4)
if not (p_row == 0) or not (p_col == 0):
if not ((p_row, p_col) in pits_dict.keys()):
pits_dict[(p_row, p_col)] = pit
else:
p_row = 0
p_col = 0
# Takes the coordinates for the pits and adds them to the grid.
for pit in pits_dict.keys():
self.grid[pit].hasPit = True
self.stench_dict = {}
# Creates the coordinates for all possible points to have a stench
s_up = (w_row + 1, w_col)
s_down = (w_row - 1, w_col)
s_east = (w_row, w_col + 1)
s_west = (w_row, w_col - 1)
# Check to see if the points are in the area of the grid and if they are add them to the dictionary
if s_up in self.grid.keys():
self.stench_dict[s_up] = 1
if s_down in self.grid.keys():
self.stench_dict[s_down] = 1
if s_east in self.grid.keys():
self.stench_dict[s_east] = 1
if s_west in self.grid.keys():
self.stench_dict[s_west] = 1
# Add the points from the dictionary into the grid
for stench in self.stench_dict.keys():
self.grid[stench].hasStench = True
breezy_dict = {}
# Calculate all the possible locations for a breeze and check to see if they are on the graph
# Also does not add the breeze characteristic if it overlaps with a pit
for pit in pits_dict:
x_row, y_col = pit
b_up = (x_row + 1, y_col)
b_down = (x_row - 1, y_col)
b_east = (x_row, y_col + 1)
b_west = (x_row, y_col - 1)
if not (b_up in pits_dict.keys()):
if b_up in self.grid.keys():
breezy_dict[b_up] = 1
if not (b_down in pits_dict.keys()):
if b_down in self.grid.keys():
breezy_dict[b_down] = 1
if not (b_east in pits_dict.keys()):
if b_east in self.grid.keys():
breezy_dict[b_east] = 1
if not (b_west in pits_dict.keys()):
if b_west in self.grid.keys():
breezy_dict[b_west] = 1
# Add the hasBreeze attribute to all of the Cells that should have a Breeze
for breeze in breezy_dict.keys():
self.grid[breeze].hasBreeze = True
def isBreezy(self, r, c):
#Checks to see if the coordinates have a Breeze
if self.grid[r,c].hasBreeze == True:
return True
else:
return False
def isSmelly(self, r, c):
#Checks to see if the cell is Smelly
if self.grid[r,c].hasStench == True:
return True
else:
return False
def isGlinty(self, r, c):
#Checks to see if the coordinates have the gold
if self.grid[r,c].hasGold == True:
return True
else:
return False
def removeGlint(self, r, c):
self.grid[r,c].hasGold = False
def hasWumpus(self, r, c):
#Checks to see if the coordinates have the Wumpus
if self.grid[r,c].hasWumpus == True:
return True
else:
return False
def hasPit(self, r, c):
#Checks the coordinates to see if it has a pit
if self.grid[r,c].hasPit == True:
return True
else:
return False
|
c7e6dcbeb97d8bc7dcd77a55b748d3621bbaf012 | Confuzerpy/checkio_solve | /home/to_encrypt.py | 419 | 3.96875 | 4 | from string import ascii_letters
alfavit = ascii_letters.lower()
alfavit = sorted(list({i for i in ascii_letters.lower()}))
def to_encrypt(text, delta=3):
text = text.lower()
shifr = ""
for letter in text:
if letter in alfavit:
ind = alfavit.index(letter)%len(alfavit)
shifr += alfavit[(ind + delta)%len(alfavit)]
else:
shifr += letter
return shifr
|
436b97fa4c02770501e1fbcbab44a5c47c6c8a75 | yuhao-lin007/Advent-of-Code-2020 | /Day 9/day_9.py | 909 | 3.875 | 4 | def get_valid_contiguous_set(numbers, total):
for length in range(2, len(numbers)+1):
for offset in range(len(numbers)-length+1):
contiguous_set = numbers[offset:offset+length]
if sum(contiguous_set) == total:
return contiguous_set
with open("input.txt", "r") as file:
numbers = list(map(int, file.read().split()))
preamble_length = 25
for i in range(len(numbers) - preamble_length):
previous_numbers = numbers[i:i+preamble_length]
total = numbers[i+preamble_length]
total_valid = False
for num1 in previous_numbers:
for num2 in previous_numbers:
if num1 + num2 == total:
total_valid = True
if not total_valid:
invalid_total = total
# Part 1
print("Part 1")
print(invalid_total, "is an invalid total!")
print()
# Part 2
print("Part 2")
contiguous_set = get_valid_contiguous_set(numbers, invalid_total)
print("Encryption Weakness:", min(contiguous_set) + max(contiguous_set)) |
82e636b934ce0075f61e58808d1889ee3d65489b | Jayendu/Chatbot | /chat.py | 788 | 3.8125 | 4 | print('Hey I am Chappie, A Simple Chatbot.')
name = input('So Whats your name? ')
print('Nice to meet you ' + name)
age = input('How old are you? ')
print("Ohh... Unfortunately I dont have any age... :)")
print('I was porgrammed by a boy called Jayendu...')
print('He made me for an experiment.')
interests = input('BTW are you interested in computers? ')
print('Oh then its good')
interest_areas = input('In what things are you interested in Computers? ')
print('Very well, then you could learn and program a more intelligent A.I. program like me.')
hardware = input('Are you interseted in Computer Hardware? ' + hardware)
print('Ohh... Thats good then')
print('By all the results I have collected from you I will give you a last summary of you... :)')
print(name + ' is ') |
a6e1b2c2c494bcc7371ab3eda952a7ba1ec4424a | pvolnuhi/CSC-225 | /Assign1/hexadecimal_tests.py | 598 | 3.53125 | 4 | #Learn more or give us feedback
# Tests operations on hexadecimal numbers.
# CSC 225, Assignment 1
# Given tests, Winter '20
import unittest
import hexadecimal as hx
class TestHexadecimal(unittest.TestCase):
def test01_binary_to_hex(self):
msg = "Testing basic binary-to-hex conversion"
self.assertEqual(hx.binary_to_hex("0000010100011010"), "0x051A", msg)
def test02_hex_to_binary(self):
msg = "Testing basic hex-to-binary conversion"
self.assertEqual(hx.hex_to_binary("0x051A"), "0000010100011010", msg)
if __name__ == "__main__":
unittest.main() |
b4e8d5574b158b0780f84f94ebd39c4feb6b6901 | ja95aricapa/holbertonschool-higher_level_programming | /0x0C-python-almost_a_circle/models/base.py | 2,656 | 3.984375 | 4 | #!/usr/bin/python3
"""
Base Class
"""
import json
class Base:
"""
Creates a class Base for do some operations
atributes:
*__nb_objects (int): The number of instance.
"""
__nb_objects = 0
def __init__(self, id=None):
"""
Initialize a Base object
parametters:
*self: the class itself
*id: the identification of the object
"""
if id is not None:
self.id = id
else:
Base.__nb_objects += 1
self.id = Base.__nb_objects
@staticmethod
def to_json_string(list_dictionaries):
"""
Static method that returns the JSON string representation
of list_dictionaries.
"""
if list_dictionaries is None or list_dictionaries == []:
return ("[]")
else:
return (json.dumps(list_dictionaries))
@classmethod
def save_to_file(cls, list_objs):
"""
Class method that writes the JSON string representation
of list_objs to a file.
"""
filename = cls.__name__ + ".json"
with open(filename, mode="w") as myfile:
if list_objs is None:
myfile.write("[]")
else:
list_convert = [list_.to_dictionary() for list_ in list_objs]
json_list = cls.to_json_string(list_convert)
myfile.write(json_list)
@staticmethod
def from_json_string(json_string):
"""
Static method that returns the list of the JSON string
representation json_string.
"""
if json_string is None or json_string == []:
return ([])
else:
return (json.loads(json_string))
@classmethod
def create(cls, **dictionary):
"""
Class method that returns an instance with all attributes
already set.
"""
if (cls.__name__ == "Rectangle"):
dummy = cls(2, 2)
elif (cls.__name__ == "Square"):
dummy = cls(4)
dummy.update(**dictionary)
return (dummy)
@classmethod
def load_from_file(cls):
"""
Class method that returns a list of instances
"""
try:
filename = cls.__name__ + ".json"
with open(filename, "r") as myfile:
obj_loaded = myfile.read()
content_for_list = cls.from_json_string(obj_loaded)
list = []
for object in content_for_list:
list.append(cls.create(**object))
return (list)
except FileNotFoundError:
return ([])
|
6548e0114773f33328f55812534c843f0302e6a2 | Deiarodrigues/programacao-orientada-a-objetos | /listas/lista-de-exercicio-05/questao-04.py | 133 | 3.703125 | 4 | def caracterie(x):
if x >0:
print("P")
elif x <=0:
print("N")
elemento=int(input())
y =caracterie(elemento)
|
497dec96a6b4761a9626e6e076f3fbebe2d1d021 | ralevn/Python_scripts | /PyCharm_projects_2020/Fundamentals/Exam_prep/pirates.py | 2,437 | 3.84375 | 4 | cities = {}
inp_city = input()
while inp_city != 'Sail':
city = inp_city.split('||')[0]
population = int(inp_city.split('||')[1])
gold = int(inp_city.split('||')[2])
if city not in cities:
cities[city] = [population, gold]
else:
cities[city][0] += population
cities[city][1] += gold
inp_city = input()
event = input()
while event != 'End':
if event.split('=>')[0] == 'Plunder':
town = event.split('=>')[1]
people = int(event.split('=>')[2])
p_gold = int(event.split('=>')[3])
if (cities[town][0] - people > 0) and (cities[town][1] - p_gold > 0):
cities[town][0] -= people
cities[town][1] -= p_gold
print(f'{town} plundered! {p_gold} gold stolen, {people} citizens killed.')
elif (cities[town][0] - people <= 0) and (cities[town][1] - p_gold > 0):
print(f'{town} plundered! {p_gold} gold stolen, {cities[town][0]} citizens killed.')
cities.pop(town)
print(f"{town} has been wiped off the map!")
elif (cities[town][0] - people > 0) and (cities[town][1] - p_gold <= 0):
print(f'{town} plundered! {cities[town][1]} gold stolen, {people} citizens killed.')
cities.pop(town)
print(f"{town} has been wiped off the map!")
elif (cities[town][0] - people <= 0) and (cities[town][1] - p_gold <= 0):
print(f'{town} plundered! {cities[town][1]} gold stolen, {cities[town][0]} citizens killed.')
cities.pop(town)
print(f"{town} has been wiped off the map!")
elif event.split('=>')[0] == 'Prosper':
town = event.split('=>')[1]
gold = int(event.split('=>')[2])
if gold < 0:
print('Gold added cannot be a negative number!')
event = input()
continue
else:
cities[town][1] += gold
print(f'{gold} gold added to the city treasury. {town} now has {cities[town][1]} gold.')
event = input()
if len(cities) > 0:
ordered_cities = sorted(cities.items(), key=lambda s: (-s[1][1], s[0]))
print(f'Ahoy, Captain! There are {len(cities)} wealthy settlements to go to:')
for t, i in ordered_cities:
print(f'{t} -> Population: {i[0]} citizens, Gold: {i[1]} kg')
else:
print("Ahoy, Captain! All targets have been plundered and destroyed!") |
c67c58824d068f8332b95d9e3fd33cf89a3aade9 | LorenzoVaralo/ExerciciosCursoEmVideo | /Mundo 3/Ex082.py | 829 | 3.890625 | 4 | #Crie um programa que vai ler varios numeros e colocar em uma lista.
# Depois disso crie duas listas extras que vão conter apenas os valores pares e os impares digitados, respectivamente.
# No final, mostre o conteudo das tres listas geradas.
cont = ''
lis = []
par = []
impar = []
while cont != 'N':
num = int(input('Digite um numero: '))
lis.append(num)
if num % 2 == 0:
par.append(num)
elif num % 2 == 1:
impar.append(num)
while True:
cont = str(input('Quer continuar? ')).upper().strip()[0]
if cont not in 'SN':
print('Erro! Valor invalido, tente novamente.')
else:
break
print(f'Você digitou os numeros: {lis}')
print(f'Os numeros pares digitados são: {par}')
print(f'Os numeros impares digitados são: {impar}') |
e6284175d4549ab95c315a9582619b76e6b6b44f | fjpolo/ThinkPython | /Code/ThinkPython_4_3.py | 1,264 | 4.1875 | 4 | from swampy.TurtleWorld import *
import math
"""
world = TurtleWorld()
bob = Turtle()
print(bob)
#
for i in range(200):
fd(bob, 2*i)
lt(bob)
#
wait_for_user()
"""
#
# square
#
def square(t, length):
for i in range(4):
fd(bob, length)
lt(bob)
#
# polyline
#
"""Draws n line segments with the given length and
angle (in degrees) between them. t is a turtle.
"""
def polyline(t, n, length, angle):
for i in range(n):
fd(t, length)
lt(t, angle)
#
# polygon
#
"""Draws a n sided polygon with the given length.
t is a turtle.
"""
def polygon(t, n, length):
angle = 360.0 / n
polyline(t, n, length, angle)
#
# circle
#
"""Draws a circle with radius r. t is a turtle."""
def circle(t, r):
arc(t, r, 360)
#
# arc
#
def arc(t, r, angle):
arc_length = 2 * math.pi * r * angle / 360
n = int(arc_length / 3) + 1
step_length = arc_length / n
step_angle = float(angle) / n
polyline(t, n, step_length, step_angle)
#
# Main
#
if __name__ == '__main__':
world = TurtleWorld()
bob = Turtle()
bob.delay = 0.01
#square(bob, 25)
#polygon(bob, 15, 100)
circle(bob, 50)
#arc(bob, 50, 180)
|
0a9379e73822632e09f954a9cd05d3e86a2ae35c | SApsalamov/psupyis202s | /les2/func2.py | 339 | 3.953125 | 4 | def sum(a, b=0): # b имеет значение по умолчанию
c = a + b
return c
print(sum(2, 3))
print(sum(2))
# args - список аргументов в порядке указания при вызове return args
# тип данных кортеж
def func1(*args):
return args
print(func1('ddd',111, 222, '4444')) |
891ba254bc5bbd92f8ca5cfe12eda121c4de577d | HarakaRisasi/python_code | /code_study/python_learn/010_1_class.py | 17,245 | 3.921875 | 4 | # -*- coding: utf-8 -*-
import os
os.system('cls' if os.name == 'nt' else 'clear')
# A class is a blueprint for objects
# one class for any number of objects of that type.
# Also call it an abstract data type.
# Interestingly, it contains no values itself,
# but it is like a prototype for objects.
# Многие объектно-ориентированные языки, такие как C++,
# Java и Python, используют классы для определения состояния, которое
# может храниться в объекте, и методов для изменения этого состояния.
# Если классы являются определениями состояния и методов, экземпляры
# являются воплощениями этих классов. Как правило, когда разработчик
# говорит об объектах, он имеет в виду экземпляры классов.
# Чтобы создать экземпляр класса str с именем b , используйте синтаксис
# строковых литералов Python:
b = 'I\'m a string'
print(b) #>> I'm a string
# Термин «литерал» в данном случае означает специальный синтаксис
# создания строк, встроенный в Python.
# Если программисты начнут обсуждать b , вы можете услышать самые
# разные термины.
# « b — это строка»,
# « b — это объект»,
# « b — это экземпляр строки»
# Прежде всего заметим, что классы не всегда необходимы в Python.
# Подумайте, нужно ли определять класс или же хватит функции (или группы функций).
# Класс может быть полезен для программного представления
# физических или концептуальных объектов.
# Понятия, являющиеся описаниями, — скорость, температура, среднее арифметическое, цвет
# — не являются хорошими кандидатами для классов.
# Если вы решили, что хотите моделировать что-либо с помощью класса,задайте себе следующие вопросы:
# У него есть имя?
# Имена классов записываются в «верблюжьем регистре»
# Какими свойствами он обладает?
# Присущи ли эти свойства всем экземплярам класса?
# А именно:
# Какие свойства являются общими для класса в целом?
# Какие из этих свойств уникальны для каждого экземпляра?
# Какие операции он выполняет?
num = 42
answer = str(num)
print(answer) #>> 42
print(type(answer)) #>> <class 'str'>
# class "Chair"
# Есть ли имя у моделируемой сущности? Да, «кресло».
# Среди свойств
# кресла можно выделить номер, вместимость, наличие планки безопасности и мягких сидений.
# Если погрузиться немного глубже,
# вместимость можно разбить на максимальную вместимость и текущую занятость.
# Максимальная емкость должна оставаться постоянной,
# тогда как занятость может изменяться в любой момент времени.
# Строки документации - строковые литералы,
# которые являются первым оператором в модуле, функции, классе или определении метода.
# Создать класс:
# Определяете нужные атрибуты.
# Те атрибуты, которые существуют на уровне класса, размещаются в определении класса.
# Атрибуты, уникальные для каждого экземпляра, размещаются в конструкторе.
# Также можете определить методы с операциями, изменяющими экземпляр класса.
# Методы также определяются на уровне класса, но атрибуты экземпляров — нет.
# Так как атрибуты экземпляров уникальны для объекта, они хранятся в экземпляре.
class Chair: # name
''' A chair on a chairlift ''' # documentation line
max_occupants = 4 # atributes of a class (4 occupants)
def __init__(self, id): # method(constructor)
self.id = id # inside constructor body, add two atributes 'id', 'count'
self.count = 0
def load(self, number): # method 'load'.
self.count += number # this method represents an operation that can be performed
# by an instance of a class.
def unload(self, number):
self.count -= number
print(Chair.__doc__) #>> 'A chair on a chairlift'
# Атрибут класса используется для хранения состояния, общего для всех экземпляров класса.
# Функция, определяемая прямо в теле класса, называется методом.
# Так как этот метод имеет специальное имя __init__ , он называется конструктором.
# Конструктор вызывается при создании экземпляра класса.
# Метод получает два параметра, self и id .
# У большинства методов первым параметром является self.
# Его можно интерпретировать как экземпляр класса.
# Конструктор вызывается при создании экземпляра класса.
# В Python есть встроенная функция id , но вы также можете использовать
# это имя как имя атрибута класса.
# Если экземпляру было присвоено имя chair , то для получения значения id
# следует использовать запись chair.id . Таким образом,
# Методы представляют собой функции, присоединенные к классу.
# Метод вызывается не сам по себе, а для конкретного экземпляра класса:
# 'matt'.capitalize() #>> 'Matt
# встроенная функция не замещается.
class Try:
def mymethod(self):
print("Hello")
print("Hi")
# create 'obj1' object for 'try1()' class.
obj1 = Try()
# called the method 'method()'.
# a method may take arguments.
obj1.mymethod()
#>>
# Hello
# Hi
class FruitOne:
def size(self, x):
print(f'I\'m size {x}')
orange = FruitOne()
orange.size(7)
#>> I'm size 7
class FruitTwo:
def __init__(self, color, size):
self.color = color
self.size = size
def salutation(self):
print(f'I\'m {self.color} and a size {self.size}')
orange = FruitTwo('Orange', 7)
orange.salutation()
#>> I'm Orange and a size 7
# bank account class
class BankAccount:
def __init__(self):
self.balance = 0
def withdraw(self, amount):
self.balance -= amount
# return self.balance
print(f'Withdrawal of -{amount} RUB from an account, balance your account = {self.balance} RUB')
def deposit(self, amount):
self.balance += amount
# return self.balance
print(f'Depositing funds of +{amount} RUB, balance your account = {self.balance} RUB')
a = BankAccount()
b = BankAccount()
a.deposit(100000) #>> Depositing funds of +100000 RUB, balance your account = 100000 RUB
a.withdraw(12546) #>> Withdrawal of -12546 RUB from an account, balance your account = 87454 RUB
b.deposit(6584) #>> Depositing funds of +6584 RUB, balance your account = 6584 RUB
b.withdraw(17) #>> Withdrawal of -17 RUB from an account, balance your account = 6567 RUB
# Классы и обьекты(как можно проще)
# Объект
# Объект содержит как данные (переменные, которые называются атрибутами,
# так и код (функции, которые называются методами).
# Строки 'cat' и 'duck'
# также являются объектами и имеют методы, например, capitalize() и replace().
print('cat'.capitalize()) #>> Cat
print('duck'.replace('d', 'c')) #>> cuck
# При создании нового объекта, которые не создавал никто,
# надо создать класс, который демонстрирует его содержимое.
# ! Объекты можно считать существительными, а их методы — глаголами.
# Объект представляет отдельную вещь, а его методы определяют,
# как она взаимодействует с другими вещами.
# Класс
# Если Объект это коробка - то Класс это форма из которой эта коробка создается
# ex: String - это встроенный класс Python который создает строковые объекты вроде 'cat', 'duck'
# ex: определять объекты представляющие информацию о людях.
# Каждый объект будет представлять одного человека.
# Сначала нужно определить класс Person в качестве формы.
class Person:
pass
# Такое определение является необходимым минимумом создания объекта.
# объект создается из класса с помощью вызова имени класса так, будто оно является функцией:
someone = Person()
# В этом случае Person() создает отдельный объект класса Person
# и присваивает его имени someone.
class Person:
def __init__(self): # специальный метод инициализации
pass
# __init__() — это особое имя метода,
# который инициализирует отдельный объект с помощью определения его класса
# Аргумент self указывает на сам объект.
class Person:
def __init__(self, name):
self.name = name # is a parameter inside method __init__
donald = Person('Duck')
print(f'The Donald is {donald.name}') # The Donald is Duck
# - этот объект похож на любой другой объект Python.
# - можно использовать его как элемент списка, кортежа, словаря или множества.
# - Можно передать его в функцию как аргумент или вернуть его в качестве результата.
# ! Помни, внутри определения класса Person получаешь доступ к атрибуту name
# с помощью конструкции self.name.
# Когда создаете реальный объект вроде donald , то ссылаетесь на этот атрибут как donald.name.
# ! Не обязательно иметь метод __init__ в описании каждого класса, он используется для того,
# чтобы различать объекты одного класса.
# donald = Person('Duck')
# Эта строка кода делает следующее:
# - выполняет поиск определения класса Person
# - инстанцирует (создает) новый объект в памяти
# - вызывает метод объекта __init__ , передавая только что созданный объект под
# именем self и другой аргумент ( 'Duck' ) в качестве значения параметра name
# - сохраняет в объекте значение переменной name
# - возвращает новый объект
# - прикрепляет к объекту имя Donald
# test
class Cat():
'''A simple attempt to model a cat.'''
def __init__(self, name, age, sex, eye_color, color):
'''Initialize name, age, sex, eye_color, color attributes.'''
self.name = name
self.age = age
self.sex = sex
self.eye_color = eye_color
self.color = color
def sit(self):
'''Simulate a cat sitting in response to a command.'''
print(f'{self.name} is now sitting.')
def roll_over(self):
'''Simulate rolling over in response to a command.'''
print(f'{self.name} rolled over.')
# make instance from a class Cat
cat_034 = Cat('Artemis', 3, 'M', 'Gray', 'White')
print(f'Cat_034 {cat_034.name} is {cat_034.age} years')
#>> Cat_034 Artemis is 3 years
print(f'Cat_034 gender {cat_034.sex}, his color is {cat_034.color} and his eye color is {cat_034.eye_color}')
#>> Cat_034 gender M, his color is White and his eye color is Gray
cat_034.sit() #>> Artemis is now sitting.
cat_034.roll_over() #>> Artemis rolled over.
# test
class Car:
'''A simple attempt to represent a car.'''
def __init__(self, manufacturer, model, year):
'''Initialize attributes to describe a car.'''
self.manufacturer = manufacturer
self.model = model
self.year = year
#default attributes
self.odometr_reading = 0
def get_descriptive_name(self):
'''Return a neatly formatted descriptive name.'''
long_name = f'{self.year} {self.manufacturer} {self.model}'
return long_name.title()
def read_odometr(self):
'''Print a statement showing the car\'s mileage.'''
print(f'This car has {self.odometr_reading} miles on it.')
def update_odometr(self, mileage):
'''
Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
'''
if mileage >= self.odometr_reading:
self.odometr_reading = mileage
else:
print(f'You can\'t roll back an odometer!')
def increment_odometr(self, miles):
'''Add the given amount to the odometer reading.'''
self.odometr_reading += miles
print(f'The car drove plus {miles} miles on it')
my_new_car = Car('UAZ', 'Patriot', 2019)
print(my_new_car.get_descriptive_name()) #>> 2019 Uaz Patriot
# test(Modifying Attribute Values)
my_new_car.update_odometr(2)
my_new_car.read_odometr() #>> This car has 23 miles on it.
my_new_car.increment_odometr(100) #>> This car now has +100 miles on it
my_new_car.read_odometr() #>> This car has 123 miles on it.
#>>
# 2019 Uaz Patriot
# This car has 2 miles on it.
# The car drove plus 100 miles on it
# This car has 102 miles on it.
# Итоги:
# - Можно говорить «объект» или «экземпляр», эти термины можно считать синонимами.
# - Каждый объект связан с некоторым классом.
# - Класс — своего рода фабрика, определяющая поведение объектов/экземпляров.
# - Объект создается специальным методом, который называется конструктором.
# Этому методу присваивается имя __init__ .
# - Вы также можете определять собственные методы классов.
# - При создании класса необходимо как следует поразмыслить.
# Какими атрибутами должен обладать класс?
# Если атрибут остается постоянным для всех объектов, определите его в классе.
# Если атрибут уникален для объекта, задайте его в конструкторе.
#
|
eaba9f7b1bc068972de9069e873593803dc4cc9c | newcaolaing/web_auto | /otherdemo/python高级编程/深入类和对象/1_判断类包含方法及抽象类的创建.py | 572 | 3.515625 | 4 |
class conpany():
def __init__(self,list):
self.list =list
def __len__(self):
return len(self.list)
# 判断类型
com = conpany(["b1",'b2'])
print(hasattr(com,"__len__"))
# 方法二
from collections.abc import Sized
print(isinstance(com,Sized))
# 抽象类实现
import abc
class a(metaclass=abc.ABCMeta):
@abc.abstractmethod
def get(self,key):
pass
@abc.abstractmethod
def set(self,key,value):
pass
class aa(a):
def get(self,key):
pass
def set(self,key,value):
pass
a_test = aa() |
b6ac3a04c654c61055ab1b7109893e1617cf160b | terrenceliu01/python1 | /src/function/function.py | 1,492 | 3.84375 | 4 | """
A function is a block of organized, reusable code
that is used to perform a single, related action.
1. Python built-in functions
print()
len()
sum()
2. User defined function
circleArea()
"""
def printName(firstName, lastName):
print(f"First name: {firstName}, last name: {lastName}")
# call function
printName( lastName="Wang", firstName="John")
def printName(x): # overridden previously defined function
print(f"Hello, {x}")
# printName( "Wang", "John") # previous function no long available
print(len("hello"))
# override built-in function
def len():
print("Hello, world!")
# len("hello")
# a function can return nothing, or return one vaule, or multiple values
def getName():
firstName = input("Enter your first name: ")
lastName = input("Enter your last name: ")
age = int(input("Enter your age: "))
return firstName, lastName, age
# x = getName()
# print(x)
# print(type(x))
# print(f"Your first name: {x[0]}, and last name: {x[1]}.")
def circleArea(r):
circleArea.pi = 3.1415926 # create attribute of the function, the attribute can be accessed outside by function name
pi = 3.14 # function can have local variable which cannot be accessed outside.
return circleArea.pi * r**2
x = circleArea(2)
print(x)
print(circleArea.pi)
# function should be single responsible
def area(x): # bad example it does the realated thing, but not single response.
circleArea = pi * x**2
squareArea = x*x
return circleArea, squareArea
|
bdbf23d895721584182b259060862fd87b1ef1f5 | baranshad/projects | /leecode/reverseinteger.py | 410 | 3.96875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed May 27 23:55:58 2020
@author: user
"""
#%% easier version
def reverse1(x):
y = list(str(abs(x)))
y.reverse()
z= ''.join(x for x in y)
if x > 0 and int(z) <= (2**31-1):
return (int(z))
if x == 0:
return 0
if x < 0 and int(z) <= (2**31-1):
return (- int(z))
else:
return 0
#%%
reverse1(-123)
|
6dc31934b01e5d3770044a7762752d8bbcb56d2c | ringalls2020/Senior-Design | /Shuffle_Songs.py | 1,231 | 3.5 | 4 | import random
import pygame
#This module shuffles songs
#songs must list of file paths when called
#and current_song must = None
def play_song(songs,current_song):
next_song = random.choice(songs)
while next_song == current_song:
next_song = random.choice(songs)
current_song = next_song
return next_song
#This function plays and shuffles songs from a playlist when called
def music():
song1 = '/home/pi/Downloads/The_Song_of_the_Butterfly_[Hungary_2014_HD.ogg'
song2 = '/home/pi/Downloads/Rain and Native American Flute 2 - Shamanic Dream.ogg'
song3 = '/home/pi/Downloads/Buddhist Meditation Music for Positive Energy Buddhist Thai Monks Chanting Healing Mantra.ogg'
song4 = '/home/pi/Downloads/Kill Paris - Good Love.ogg'
songs = [song1,song2,song3,song4]
current_song = None
song_End = pygame.USEREVENT + 1
pygame.init()
pygame.mixer.music.set_endevent(song_End)
pygame.mixer.music.load(play_song(songs,current_song))
pygame.mixer.music.play()
#while True:
#for event in pygame.event.get():
#if event.type == song_End:
#pygame.mixer.music.load(play_song(songs,current_song))
#pygame.mixer.music.play()
|
c0341ad0e0e218dea5d9bd3d0c640811834ba00d | MichaelHancock/Programming-Challenges | /AdventOfCode2018/Day-05-Part-01/program.py | 1,431 | 3.71875 | 4 | def findReactionPair(dataString):
pairIndex = -1
for index, character in enumerate(dataString):
characterToCompare = ""
if (character.isupper()):
characterToCompare = character.lower()
else:
characterToCompare = character.upper()
if (characterMatchesToTheRight(dataString, index, characterToCompare)):
pairIndex = index
break
elif (characterMatchesToTheLeft(dataString, index, characterToCompare)):
pairIndex = index - 1
break
return pairIndex
def characterMatchesToTheRight(dataString, index, character):
return index < len(dataString) - 1 and dataString[index + 1] == character
def characterMatchesToTheLeft(dataString, index, character):
return index > 0 and dataString[index - 1] == character
def removeCharacterAt(indexOfCharacterPair, str):
return str[:indexOfCharacterPair] + str[indexOfCharacterPair+2:]
def main():
inputFile = open("input.txt", "r")
rawStringData = inputFile.read()
stringData = rawStringData.strip()
while (len(stringData) > 0):
indexOfReactionPair = findReactionPair(stringData)
if (indexOfReactionPair == -1):
break;
stringData = removeCharacterAt(indexOfReactionPair, stringData)
print("Advent of Code - Day 05 - Part 01: {0}".format(len(stringData)))
if __name__ == "__main__":
main() |
8ce650034b26d85f77338f6154143119fc021fe5 | elroyg1/QuantQual | /QuanQual.py | 1,297 | 3.6875 | 4 | import csv
from collections import Counter
import itertool
#User will identify the input file location, variable to be analyzed and output file location
inputfile = raw_input("Please identify your file directory: ")
fileVariable = raw_input("Please enter your variable of interest: ")
outputfile = raw_input("Please identify where you want this file to be saved: ")
excluded =['a', 'an', 'the', 'is', 'are', 'were', 'was']
def main():
#opens file
with open(inputfile, 'r') as my_file:
data = csv.DictReader(my_file, delimiter=',')
combi = []
#for each row, create a two word combination and append to combi
for row in data:
for w in itertools.permutations(row[fileVariable].split(), 2):
if (w[0] not in excluded) and (w[1] not in excluded):
combi.append(w)
nodes = Counter(combi)
#creates output file
with open(outputfile, 'w') as csv_file:
fieldnames = ['Source','Target', 'Type', 'ID', 'Label', 'Weight']
data = csv.DictWriter(csv_file, fieldnames = fieldnames)
data.writeheader()
types = 'Undirected'
for combination,count in nodes.most_common():
for i in range(1, len(nodes)):
data.writerow({'Source':combination[0], \
'Target':combination[1], 'Type': 'Undirected' , \
'ID' :i,'Label':combination, 'Weight':count})
main_py()
|
525a19a404bc0452b849c9161ee8fd71adbad3b9 | coocos/leetcode | /leetcode/735_asteroid_collision.py | 3,906 | 4.40625 | 4 | from __future__ import annotations
import unittest
from typing import List, Optional
class Node:
"""Linked list node"""
def __init__(self, value) -> None:
self.value = value
self.next: Optional[Node] = None
self.previous: Optional[Node] = None
@classmethod
def from_list(cls, values: List) -> Node:
"""Constructs linked list from a list"""
head = cls(values[0])
current = head
for value in values[1:]:
current.next = cls(value)
current.next.previous = current
current = current.next
return head
def to_list(self) -> List:
"""Turns linked list into a list"""
values = []
current = self
while current:
values.append(current.value)
current = current.previous
return values
class Solution:
"""
This rather convoluted solution constructs a doubly linked list from the asteroids.
A pointer is moved over the linked list and when a collision is detected, the linked
list is altered to delete either both asteroids or one of the asteroids according
to the size of each asteroid. Then the pointer is adjusted accordingly. For example,
if both asteroids are destroyed then the pointer is moved one asteroid backwards
and the two asteroids are deleted from the linked list. This process repeats until
the pointer reaches the end of the linked list.
"""
def asteroidCollision(self, asteroids: List[int]) -> List[int]:
current = Node.from_list(asteroids)
while current.next:
if current.value > 0 and current.next.value < 0:
# Next asteroid gets demolished
if current.value > abs(current.next.value):
current.next = current.next.next
if current.next:
current.next.previous = current
# Current asteroid gets demolished
elif current.value < abs(current.next.value):
if current.previous:
current = current.previous
current.next = current.next.next
current.next.previous = current
else:
current = current.next
current.previous = None
# Both asteroids get demolished
else:
if current.previous:
current = current.previous
current.next = current.next.next.next
if current.next:
current.next.previous = current
else:
current = current.next.next
if current:
current.previous = None
else:
current = current.next
if not current:
break
return list(reversed(current.to_list())) if current else []
class TestSolution(unittest.TestCase):
def test_example_with_two_collisions(self):
asteroids = [10, 2, -5]
self.assertListEqual(Solution().asteroidCollision(asteroids), [10])
def test_example_with_one_collision(self):
asteroids = [5, 10, -5]
self.assertListEqual(Solution().asteroidCollision(asteroids), [5, 10])
def test_example_with_all_asteroids_colliding(self):
asteroids = [8, -8]
self.assertListEqual(Solution().asteroidCollision(asteroids), [])
def test_example_with_no_asteroids_colliding(self):
asteroids = [-2, -1, 1, 2]
self.assertListEqual(Solution().asteroidCollision(asteroids), asteroids)
def test_example_with_the_last_asteroid_destroying_others(self):
asteroids = [2, 1, -8]
self.assertListEqual(Solution().asteroidCollision(asteroids), [-8])
|
cb1272f8872c246a4e9dab3082809d94db13bce9 | 1Riyad/hue_sms | /src/testinput.py | 793 | 3.546875 | 4 | from hue_controller import HueController
from name_converter import clean_name
from data_writer import writeFile,colorPercent,firstEntryDate
controller = HueController()
file = "data.csv"
def go():
test = "."
while (test != ""):
test = input("Please enter a color: ")
color_name = clean_name(test)
print(test)
if color_name == "black":
print("No black")
else:
percent = colorPercent(file, color_name)
message = controller.set_color(color_name)
date = firstEntryDate(file)
writeFile(file,"856-938-4220", str(color_name), str(message))
print(message +" This entry has been chosen " + str(percent) + "% of the time since " + date + "!"
)
if __name__ == '__main__':
go() |
e3368bc5ae72b178f90d85bdaaa366fd24d0724e | kal-g/SummerResearch | /Abstract Landmarks/FeatureDetectors.py | 15,942 | 3.5625 | 4 | from numpy import *
from math import degrees, sin, cos, hypot, atan2, pi
import random
from scipy.optimize import curve_fit
from cv2 import *
"""All classes Has to contain a get_landmark class which returns landMarks
Has to contain a landmarkType member containing the type of landmark"""
class RANSAC(object):
"""Class to perform RANSAC Based feature detection"""
def __init__(self,N,D,S,C,X,avgWidth):
self.numberOfTrials = N
self.neighbourhood = D
self.numberOfSamples = S
self.consensusRequired = C
self.errorRange = X
self.landmarkType = "Wall"
self.avgWidth = avgWidth
@staticmethod
def _line(x,m,c):
"""Equation of a line used as a cost function for least square optimization"""
return m*x+c
@staticmethod
def _cart_to_pole(Set,deg=True):
"""Cartesian to Polar conversion of a whole list"""
PSet=[]
for (x,y) in Set:
r = hypot(x, y)
t=atan2(y, x)
# if t<0:
# t=2*pi+t
if deg:
PSet.append(tuple((180*t/pi,r)))
else:
PSet.append(tuple((t,r)))
return PSet
@staticmethod
def _pole_to_cart(Set):
"""Polar to Cartesian conversion of a whole list"""
xS=[]
yS=[]
for s in Set:
angle = s[0]
distance = s[1]
if distance !=0:
xs, ys = distance*cos(angle), distance*sin(angle)
xS.append(xs)
yS.append(ys)
return xS,yS
def get_landmarks(self, angles, distances):
wallList = [] #Initialize list of walls
FullScan=[(angles[i],distances[i]) for i in xrange(len(angles))]
#print len(FullScan)
xData,yData=self._pole_to_cart(FullScan)
#Generate Set of Unassociated scans
UnAsc=[]
for x, y in zip(xData,yData):
UnAsc.append((x, y))
Trials=0
m=0
c=0
while UnAsc and (Trials<self.numberOfTrials):
Trials=Trials+1
#Select a random laser data reading.
(seedAngle,seedDistance)=random.choice(FullScan)
#Randomly sample data readings within neighborhood of this laser data reading
shortList=[(a,d) for (a,d) in FullScan
if seedAngle-self.neighbourhood < a < seedAngle+self.neighbourhood]
if not len(shortList)>self.numberOfSamples:
continue
samples=random.sample(FullScan,self.numberOfSamples)
#calculate a least squares best fit line
xSamples,ySamples=self._pole_to_cart(samples)
xSamples=array(xSamples)
ySamples=array(ySamples)
m,c=curve_fit(self._line,xSamples,ySamples)[0]
#Determine how many laser data readings
#lie within self.error_range meters of this best fit line
pointsOnLine=[]
for u in UnAsc:
x1=u[0]
y1=u[1]
d=abs(m*x1+c-y1)/sqrt((m**2)+1)
if d<=self.errorRange:
pointsOnLine.append(u)
xLine=[]
yLine=[]
#If the number of laser data readings on the line
#is above some consensus self.consensus
if len(pointsOnLine)>=self.consensusRequired:
#Calculate new least squares best fit line based on all the
# laser readings determined to lie on the old best fit line.
for p in pointsOnLine:
xLine.append(p[0])
yLine.append(p[1])
#Remove the number of readings lying on the line from the
# total set of unassociated readings.
UnAsc.remove(p)
xLine=array(xLine)
yLine=array(yLine)
m,c=curve_fit(self._line,xLine,yLine)[0]
#Add this best fit line to the lines we have extracted.
yL=c/((m**2)+1)
xL=-m*yL
probablity = len(pointsOnLine)/(self.avgWidth)
print "length of points"
print len(pointsOnLine)
wallList.append(([xL,yL],probablity))
# print Trials
# print len(UnAsc)
# print len(pointsOnLine)
# print len(wallList)
# print "----------------"
return wallList
class SPIKE(object):
def __init__(self,jump, avgWidth):
self.threshold = jump
self.avgWidth = avgWidth
self.landmarkType = "Cylinder"
def _computeDerivative(self,angles, distances):
"""Find the derivative in scan data, ignoring invalid measurements."""
slope=[]
slope.append(0)
for i in xrange(1,len(angles)):
der = (distances[i]-distances[i-1])/(angles[i]-angles[i-1])
slope.append(der)
#slope.append(0)
return slope
def get_landmarks(self, angles, distances):
cylinder_list = []
on_cylinder = False
sum_ray, sum_depth, rays = 0.0, 0.0, 0
scan_derivative=self._computeDerivative(angles,distances)
for i in xrange(len(scan_derivative)):
# --->>> Insert your cylinder code here.
# Whenever you find a cylinder, add a tuple
# (average_ray, average_depth) to the cylinder_list.
if (scan_derivative[i]<0 and abs(scan_derivative[i])>self.threshold):
on_cylinder=True
sum_ray, sum_depth, rays = 0.0, 0.0, 0
if on_cylinder == True:
sum_depth=sum_depth+distances[i]
rays=rays+1
sum_ray=sum_ray+angles[i]
if (scan_derivative[i]>0 and abs(scan_derivative[i])>self.threshold):
print abs(scan_derivative[i])
on_cylinder=False
average_ray=sum_ray/rays
average_depth=sum_depth/rays
probablity = 1#rays/self.avgWidth
cylinder_list.append(([average_ray,average_depth], probablity))
sum_ray, sum_depth, rays = 0.0, 0.0, 0
return cylinder_list,scan_derivative
class HOUGH(object):
"""Class to find walls in Lidar data using Hough Transform"""
def __init__(self,maxRange,radialResolution,angularResolution,threshold):
#Max range of Lidar to be used for defining blank image (cm).
self.maxRange = maxRange
#Resolution for line detection
self.radialResolution = radialResolution
self.angularResolution = angularResolution
self.threshold = threshold
#Transformation matrix from lidar frame to image frame
self.trans_matrix=array([[0,-1,maxRange],[1,0,maxRange],[0,0,1]])
#Transformation matrix from image frame to lidar frame
self.inv_trans_matrix=linalg.inv(self.trans_matrix)
self.landmarkType = "Wall"
def _pole_to_cart(self,angles,distances):
""" Converts from polar coordinates to cartesian coordinates"""
cart=[]
for i in xrange(0,len(angles)-1):
angle = angles[i]
distance = distances[i]
xs, ys = distance*cos(angle), distance*sin(angle)
cart.append(tuple((xs,ys)))
return cart
def get_landmarks(self,angles,distances):
landMarks=[]
#Convert distances to centimeters
distances=[d*100 for d in distances]
#Convert from polar t cartesian coordinates
points=self._pole_to_cart(angles,distances)
# Create new blank 1000x1000 black image
image = zeros((2*self.maxRange, 2*self.maxRange, 3), uint8)
# Place White dots for each Lidar reading
for (xo,yo) in points:
lid_pnt=array([xo,yo,1])
img_pnt=floor(dot(self.trans_matrix,lid_pnt))
image[img_pnt[0],img_pnt[1]]=(255,255,255)
#Use hough transform to detect lines.
#lines = HoughLines(image[:,:,0],self.radialResolution,self.angularResolution,self.threshold)
lines = HoughLines(image[:,:,0],2,pi/18,50)
#If there are lines transform back to lidar frame.
try:
# print "No of lines:"
# print len(lines[0])
for rho,theta in lines[0]:
a = cos(theta)
b = sin(theta)
x0 = a*rho
y0 = b*rho
x1 = (x0 + 100*(-b))
y1 = (y0 + 100*(a))
x2 = (x0 - 100*(-b))
y2 = (y0 - 100*(a))
img_pnt0=array([y1,x1,1])
img_pnt1=array([y2,x2,1])
lid_pnt0=dot(self.inv_trans_matrix,img_pnt0)
lid_pnt1=dot(self.inv_trans_matrix,img_pnt1)
dx=lid_pnt1[0]-lid_pnt0[0]
dy=lid_pnt1[1]-lid_pnt0[1]
K=((dx*lid_pnt0[1])-(dy*lid_pnt0[0]))/(hypot(dx,dy)**2)
xL=-K*dy/100
yL=K*dx/100
landMarks.append(([xL,yL],1))
except:
print "no lines"
pass
return landMarks
class DERIVATIVES(object):
"""Class to find cylinders using first derivative combined with pre knowledge of the cylinders"""
def __init__(self,derivativeThreshold, cylinderRadius, shortRangeAccuracy, longRangeAccuracy, unobservableLandmarkArea, lineFittingThreshold, minSamples):
self.derivativeThreshold = derivativeThreshold
#Radius of cylinders (unit = meter)
self.cylinderRadius = cylinderRadius
#Accuracy of lidar sensor for distance less than 1 meter (Unit = meter)
self.shortRangeAccuracy = shortRangeAccuracy
#Accuracy of lidar sensor for distance larger than 1 meter (Unit = percentage)
self.longRangeAccuracy = longRangeAccuracy
#The percentage of the landmark's area that we suppose the lidar misses
self.unobservableLandmarkArea = unobservableLandmarkArea
#Threshold for line fitting error
self.lineFittingThreshold = lineFittingThreshold
#Threshold for minimum number of samples
self.minSamples = minSamples
self.landmarkType = "Cylinder"
@staticmethod
def _line(x,m,c):
"""Equation of a line used as a cost function for least square optimization"""
return m*x+c
@staticmethod
def _pole_to_cart(Set):
"""Polar to Cartesian conversion of a whole list"""
xS=[]
yS=[]
for s in Set:
angle = s[0]
distance = s[1]
if distance !=0:
xs, ys = distance*cos(angle), distance*sin(angle)
xS.append(xs)
yS.append(ys)
return xS,yS
def get_landmarks(self,angles,distances):
#Initialize empty list of landmarks
landmarks = []
#Initially no thresholds are found
previousThresholdFound = False
startingIndex = 1
#Look at each pair of angles and distances
for i in xrange(1,len(angles)):
#Check if there is a large jump in distance
if abs(distances[i]-distances[i-1])>self.derivativeThreshold :
#Store starting index
stoppingIndex = i-1
#Check if we are already on a probable landMark
if previousThresholdFound:
# Then this is at the end of a section of scan
#Find the parameters of the probable landmark.
#[startingIndex from previous threshold]
beamIndex = int((startingIndex+stoppingIndex)/2)
beamDistance = distances[beamIndex]+self.cylinderRadius
beamAngle = angles[beamIndex]
#Convert parameters to cartesian space.
beamX = beamDistance*cos(beamAngle)
beamY = beamDistance*sin(beamAngle)
#Find the angular width of the probable landmark
angularWidth = abs(angles[stoppingIndex]-angles[startingIndex])*180/pi
#Calculate the theoretical angular width for known landmarks
expectedWidth = 2*atan2(self.cylinderRadius,distances[startingIndex])*180/pi
# Find acceptable levels of deviation from the angular width
# Check if it is near range
if distances[startingIndex] > 1:
#Find the maximum error possible by taking the tangential beam
distanceError = distances[startingIndex] - self.cylinderRadius - self.shortRangeAccuracy
#Calculate acceptable deviation
angleDeviation = abs(self.unobservableLandmarkArea*2*atan2(self.cylinderRadius,distanceError)*180/pi)
else:
#Find the maximum error possible by taking the tangential beam
distanceError = distances[startingIndex] - self.cylinderRadius - self.longRangeAccuracy*distances[startingIndex]
#Calculate acceptable deviation
angleDeviation = abs(self.unobservableLandmarkArea*2*atan2(self.cylinderRadius,distanceError)*180/pi)
# Compute least square fit on the model of a straight line.
samples=[(angles[i],distances[i]) for i in xrange(startingIndex,stoppingIndex)]
xSamples,ySamples=self._pole_to_cart(samples)
xSamples=array(xSamples)
ySamples=array(ySamples)
parameters,covariance=curve_fit(self._line,xSamples,ySamples)
fittingError = norm(diag(covariance))
#Check for different condition:
# 1) Check if there are enough points
# 2) Check if it's angular width is as expected
# 3) Check if it is not a line, i.e. line fitting threshold is large
if abs(expectedWidth-angularWidth) < angleDeviation \
and len(samples) > self.minSamples \
and fittingError > self.lineFittingThreshold:
landmarks.append([beamAngle,beamDistance],1)
else:
previousThresholdFound = True
startingIndex = i
return landmarks
class ABSTRACT_DETECTOR(object):
#TODO Add all the variables we will need for get_landmarks
def __init__(self):
self.landmarkType = "Abstract"
#TODO Check if the current LIDAR data is enough to constitute a landmark.
# If it is, return an abstract landmark
def get_landmarks(self,angles,distances):
class IMAGE_LINES(object):
"""Class to find vertical lines in on-board camera images"""
def __init__(self,kernalSize,thresholdingBlockSize,thresholdingConstant,
edgeThreshold1,edgeThreshold2,edgeApertureSize,angleRange,
distanceRange,lineThreshold,fieldOfView,angularError):
#parameters for median blur
self.kernalSize = kernalSize
#Aperture linear size; it must be odd and greater than 1,
#for example: 3, 5, 7 ...
#adaptiveThreshold parameters
#Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on.
self.thresholdingBlockSize = thresholdingBlockSize
#Constant subtracted from the mean or weighted mean
self.thresholdingConstant = thresholdingConstant
#Canny edge detector parameters
#First threshold for the hysteresis procedure
self.edgeThreshold1 = edgeThreshold1
#Second threshold for the hysteresis procedure
self.edgeThreshold2 = edgeThreshold2
#Aperture size for the Sobel() operator
self.edgeApertureSize = edgeApertureSize
#HOUGH transform parameters
#Angle resolution of the accumulator in radians
self.angleRange = angleRange
#Distance resolution of the accumulator in pixels
self.distanceRange = distanceRange
#Accumulator threshold parameter.
#Only those lines are returned that get enough votes (>threshold)
self.lineThreshold = lineThreshold
#Horizontal Field of View
self.fieldOfView = fieldOfView
#EKF Error variable for Covariance
self.angularError = angularError
self.landmarkType = "Image Line"
def get_landmarks(self,image):
"""Hough transform based lines extractor"""
landmarks=[]
#Convert image to gray
gray = cvtColor(image,COLOR_BGR2GRAY)
#deNoise image
gray = medianBlur(gray,self.kernalSize)
#Convert into a binary image
th2 = adaptiveThreshold(gray,255,ADAPTIVE_THRESH_MEAN_C,THRESH_BINARY,
self.thresholdingBlockSize,self.thresholdingConstant)
#Find edges in image
edges = Canny(th2,self.edgeThreshold1,self.edgeThreshold2,
apertureSize = self.edgeApertureSize)
#Find lines in image
lines = HoughLines (edges,self.distanceRange,
self.angleRange,self.lineThreshold)
if lines is not None:
for line in lines:
for rho,theta in line:
if theta < 0.5 or theta > math.pi-0.5: #~20 degrees
angle = (rho*self.fieldOfView/image.shape[1])-(self.fieldOfView/2)
#landmarks.append((radian(angles),self.angularError))
landmarks.append((rho, theta))
pass
return landmarks
|
0aa40b1c467b5fa0458f7de03fab0e86d1a5e5eb | warrior-graph/UECE | /Trabalho-2-PEOO/elemento.py | 808 | 3.765625 | 4 | from abc import ABCMeta
class Elemento(metaclass=ABCMeta):
# Atributo que representa o nome de um objeto elemento
__nome = ""
# Atributo que representa o nome
__tipo_elemento = None
def __init__(self, nome="", tipo_elemento=None):
self.__nome = nome
self.__tipo_elemento = tipo_elemento
@property
def nome(self):
return self.__nome
@nome.setter
def nome(self, nome):
self.__nome = nome
@nome.deleter
def nome(self):
del self.__nome
@property
def tipo_elemento(self):
return self.__tipo_elemento
@tipo_elemento.setter
def tipo_elemento(self, tipo_elemento):
self.__tipo_elemento = tipo_elemento
@tipo_elemento.deleter
def tipo_elemento(self):
del self.__tipo_elemento
|
16c2851fab10d33612a704787a871aae15930894 | ReDI-School/redi-python-intro | /theory/Lesson2-Interactive-programs/code/numbers_operators.py | 444 | 4.0625 | 4 | # Lesson2: Operators with numbers
# source: code/numbers_operators.py
a = 21
b = 10
c = 0
c = a + b
print ("Line 1 - Value of c is ", c)
c = a - b
print ("Line 2 - Value of c is ", c )
c = a * b
print ("Line 3 - Value of c is ", c)
c = a / b
print ("Line 4 - Value of c is ", c )
c = a % b
print ("Line 5 - Value of c is ", c)
a = 2
b = 3
c = a**b
print ("Line 6 - Value of c is ", c)
a = 10
b = 5
c = a//b
print ("Line 7 - Value of c is ", c) |
c9b6764685de1cd07aa71b28a8f5631d277ec116 | haijiwuya/python-collections | /base/5.set/SetUse.py | 1,723 | 3.875 | 4 | """
集合和列表非常相似
不同点:
1、集合中只能存储不可变对象
2、集合中存储的对象是无序的
3、集合中不能出现重复的元素
"""
s = {1, 2, 3, 4}
print(s, type(s))
# 空集合只能通过set()函数来创建
s = set()
print(s, type(s))
# s = set([1, 2, 3, 4, 5])
s = {1, 2, 3, 4, 5}
print(s, type(s))
# 使用set()将字典转换为集合只包含集合中的键
# s = set({'a': 1, 'b': 2, 'c': 3})
s = {'a': 1, 'b': 2, 'c': 3}
print(s, type(s))
# 使用in 和not in来检查集合中的元素
s = {'a', 'b', 1, 2, 3, 1}
print('c' in s)
print('a' in s)
# 使用len()来获取集合中元素的数量
print(len(s))
# add()向集合中添加元素
s.add(10)
s.add(30)
print(s)
# update()将一个集合中的元素添加到当前集合中
s2 = set('hello')
s.update(s2)
print(s)
# pop()随机删除一个集合中的元素,并返回删除的元素
s.pop()
print(s)
# remove()删除集合中的指定元素
s.remove(30)
print(s)
# clear()清空集合
s.clear()
print(s)
# copy()对集合进行浅复制
s = {1, 2, 3, 4, 5}
s2 = {3, 4, 5, 6, 7}
# &交集运算
result = s & s2
print(result)
# |并集运算
result = s | s2
print(result)
# -差集
result = s - s2
print(result)
# ^异或集
result = s ^ s2
print(result)
# <=检查一个集合是否另一个集合的子集,如果两个集合元素一样,也算一个集合是另一个集合的子集
result = s <= s2
print(result)
# < 检查一个集合是否是另一个集合的真子集(两个集合元素不相同)
s = {1, 2, 3}
s2 = {1, 2, 3, 4, 5}
print(s < s2)
# >= 检查一个集合是否是另一个集合的超集
# > 检查一个集合是否是另一个集合的真超集
|
6e345e73fc7e9364761b0b7df7f4ab792f2d9b9e | AasifMdr/LabExercise | /LabOne/Qn9.py | 236 | 4.1875 | 4 | '''
Write a python program to find sum of the first n positive integers.
sum = (n*(n+1)) / 2
'''
num = int(input("Enter a positive integer: "))
sum = (num * (num + 1)) / 2
print(f'The sum of the first {num} positive integers is {sum}') |
9a95a643324d3f5d6609195ef2e04e6150b9c750 | sf-burgos/BasicProgrammingWithPython | /soluciones/semana9/dnasort.py | 2,350 | 3.96875 | 4 | from sys import stdin
def quickSort(alist):
#Pre: Una lista ordenable
#pos: Una lista ordenada """
quickSortHelper(alist,0,len(alist)-1)
def quickSortHelper(alist,first,last):
#pre: una lista ordenable,con un pivote y una lista de salida
#returnara un marcador derecho o pivote """
if first<last:
splitpoint = partition(alist,first,last)
quickSortHelper(alist,first,splitpoint-1)
quickSortHelper(alist,splitpoint+1,last)
def partition(alist,first,last):
pivotvalue = alist[first]
leftmark = first+1
rightmark = last
done = False
while not done:
while leftmark <= rightmark and alist[leftmark] <= pivotvalue:
leftmark = leftmark + 1
while alist[rightmark] >= pivotvalue and rightmark >= leftmark:
rightmark = rightmark -1
if rightmark < leftmark:
done = True
else:
temp = alist[leftmark]
alist[leftmark] = alist[rightmark]
alist[rightmark] = temp
temp = alist[first]
alist[first] = alist[rightmark]
alist[rightmark] = temp
return rightmark
def bubbleSort(alist,listanumeros,listagrande):
cont=0
alist=list(alist)
alist2=alist.copy()
a=""
for i in range(len(alist2)):
a+=alist[i]
for passnum in range(len(alist)-1,0,-1):
for i in range(passnum):
if alist[i]>alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
cont+=1
listanumeros.append(cont)
listagrande.append(cont)
listagrande.append(a)
def main():
n=int(stdin.readline().strip())
for j in range(n):
k=str(stdin.readline().strip())
listanumeros=[]
listagrande=[]
datos=[int(s) for s in stdin.readline().strip().split(" ")]
cont=0
for i in range(datos[1]):
alist =str(stdin.readline().strip())
bubbleSort(alist,listanumeros,listagrande)
quickSort(listanumeros)
for i in range(len(listagrande)):
a=listagrande.index(listanumeros[cont])
listagrande[a]=-1
print(listagrande[a+1])
if cont==len(listanumeros)-1:
break
else:
cont+=1
if j<n-1:
print()
main()
|
767d87e12859c198637bbb5567e053bfb7e35948 | jbascunan/Python | /1.Introduccion/24.raise.py | 340 | 3.609375 | 4 | class TinyIntError(Exception):
pass
def tyni_int(val):
return val >= 0 and val <= 255
try:
numero = 400
if tyni_int(numero):
print("el numero es correcto")
else:
raise TinyIntError(
"este es un mensaje para los numeros que no son tyni_int")
except TinyIntError as error:
print(error)
|
a76e7f5de7eaeea7f3b88e4eefe31a1bca55dc23 | LukaLiu/fulpropalgo | /utils.py | 1,098 | 3.5 | 4 | import math
from math import factorial as fac
import scipy.stats as ss
#factorial function
# fac(n) / (fac(k) * fac(n - k)) * p**k * (1-p)**(n-k)
#caculate binominal probability
def binominal(k,n,p):
return ss.binom.pmf(k,n,p)
#caculate_right or left bondary, which is the sum of binominal probs
def cal_bond(bond, total_tokens, probability):
result=0
for x in bond:
result+=binominal(x,total_tokens, probability)
return result
#calculate binominal boundary for verification
#input total numbers of user's tokens, and probability of that round
def bino_bond(user_total_tokens, prob):
#bonds for binomial boundary
bonds = []
# new_j to be used to caculate binomial boundary
j=[[num for num in range(x+1)] for x in range(user_total_tokens+1)]
new_j=[(j[x],j[x+1]) for x in range(len(j)-1)]
for element in new_j:
right,left = element
bond = (cal_bond(right,user_total_tokens, prob),cal_bond(left,user_total_tokens,prob))
bonds.append(bond)
return bonds
def get_bond(j,user_total,prob):
sum = 0
while j >= 0:
sum += ss.binom.pmf(j, user_total, prob)
j -= 1
return sum
|
cea1c70816d1ad9b3eec72061a491694acd31141 | Alkagdy/dzien3 | /Zadanie2.py | 477 | 3.796875 | 4 | #czy liczba jest podzielna przez 3, 5 lub 7
#input
liczba = input("Podaj liczbe:")
#spr czy tylko cyfry
if liczba.isdigit():
#jesli podzielna przez 3
if int(liczba) %3==0:
print("Podzielna przez 3")
# w przeciwnym wypadku czy podzielna przez 5
elif int(liczba) %5==0:
print("Podzielna przez 5")
#napisz podzielna przez 5
#Czy podzielna przez 7
elif int(liczba) %7==0:
print("Liczba podzielna przez 7")
else:
print("Podaj liczbe!!") |
e3d0507ad6e0377d29125bd3b2544d76fb0627d7 | sidtrip/hello_world | /CS106A/week4/sec4/trim_crop.py | 1,170 | 3.921875 | 4 | from simpleimage import SimpleImage
def main():
image = SimpleImage('images/karel.png')
trimmed_img = trim_crop_image(image, 30)
trimmed_img.show()
def trim_crop_image(original_img, trim_size):
"""
This function returns a new SimpleImage which is a trimmed and
cropped version of the original image by shaving trim_sz pixels
from each side (top, left, bottom, right) of the image. You may
assume trim_sz is less than half the width of the image.
Inputs:
- original_img: The original image to process
- trim_size: The number of pixels to shave from each side
of the original image
Returns:
A new SimpleImage with trim_sz pixels shaved off each
side of the original image
"""
nudimx = original_img.width - 2*trim_size
nudimy = original_img.height - 2*trim_size
new = SimpleImage.blank(nudimx, nudimy)
for y in range(new.height):
for x in range(new.width):
newx = x + trim_size-1
newy = y + trim_size-1
new.set_pixel(x, y, original_img.get_pixel(newx, newy))
return new
if __name__ == '__main__':
main() |
3938042f21cbe4285b623c0be875f36ca641884f | Adam-Albert/cp1404practicals | /prac_04/lists_warmup.py | 786 | 4.09375 | 4 | numbers = [3, 1, 4, 1, 5, 9, 2]
# numbers[0] = 3
print(numbers[0])
# numbers[-1] = 2
print(numbers[-1])
# numbers[3] = 1
print(numbers[3])
# numbers[:-1] = 3 1 4 1 5 9
print(numbers[:-1])
# numbers[3:4] = 1
print(numbers[3:4])
# 5 in numbers = true
print(5 in numbers)
# 7 in numbers = false
print(7 in numbers)
# "3" in numbers = false
print("3" in numbers)
# numbers + [6, 5, 3] = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3]
print(numbers + [6, 5, 3])
# 1. Change the first element of numbers to "ten" (the string, not the number 10)
numbers[1] = "ten"
print(numbers)
# 2. Change the last element of numbers to 1
numbers[-1] = 1
print(numbers)
# 3. Get all the elements from numbers except the first two (slice)
print(numbers[2:])
# 4. Check if 9 is an element of numbers
print(9 in numbers) |
292e9cca4adccb0174dae45816db7d75d8642bd9 | jsygal/TrainPy | /Python/exercise/Udemy/FIleOperations/file2.py | 853 | 3.5625 | 4 | #!/usr/bin/env python3
'''
Requirement:
Create a program that opens file.txt. Read each line of the file and prepend it with a line
number.'''
import time
with open('/Users/jishnusygal/VSCode/myCode/pythonBegin/exercise/Udemy/FIleOperations/animals.txt') as file:
animals=[];
for line in file:
animals.append(line.rstrip());
print("Unsorted:",animals);
print("Sorted:",sorted(animals));
sortAnimal=sorted(animals);
with open('/Users/jishnusygal/VSCode/myCode/pythonBegin/exercise/Udemy/FIleOperations/animals-sort.txt',mode='w') as sFile:
sFile.truncate();
for animal in sortAnimal:
with open('/Users/jishnusygal/VSCode/myCode/pythonBegin/exercise/Udemy/FIleOperations/animals-sort.txt',mode='a+') as sFile:
sFile.write(animal);
sFile.write('\n');
print(time.asctime()); |
b79db6d1ab13b9cebd20c378e0d930898fb79b40 | rasyidev/Google-IT-Automation-with-Python | /Course 1 - Crash Course on Python/21-letter-frequency.py | 188 | 3.859375 | 4 | def get_freq(text):
res = {}
for letter in text:
if(letter not in res):
res[letter] = 0
res[letter] += 1
return res
res = get_freq("hello world!")
print(res) |
34a2e2a11dc2c7531ad358ca2deea00fb66958b1 | emanuel-mazilu/python-projects | /timer/timer.py | 556 | 3.890625 | 4 | import tkinter as tk
window = tk.Tk()
window.title("Timer")
def countdown(count):
mins, secs = divmod(count, 60)
if mins >= 60:
hours, mins = divmod(mins, 60)
else:
hours = 0
label1['text'] = str(hours).zfill(2) + ":" + str(mins).zfill(2) + ":" + str(secs).zfill(2)
if count > 0:
window.after(1000, countdown, count - 1)
label1 = tk.Label(window, justify='center', font=("arial", 40))
label1.pack()
# Timer in seconds
countdown(7210)
window.mainloop()
# TODO
# user input
# notification when time finishes
|
dac8d916a2a7d28e24ca2388757ec021ff48297c | LeetCodeSolution/ListNode | /delete_according_to_value.py | 382 | 3.75 | 4 | def delete_according_to_value(head, value):
if not head:
return None
if head.value == value:
return None
node = head
prev = None
while node and node.value != value:
prev = node
node = node.next
if not node:
return head
if node.value == value:
prev.next = node.next
return head
|
21846fa3a05c7170508887418a6305da900f9fa3 | genzai0/HIKKOSHI | /suburi/gener/ex1.py | 232 | 3.703125 | 4 | def count_up():
x = 0
while True:
yield x
x += 1
def fib():
a,b = 0,1
while True:
yield b
a,b = b,a+b
for i in fib():#enumerate(fib()):
print(i)
if i == 10**9:
break
|
8c65db2e94b515e5fb723bd910ffc45cf941bdcc | noob-tactics/ML-Project | /Predicting-Fantasy-Football-Points-Using-Machine-Learning-master/rmse_bar_plot.py | 1,729 | 3.515625 | 4 | """
This program reads two csv files, rmse.csv and FantasyData_rmse.csv, and
construct bar plots to compare prediciton RMSE and FantasyData RMSE.
"""
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
"""
Read prediction RMSEs and FantasayData's RMSEs
Find min RMSE for each position
"""
path = "data/"
pred = pd.read_csv(path + "rmse.csv")
fantasy = pd.read_csv(path + "FantasyData_rmse.csv")
print ("The best estimator for each position with the lowest RMSE is: \n")
RMSE = []
pred_rmse = pred.ix[:, 1:]
for column in pred_rmse:
min_rmse = min(pred_rmse[column])
min_rmse_index = pred_rmse[column].argmin()
min_rmse_algo = pred.ix[min_rmse_index, 0]
print "{}: {}".format(min_rmse_algo, min_rmse)
RMSE.append(min_rmse)
Fantasy_RMSE = []
for position in pred.columns.values[1: ]:
Fantasy_RMSE.append(float(fantasy.ix[fantasy['Pos'] == position, 1]))
"""
Bar plot to compare prediction RMSE to Fantasydata.com
"""
def autolabel(rects):
# attach value labels
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2.0, 1.05 * height,
'{0:.3f}'.format(height),
ha='center', va='bottom')
ind = np.arange(5) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots(1)
rects1 = ax.bar(ind, RMSE, width, color='r')
rects2 = ax.bar(ind + width, Fantasy_RMSE, width, color='y')
ax.set_ylabel('RMSE')
ax.set_ylim([0, 13])
ax.set_title('RMSE Comparision by Position')
ax.set_xticks(ind + width)
ax.set_xticklabels(pred.columns.values[1: ])
ax.legend((rects1[0], rects2[0]), ('Prediction', 'Fantasydata.com'))
autolabel(rects1)
autolabel(rects2)
plt.show()
|
ba708a5fa5f61c9815ba676d0f739331a38808e4 | tokareff/xlrd-nameSalary-demo | /info.py | 2,113 | 3.71875 | 4 | import xlrd
#from xlrd import cellname #this is not needed unless you want to use the name of cell e.g A1
def open_xlBook(file_name, sheet_name):
data = xlrd.open_workbook(file_name)
sheet = data.sheet_by_name(sheet_name)
return sheet
def print_contents(sheet):
for row_index in range(sheet.nrows):
for col_index in range(sheet.ncols):
#cell_name = cellname(row_index,col_index)
print sheet.cell(row_index,col_index).value
def createDictionary(sheet):
name_sal_dict = {} #create a one to one mapping between names and salaries
sal = [] #create list to store salaries
for row_index in range(sheet.nrows):
for col_index in range(sheet.ncols):
#skip the title row (i.e topmost row) and only focus on column 0
#where we get all the names
if row_index > 0 and col_index <1:
#get the salary from 3rd column and map it to the name from column 0
name_sal_dict[sheet.cell(row_index,col_index-col_index).value] = \
sheet.cell(row_index,col_index+2).value
#keep adding the salaries to list
sal.append(sheet.cell(row_index,col_index+2).value)
else:
pass
return name_sal_dict,sal
def whoEarnMost(dic, lis):
#assemble the result string to write to the file
output_string = ""
for name, sal in dic.iteritems():
if sal == max(lis):
output_string = output_string + name + " earns " + str(sal) + " USD."+'\n'
return output_string
def writeOut(output_string):
f = open('output.txt','w')
f.write(output_string)
f.close
if __name__=='__main__':
xlFile = './Information.xlsx'
sheetName = 'People'
#open sheet
sheet = open_xlBook(xlFile, sheetName)
#get the name: salary dictionary and the salary list
name_salary_dict, salary_list = createDictionary(sheet)
#get the result string
out_string = whoEarnMost(name_salary_dict, salary_list)
#output to the file
writeOut(out_string)
|
b2d057122ee5588fc1115beada6c0ddeabda72c0 | benjaminpotter/HatchProjects | /So Many Words/base.py | 661 | 3.890625 | 4 | word = "SOMANYWORDS"
mainColor = color(255,255,255)
secondaryColor = color(255,0,0)
coloredWord = 7
backgroundColor = color(0,0,0)
wordSize = 15
multipleWords = []
counter = 0
wordLength = word.length
background(backgroundColor)
def combineText():
for i in range (0, 300):
multipleWords = multipleWords + word
combineText()
def drawText():
textSize(wordSize)
start = wordLength*coloredWord-1
for y in range (-20, 500, 50):
for x in range (10; 400, 29):
if counter > start and counter <= start+wordLength :
fill(secondaryColor)
else:
fill(mainColor)
text(multipleWords[counter],x,y)
counter++
drawText()
|
2e2785f482816fe56847c751911afe13d41e851f | kyana1234/Back_to_the_Loonaverse | /bullet.py | 912 | 3.53125 | 4 | import pygame
import constant_movement
class Bullet(constant_movement.ConstantMovement):
"""Projectiles that the players shoot to destroy the aliens.
Subclass of ConstantMovement
Attributes:
Please reference constant_movement.py for attributes
Functions:
get_img()
"""
img: pygame.Surface = pygame.image.load('graphics/star.png')
def __init__(self, screen_dim, player_x: float, player_y: float, player_img_dim: tuple):
self.screen_dim = screen_dim
super().__init__(self.img, screen_dim)
# Shifted x,y based on how the bullets were drawn relative to spaceship in GUI testing.
self.set_x(player_x + (player_img_dim[0] / 2) - 10)
self.set_y(player_y - (player_img_dim[1] / 2) + 5)
# Default y-velocity
self.set_vy(-5) # Upward motion is negative y-velocity.
def get_img(self):
return self.img
|
93b504520b8dbb07d500b33fddc1aabeec8f54c6 | SiddhiPevekar/Python-Programming-MHM | /prog22.py | 166 | 4.34375 | 4 | #program to print table of a given number
n=int(input("enter any number to print the table for:\n"))
i=1
while i<=10:
print(n,"*",i,"=",n*i)
i+=1
|
0d66b868859d2ba1644ad71ee8aee871fb620ef3 | yorkypy/selise-intervie | /problems/binarySearch.py | 257 | 3.734375 | 4 | #Binary Search
from typing import Sized
def binarySearch(arr,n):
size=len(arr)
for i in range(size):
if arr[(size/2)]==arr[i]:
return arr[i]
elif n>arr[(size/2)]:
pass
if __name__ == "__main__":
pass
|
afc3704a2f8fc05431661bbc14d90181233d4cb6 | robin8a/udemy_raspberry_machine_learning | /Codes/Course_codes_image/4.4-Varying_Brightness.py | 1,170 | 3.625 | 4 | # Varying Brightness of Images using Add and Subtract Operations
# Import Computer Vision package - cv2
import cv2
# Import Numerical Python package - numpy as np
import numpy as np
# Read the image using imread built-in function
image = cv2.imread('image_4.jpg')
# Display original image using imshow built-in function
cv2.imshow("Original", image)
# Wait until any key is pressed
cv2.waitKey(0)
# np.ones returns an array of given shape and type, filled with ones
# np.ones(shape, dtype)
matrix = np.ones(image.shape, dtype = "uint8") * 120
# image.shape: gives takes the shape of original image
# uint8: unsigned integer (0 to 255)
# matrix: contains ones, having same dimension as original image but mutlipied by 120
# Adding matrix to orginal image, increases brightness
add = cv2.add(image, matrix)
# Display added image
cv2.imshow("Added", add)
# Wait until any key is pressed
cv2.waitKey(0)
# Subtracting matrix and original image, decreases brightness
subtract = cv2.subtract(image, matrix)
# Display subtracted image
cv2.imshow("Subtracted", subtract)
# Wait untill any key is pressed
cv2.waitKey(0)
# Close all windows
cv2.destroyAllWindows()
|
8d906e3fb5539b24114e2f9f887e92a8403a4807 | Klakurka/BattleShip | /BattleShip.py | 11,257 | 3.734375 | 4 | from sys import exit
from random import randint
class player(object):
def __init__(self):
self.ship_Board = gameBoard()
self.ship_Board.initialize_Ships()
self.firing_Board = gameBoard()
self.shot_Log = []
self.firing_Queue = []
self.boat_Hit_Log = []
self.rand_Queue = []
def shots_Fired(self, shot):
self.shot_Log.append(shot)
self.firing_Board.board[shot][1] = ('hit')
if shot in self.rand_Queue:
self.rand_Queue.remove(shot)
def hit_Boat(self, shot):
self.boat_Hit_Log.append(shot)
self.firing_Board.board[shot][0] = ('boat')
def display_Boards(self):
print " Firing Board"
print ""
self.firing_Board.display_Board()
print " Ship Board"
print ""
self.ship_Board.display_Board()
def game_Status(self):
if self.ship_Board.ships_Left == []:
return (True)
return (False)
def computer_Logic(self):
#Add items to the firing queue
self.future_Targets()
if self.firing_Queue != []:
target = randint(0, (len(self.firing_Queue) - 1))
return (self.firing_Queue.pop(target))
else:
column = self.firing_Board.column
row = self.firing_Board.row
#fire only on every other square
if self.rand_Queue == []:
for i in column:
if column.index(i) % 2 == 0:
for n in row:
if row.index(n) % 2 == 0:
self.rand_Queue.append((i + n))
elif column.index(i) % 2 != 0:
for n in row:
if row.index(n) % 2 != 0:
self.rand_Queue.append((i + n))
target = self.rand_Queue[(randint(0, (len(self.rand_Queue) - 1)))]
return target
def future_Targets(self):
#Add area around confirmed hits to a firing queue
for item in self.boat_Hit_Log:
# Only add it if its not in the queue already
# and if it hasn't been shot
column_Letter = item[:1]
row_Number = item[1:]
column_Pos = self.firing_Board.column.index(column_Letter)
row_Pos = self.firing_Board.row.index(row_Number)
potential_Targets = []
if column_Pos != (9):
#add 1 to column
potential_Targets.append((self.firing_Board.column[(column_Pos + 1)] + row_Number))
if column_Pos != (0):
#subtract 1 from column
potential_Targets.append((self.firing_Board.column[(column_Pos - 1)] + row_Number))
if row_Pos != (9):
#add 1 to row
potential_Targets.append((column_Letter + self.firing_Board.row[(row_Pos + 1)]))
if row_Pos != (0):
#subtract 1 from row
potential_Targets.append((column_Letter + self.firing_Board.row[(row_Pos - 1)]))
for target in potential_Targets:
valid = self.firing_Board.valid_Target(target)
if target not in self.shot_Log and valid == (True) and target not in self.firing_Queue:
self.firing_Queue.append(target)
class playerComputer(player):
pass
class gameBoard(object):
def __init__(self):
self.column = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
self.row = ['1','2','3','4','5','6','7','8','9','10']
self.ships_Left = []
self.ships = {
'battleship':3,
'submarine':3,
'carrier':5,
'tug':2
}
self.board = {}
self.create_Board()
def create_Board(self):
for letter in self.column:
for num in self.row:
self.board[letter + num] = ['noBoat', 'noHit']
####################################################### BOARD DISPLAY ##########################################################################
def format_Board(self, key):
if self.board[key][0] == 'noBoat' and self.board[key][1] == 'noHit':
return ""
elif self.board[key][0] == 'boat' and self.board[key][1] == 'noHit':
return "[#]"
elif self.board[key][0] == 'noBoat' and self.board[key][1] == 'hit':
return "( )"
elif self.board[key][0] == 'boat' and self.board[key][1] == 'hit':
return "(X)"
def display_Board(self):
print " %s %s %s %s %s %s %s %s %s %s" % (
self.row[0], self.row[1], self.row[2], self.row[3], self.row[4],
self.row[5], self.row[6], self.row[7], self.row[8], self.row[9],
)
print ""
for letter in self.column:
print " %s %s %s %s %s %s %s %s %s %s %s" % (letter,
self.format_Board(letter + self.row[0]), self.format_Board(letter + self.row[1]),
self.format_Board(letter + self.row[2]), self.format_Board(letter + self.row[3]),
self.format_Board(letter + self.row[4]), self.format_Board(letter + self.row[5]),
self.format_Board(letter + self.row[6]), self.format_Board(letter + self.row[7]),
self.format_Board(letter + self.row[8]), self.format_Board(letter + self.row[9])
)
print ""
####################################################### BOARD SHOOTING ##########################################################################
def shot_Received(self, coordinate):
#modify the ship board
#remove from shipsLeft
self.board[coordinate][1] = ('hit')
if coordinate in self.ships_Left:
self.ships_Left.remove(coordinate)
return (True)
return (False)
def valid_Target(self, target):
#Not valid if target does not exist or if target has already been hit
if target not in self.board:
return (False)
elif self.board[target][1] == 'hit':
return (False)
else:
return (True)
####################################################### SHIPS ##################################################################################
def initialize_Ships(self):
for ship in self.ships:
valid = (False)
while valid == (False):
length = self.ships[ship]
starting_Coord = self.random_Coord()
vector_Options = self.potential_Vectors(starting_Coord, length)
vector = self.random_Vector(vector_Options)
ship_Coordinates = self.generate_Ship_Coordinates(starting_Coord, length, vector)
valid = self.validate_Ship_Coordinates(ship_Coordinates)
if valid == (True):
self.assign_Ship_Coordinates(ship_Coordinates)
#print "Ship list: %s" % (self.ships_Left)
def random_Coord(self):
#return a random board coordinate
rand_Row = self.row[randint(0, (len(self.row) - 1))]
rand_Col = self.column[randint(0, (len(self.column) - 1))]
return (rand_Col + rand_Row)
def potential_Vectors(self, initial_Coordinate, ship_Length):
#return potential vectors based on given coordinate and ship size
vector_Options = ['down', 'up', 'right', 'left']
lower_Bound = (ship_Length - 1)
upper_Bound = (len(self.row) - ship_Length)
row_Pos = self.row.index((initial_Coordinate[1:]))
col_Pos = self.column.index((initial_Coordinate[:1]))
#if a number is within a lower bound range than it can't go a certain direction
#take coord A5, a ship could be placed in any direction except up
if col_Pos < lower_Bound:
#can't go up
vector_Options.remove('up')
if col_Pos > upper_Bound:
#can't go down
vector_Options.remove('down')
if row_Pos < lower_Bound:
#can't go left
vector_Options.remove('left')
if row_Pos > upper_Bound:
#can't go right
vector_Options.remove('right')
return (vector_Options)
def random_Vector(self, potential_Vectors):
#return a random vector chosen from list of potential vectors
vector = potential_Vectors[(randint(0,(len(potential_Vectors) - 1)))]
return (vector)
def generate_Ship_Coordinates(self, initial_Coordinate, ship_Length, vector):
#return a set of coordinates that a ship will occupy given its initial starting point, vector, and ship size
row_Pos = self.row.index((initial_Coordinate[1:]))
col_Pos = self.column.index((initial_Coordinate[:1]))
row_Val = (initial_Coordinate[1:])
col_Val = (initial_Coordinate[:1])
ship_Coordinates = []
i = 0
while i < ship_Length:
if vector == 'up':
#subtract from column
ship_Coordinates.append((self.column[(col_Pos - i)] + row_Val))
i += 1
if vector == 'down':
#add to column
ship_Coordinates.append((self.column[(col_Pos + i)] + row_Val))
i += 1
if vector == 'left':
#subtract from row
ship_Coordinates.append((col_Val + (self.row[(row_Pos - i)])))
i += 1
if vector == 'right':
#add to row
ship_Coordinates.append((col_Val + (self.row[(row_Pos + i)])))
i += 1
return (ship_Coordinates)
def validate_Ship_Coordinates(self, set_Coordinates):
#return True if valid, False if not valid
#a valid set of coordinates is one in which no coordinate in the set is occupied by a ship
for coordinate in set_Coordinates:
if self.board[coordinate][0] == ('boat'):
return (False)
return (True)
def assign_Ship_Coordinates(self, set_Coordinates):
#given a set of coordinates, set each coordinate to occupied by boat
for coordinate in set_Coordinates:
self.board[coordinate][0] = ('boat')
self.ships_Left.append(coordinate)
def shoot(friendly, tango, destination):
#modify friendly firing board
#write shot to friendly firing log
friendly.shots_Fired(destination)
#modify tango ship board
#if it hits a boat, remove it from tango boats left list
boat_Hit = tango.ship_Board.shot_Received(destination)
if boat_Hit == (True):
#if it hits a boat write to friendly boat hit log
friendly.hit_Boat(destination)
print "%s hit a boat!" % (destination)
def whose_Turn(player_List, turn_Count):
if turn_Count % 2 == 0:
return player_List[0]
return player_List[1]
def play_Game():
game_Won = (False)
turn_Count = 0
player_Computer = player()
player_Human = player()
# If a human is playing, set as player 1 (index 0)
players = [player_Human, player_Computer]
player1 = players[0]
player2 = players[1]
while game_Won == (False):
turn = whose_Turn(players, turn_Count)
if turn == player_Human:
"""Turn order: 1) display board, 2) pick target, 3) check target(maybe refire), 4)launch missle"""
player1.display_Boards()
destination = pick_Target_Human(player1)
shoot(player1, player_Computer, destination)
game_Won = player_Computer.game_Status()
if game_Won == (True):
print "You win!"
if turn == player_Computer:
destination = pick_Target_Computer(player2)
print "[Computer]> %s" % (destination)
shoot(player2, player1, destination)
game_Won = player1.game_Status()
if game_Won == (True):
print "Computer wins!"
turn_Count += 1
def pick_Target_Human(player):
# returns the target in format 'A4'
target_Picked = (False)
while target_Picked == (False):
print "Shoot with the format A4"
target = str(raw_input("[You]> "))
if target == ('exit'):
exit()
validity = player.firing_Board.valid_Target(target)
target_Picked = validity
return target
def pick_Target_Computer(player):
# returns the target in format 'A4'
target_Picked = (False)
while target_Picked == (False):
target = player.computer_Logic()
validity = player.firing_Board.valid_Target(target)
target_Picked = validity
return target
def play_Again():
new_Game = ''
while new_Game != 'y' and new_Game != 'n':
print "Play again? answer with y or n"
new_Game = raw_input("> ")
if new_Game == 'n':
exit()
else:
return (True)
def initiate_Game():
new_Game = (True)
while new_Game == (True):
play_Game()
new_Game = play_Again()
initiate_Game() |
e6c57c7a2d5f3ecae3b1e4fd269416f972079835 | cjmcv/hpc | /coroutine/asyncio/base_hello_world.py | 747 | 4.25 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
brief:
Hello world.
Record the basic usage of async, await and loop.
async: It is used to declare a coroutine function.
await: It is used to suspend its own coroutine and wait for another to complete.
loop: The event loop is the core of every asyncio application.
Event loops run asynchronous tasks and callbacks, perform network IO
operations, and run subprocesses.
"""
import asyncio
async def hello_world():
print("Hello World!")
await asyncio.sleep(1)
print("Hello World again!")
loop = asyncio.get_event_loop()
# Blocking call which returns when the hello_world() coroutine is done
loop.run_until_complete(hello_world())
loop.close() |
65af14afb38898ac4e6690fa7960872df045cb60 | jonathenzc/Algorithm | /LeetCode/iter1/python/CoutingBits.py | 383 | 3.515625 | 4 | class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
bitLst = []
if(num>=0):
bitLst.append(0)
for i in range(1,num+1):
bitLst.append(bitLst[i>>1]+(i&1));
return bitLst
#测试程序
s = Solution()
print(s.countBits(5)) |
e4021908627f1d0b9ad6d1cbcc8179214a040bfd | chasemp/sup | /suplib/durations.py | 789 | 3.5 | 4 | import os
import time
class Timer(object):
def __enter__(self):
self.start = time.clock()
return self
def __exit__(self, *args):
self.end = time.clock()
self.interval = self.end - self.start
def ftimeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
"""http://stackoverflow.com/a/13821695"""
import signal
class TimeoutError(Exception):
pass
def handler(signum, frame):
raise TimeoutError()
# set the timeout handler
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout_duration)
try:
result = func(*args, **kwargs)
to = False
except TimeoutError:
to = True
result = default
finally:
signal.alarm(0)
return result, to
|
def63c138ed6722668bc8eeca2936f3713278fc2 | acharles7/problem-solving | /strings/max_numerical_value.py | 332 | 4 | 4 | #Extract maximum numeric value from a given string
def extractMaximum(S):
num, res = 0, 0
for i in range(len(S)):
if(S[i] >= '0' and S[i] <= '9'):
num = num * 10 + int(S[i])
else:
res = max(res, num)
num = 0
return res
S = 'abchsd2031sdhs'
print(extractMaximum(S))
|
f15923c1032052598e9eb46427892131443ff55b | andylamgot/handwriting-digi-recognition | /handwritten_digit_recognition.py | 1,106 | 3.71875 | 4 | '''
This dataset is made up of 1797 8x8 images.
Each image is of a hand-written digit.
In order to utilize an 8x8 figure,
we have to first transform it
into a feature vector with length 64.
'''
# Import dataset
from sklearn.datasets import load_digits
# Import the sklearn for SVM
from sklearn import svm
digits = load_digits()
# Each datapoint is a 8x8 image of digit
# Plot the image
plt.gray()
plt.matshow(digits.images[20])
plt.show
print digits.images[20]
'''
Output:
[[ 0. 0. 3. 13. 11. 7. 0. 0.]
[ 0. 0. 11. 16. 16. 16. 2. 0.]
[ 0. 4. 16. 9. 1. 14. 2. 0.]
[ 0. 4. 16. 0. 0. 16. 2. 0.]
[ 0. 0. 16. 1. 0. 12. 8. 0.]
[ 0. 0. 15. 9. 0. 13. 6. 0.]
[ 0. 0. 9. 14. 9. 14. 1. 0.]
[ 0. 0. 2. 12. 13. 4. 0. 0.]]
'''
clf = svm.SVC()
# Train the model
clf.fit(digits.data[:-1], digits.target[:-1])
# Test the model
prediction = clf.predict(digits.data[20:21])
print "Predicted Digit ->",prediction
'''
Output:
Predicted Digit -> [0]
'''
|
5d02513ae81556f8700e7860d91050aa8e93edc2 | RaphaelMolina/Curso_em_video_Python3 | /Desafio_52.py | 492 | 3.734375 | 4 | from Titulo import Titulo
d = Titulo(52, 'Números primos!!!')
d.Desafio()
n = int(input('Digite um número: '))
t = int()
for contador in range(1, n + 1):
if n % contador == 0:
print('\033[34m', end=' ')
t += 1
else:
print('\033[31m', end=' ')
print('{}'.format(contador), end=' ')
print('\n\n\033[mO número {} foi divisível {} vezes.'.format(n, t))
if t == 2:
print('E por isso ele é primo!!!')
else:
print('E por isso ele não é primo!')
|
c2df64b708c5065bb57ff1b3ed28310eb71a7a90 | jawhelan/PyCharm | /PyLearn/Exercise Files/Other/Sets.py | 536 | 4.0625 | 4 | groceries = {"milk", "bread","bear","juice", "apples","bear"} # sets will not print dups
groceries2 = ["milk", "bread","bear","juice", "apples","bear"] # list will print all and are imutable
groceries3 = ("milk", "bread","bear","juice", "apples","bear") # tupels will print are and is mutable
print(groceries)
print(groceries2)
print(groceries3)
if "milk" in groceries: # since you can add dups to a set this if else can tell you if you got it or not
print("you got milk hoss!")
else:
print("you needed that")
|
6d50b8c2d78c53983c01687d3498bbcde2be2b7e | AdamZhouSE/pythonHomework | /Code/CodeRecords/2498/60782/270702.py | 794 | 3.84375 | 4 | """
题目描述
给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。
对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。
你可以返回任何满足上述条件的数组作为答案。
"""
"""
输入描述
一个非负整数数组。
2 <= A.length <= 20000
A.length % 2 == 0
0 <= A[i] <= 1000
"""
"""
输出描述
排序后的数组
"""
the_array = eval(input())
odd = []
even = []
answer = []
for i in the_array:
if i % 2 == 0:
even.append(i)
else:
odd.append(i)
while True:
try:
answer.append(even[0])
answer.append(odd[0])
del even[0]
del odd[0]
except BaseException:
break
print(answer) |
8b12cbc814aedc7643f4ed605bebd205254cc2a0 | CyberCrypter2810/CFPython | /code102/ch_6/average_temperature.py | 1,068 | 4.1875 | 4 | # average_temperature.py
'''
Program displays results from temperature.txt file
and then calculates the average of the results.
'''
# main function
def main():
# Sets up accumulator
total = 0
average = 0
try:
# Open temperature.txt
temp = open('temperature.txt', 'r')
# Displaying and calculating total values from file.
for line in temp:
average += 1
result = int(line)
print("Day", str(average) + ":", format(result, '.0f'))
total += result
print()
except Exception as error:
print(error)
print("An error has occurred because the file doesn't exist.")
else:
# Calculates average of total
final = total / average
# Display final average results
print("The average temperature in the 7 recorded days is:",
format(final, '.0f'), "degress Fahrenheit.")
# Closes file when program ends.
finally:
temp.close()
# calling main
main()
|
a87ba2a557ca288c16c45e8ebe776e8a331ce7b5 | abhisheksethi02/Hackerrank | /Html_Parser.py | 863 | 3.6875 | 4 | '''
You are given an HTML code snippet of N lines.
Your task is to print start tags, end tags and empty tags separately.
'''
import re
from html.parser import HTMLParser
if __name__ == "__main__":
class MyHTMLParser(HTMLParser):
def handle_comment(self, data):
return super().handle_comment(data)
def handle_starttag(self, tag, attrs):
print('Start :',tag)
for name, value in attrs:
if value is None:
print('->',name, '> None')
else :
print('->',name,'>',value)
def handle_endtag(self, tag):
print('End :',tag)
def handle_startendtag(self, tag, attrs):
print('Empty :',tag)
parser = MyHTMLParser()
for _ in range(int(input())):
parser.feed(input()) |
17fce39561babd3ed54d8ca13b0020b297cee228 | tnakaicode/jburkardt-python | /r8lib/p00_f.py | 8,185 | 3.578125 | 4 | #! /usr/bin/env python
#
def p00_f ( prob, n, x ):
#*****************************************************************************80
#
## P00_F evaluates the function for any problem.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 27 June 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer PROB, the number of the desired test problem.
#
# Input, integer N, the number of evaluation points.
#
# Input, real X(N), the evaluation points.
#
# Output, real VALUE(N), the function values.
#
from sys import exit
if ( prob == 1 ):
value = p01_f ( n, x )
elif ( prob == 2 ):
value = p02_f ( n, x )
elif ( prob == 3 ):
value = p03_f ( n, x )
elif ( prob == 4 ):
value = p04_f ( n, x )
elif ( prob == 5 ):
value = p05_f ( n, x )
elif ( prob == 6 ):
value = p06_f ( n, x )
elif ( prob == 7 ):
value = p07_f ( n, x )
elif ( prob == 8 ):
value = p08_f ( n, x )
else:
print ( '' )
print ( 'P00_F - Fatal error!' )
print ( ' Illegal problem number = %d' % ( prob ) )
exit ( 'P00_F - Fatal error!' )
return value
def p01_f ( n, x ):
#*****************************************************************************80
#
## P01_F evaluates the function for problem p01.
#
# Discussion:
#
# Step function.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 27 June 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer N, the number of evaluation points.
#
# Input, real X(N), the evaluation points.
#
# Output, real VALUE(N), the function values.
#
import numpy as np
value = 2.0 * np.ones ( n )
i = ( x <= 1.0 / 3.0 )
j = ( 4.0 / 5.0 <= x )
value[i] = -1.0
value[j] = +1.0
return value
def p02_f ( n, x ):
#*****************************************************************************80
#
## P02_F evaluates the function for problem p02.
#
# Discussion:
#
# Nondifferentiable function.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 27 June 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer N, the number of evaluation points.
#
# Input, real X(N), the evaluation points.
#
# Output, real VALUE(N), the function values.
#
import numpy as np
value = np.zeros ( n )
i = ( x <= 1.0 / 3.0 )
j = ( 1.0 / 3.0 < x )
value[i] = 1.0 - 3.0 * x[i]
value[j] = 6.0 * x[j] - 2.0
return value
def p03_f ( n, x ):
#*****************************************************************************80
#
## P03_F evaluates the function for problem p03.
#
# Discussion:
#
# Step function.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 27 June 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer N, the number of evaluation points.
#
# Input, real X(N), the evaluation points.
#
# Output, real VALUE(N), the function values.
#
import numpy as np
value = x * ( 10.0 * x - 1.0 ) * ( 5.0 * x - 2.0 ) * ( 5.0 * x - 2.0 ) \
* ( 4 * x - 3.4 ) * ( x - 1.0 )
return value
def p04_f ( n, x ):
#*****************************************************************************80
#
## P04_F evaluates the function for problem p04.
#
# Discussion:
#
# Step function.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 27 June 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer N, the number of evaluation points.
#
# Input, real X(N), the evaluation points.
#
# Output, real VALUE(N), the function values.
#
import numpy as np
value = np.arctan ( 40.0 * x - 15.0 )
return value
def p05_f ( n, x ):
#*****************************************************************************80
#
## P05_F evaluates the function for problem p05.
#
# Discussion:
#
# Step function.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 27 June 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer N, the number of evaluation points.
#
# Input, real X(N), the evaluation points.
#
# Output, real VALUE(N), the function values.
#
import numpy as np
value = np.cos ( 7.0 * x ) \
+ 5.0 * np.cos ( 11.2 * x ) \
- 2.0 * np.cos ( 14.0 * x ) \
+ 5.0 * np.cos ( 31.5 * x ) \
+ 7.0 * np.cos ( 63.0 * x )
return value
def p06_f ( n, x ):
#*****************************************************************************80
#
## P06_F evaluates the function for problem p06.
#
# Discussion:
#
# f(x) = exp ( - (4 * x - 1)^2 )
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 27 June 2015
#
# Author:
#
# John Burkardt
#
# Reference:
#
# Alan Genz,
# A Package for Testing Multiple Integration Subroutines,
# in Numerical Integration: Recent Developments, Software
# and Applications,
# edited by Patrick Keast and Graeme Fairweather,
# D Reidel, 1987, pages 337-340,
# LC: QA299.3.N38.
#
# Parameters:
#
# Input, integer N, the number of points.
#
# Input, real X(N), the evaluation points.
#
# Output, real VALUE(N), the function values.
#
import numpy as np
value = np.exp ( - ( 4.0 * x - 1.0 ) ** 2 )
return value
def p07_f ( n, x ):
#*****************************************************************************80
#
## P07_F evaluates the function for problem p07.
#
# Discussion:
#
# f(x) = exp ( 4 * x ) if x <= 1/2
# 0 otherwise
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 27 June 2015
#
# Author:
#
# John Burkardt
#
# Reference:
#
# Alan Genz,
# A Package for Testing Multiple Integration Subroutines,
# in Numerical Integration: Recent Developments, Software
# and Applications,
# edited by Patrick Keast and Graeme Fairweather,
# D Reidel, 1987, pages 337-340,
# LC: QA299.3.N38.
#
# Parameters:
#
# Input, integer N, the number of points.
#
# Input, real X(N), the evaluation points.
#
# Output, real VALUE(N), the function values.
#
import numpy as np
value = np.zeros ( n )
i = ( x < 0.5 )
value[i] = np.exp ( 4.0 * x[i] )
return value
def p08_f ( n, x ):
#*****************************************************************************80
#
## P08_F evaluates the function for problem p08.
#
# Discussion:
#
# This is a famous example, due to Runge. If equally spaced
# abscissas are used, the sequence of interpolating polynomials Pn(X)
# diverges, in the sense that the max norm of the difference
# between Pn(X) and F(X) becomes arbitrarily large as N increases.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 27 June 2015
#
# Author:
#
# John Burkardt
#
# Parameters:
#
# Input, integer N, the number of evaluation points.
#
# Input, real X(N), the evaluation points.
#
# Output, real VALUE(N), the function values.
#
import numpy as np
value = 1.0 / ( ( 10.0 * ( x - 0.5 ) ) ** 2 + 1.0 )
return value
def p00_f_test ( ):
#*****************************************************************************80
#
## P00_F_TEST tests P00_F.
#
# Licensing:
#
# This code is distributed under the GNU LGPL license.
#
# Modified:
#
# 27 June 2015
#
# Author:
#
# John Burkardt
#
import numpy as np
import platform
from p00_prob_num import p00_prob_num
from r8vec2_print import r8vec2_print
print ( '' )
print ( 'P00_F_TEST' )
print ( ' Python version: %s' % ( platform.python_version ( ) ) )
print ( ' P00_F evaluates any function at N points X.' )
prob_num = p00_prob_num ( )
n = 11
a = 0.0
b = 1.0
x = np.linspace ( a, b, n )
print ( '' )
for prob in range ( 1, prob_num + 1 ):
y = p00_f ( prob, n, x )
title = 'X, Y for problem ' + str ( prob )
r8vec2_print ( n, x, y, title )
#
# Terminate.
#
print ( '' )
print ( 'P00_F_TEST:' )
print ( ' Normal end of execution.' )
return
if ( __name__ == '__main__' ):
from timestamp import timestamp
timestamp ( )
p00_f_test ( )
timestamp ( )
|
d9f84025a58936165f37d0dcf3f8e22aa5135202 | hhfcode/Code-Projects | /Face Tracking Camera/Python/Camera.py | 6,193 | 3.546875 | 4 | """ This is the Class for the Camera -- Henrik"""
import cv2, Servo, time
import numpy as np
from datetime import datetime
#Frame Setup is X, Y - WE CAN USE THIS DATA TO GET TO KNOW CENTRER AND CREATE A CENTRE SQUARE THAT we AIM TO ACHIEVE
FrameX = 1080 # 200 + and - should make a centrer box from half
FrameY = 640 # 100 + and - should make a centrer box from half
#This is the Class for Camera
class Camera:
def __init__(self, frameWidth, frameHeight):
self.frameWidth = frameWidth
self.frameHeight = frameHeight
def setupFrame(self):
self.video = cv2.VideoCapture(1)
Height = self.frameHeight, Width = self.frameWidth
video = cv2.resize(Height, Width)
self.check, self.frame = video.read()
#The next Class allows our camera to follow the action
#Yes I know this calls an instance of another class, Yes I know I suck, but it works and that matters more right now :(
def actionFollower(self,horizon, verizon):
if horizon <= 200:
Servo.Servos.MoveMeLeft()
time.sleep(0.1)
if horizon >= 300:
Servo.Servos.MoveMeRight()
time.sleep(0.1)
if verizon >= 140:
Servo.Servos.MoveMeDown()
time.sleep(0.1)
if verizon <= 80:
Servo.Servos.MovemeUp()
time.sleep(0.1)
#This Method calls another module that is motion detection. It returns X and Y Coordinates that we then use to move around
#don't get me wrong, this is absolutely terrible OO code, but it works :(
def MotionDetect(self):
count = 0
cv2.namedWindow('frame')
cv2.namedWindow('dist')
# capture video stream from camera source. 0 refers to first camera, 1 referes to 2nd and so on.
cap = cv2.VideoCapture(1)
_, frame1 = cap.read()
_, frame2 = cap.read()
facecount = 0
while (True):
sdThresh = 15
font = cv2.FONT_HERSHEY_SIMPLEX
# TODO: Face Detection 1
_, frame3 = cap.read()
rows, cols, _ = np.shape(frame3)
cv2.imshow('dist', frame3)
dist = distMap(frame1, frame3)
frame1 = frame2
frame2 = frame3
# apply Gaussian smoothing
mod = cv2.GaussianBlur(dist, (9, 9), 0)
# apply thresholding
_, thresh = cv2.threshold(mod, 100, 255, 0)
# calculate st dev test
_, stDev = cv2.meanStdDev(mod)
cv2.imshow('dist', mod)
cv2.putText(frame2, "Standard Deviation - {}".format(round(stDev[0][0], 0)), (70, 70), font, 1,
(255, 0, 255), 1, cv2.LINE_AA)
if stDev > sdThresh:
print("Motion detected.. Do something!!!")
name = "file-" + str(count)
cv2.imwrite( 'C:\\private\\'+str(name)+'.jpg' , frame2 )
print('took a picture' + str(datetime.now()))
count += 1 # Accumilator
time.sleep(2)
# TODO: Face Detection 2
cv2.imshow('frame', frame2)
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()
# don't get me wrong, this is absolutely terrible OO code, but it works :(
def FaceDetect(self):
import cv2
import numpy as np
cv2.namedWindow('frame')
cv2.namedWindow('dist')
# the classifier that will be used in the cascade
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_alt.xml')
# capture video stream from camera source. 0 refers to first camera, 1 referes to 2nd and so on.
cap = cv2.VideoCapture(1)
triggered = False
sdThresh = 10
font = cv2.FONT_HERSHEY_SIMPLEX
_, frame1 = cap.read()
_, frame2 = cap.read()
facecount = 0
while (True):
_, frame3 = cap.read()
rows, cols, _ = np.shape(frame3)
cv2.imshow('dist', frame3)
dist = distMap(frame1, frame3)
frame1 = frame2
frame2 = frame3
# apply Gaussian smoothing
mod = cv2.GaussianBlur(dist, (9, 9), 0)
# apply thresholding
_, thresh = cv2.threshold(mod, 100, 255, 0)
# calculate st dev test
_, stDev = cv2.meanStdDev(mod)
cv2.imshow('dist', mod)
cv2.putText(frame2, "Standard Deviation - {}".format(round(stDev[0][0], 0)), (70, 70), font, 1,
(255, 0, 255), 1, cv2.LINE_AA)
if stDev > sdThresh:
# the cascade is implemented in grayscale mode
gray = cv2.cvtColor(frame2, cv2.COLOR_BGR2GRAY)
# begin face cascade
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=2, minSize=(20, 20))
facecount = 0
# draw a rectangle over detected faces
for (x, y, w, h) in faces:
print(x,y)
self.actionFollower(x,y)
facecount = facecount + 1
cv2.rectangle(frame2, (x, y), (x + w, y + h), (0, 255, 0), 1)
cv2.putText(frame2, "No of faces {}".format(facecount), (50, 50), font, 1, (0, 0, 255), 1,
cv2.LINE_AA)
else:
if facecount > 0:
#print("Face count:")
#print(facecount)
facecount = 0
cv2.imshow('frame', frame2)
if cv2.waitKey(1) & 0xFF == 27:
break
cap.release()
cv2.destroyAllWindows()
def distMap(frame1, frame2):
"""outputs pythagorean distance between two frames"""
frame1_32 = np.float32(frame1)
frame2_32 = np.float32(frame2)
diff32 = frame1_32 - frame2_32
norm32 = np.sqrt(diff32[:,:,0]**2 + diff32[:,:,1]**2 + diff32[:,:,2]**2)/np.sqrt(255**2 + 255**2 + 255**2)
dist = np.uint8(norm32*255)
return dist
myCamera = Camera(640,480)
|
785d40f3dea2288e3867612fc34342aba54b3375 | Hamim30/Password-Mangement | /main.py | 1,083 | 3.59375 | 4 | from cryptography.fernet import Fernet
def load_key():
file= open("key.key","rb")
key=file.read()
file.close()
return key
# def write_key():
# key=Fernet.generate_key()
# with open("key.key","wb") as key_file:
# key_file.write(key)
# write_key()
key= load_key()
fer=Fernet(key)
def view():
with open("passwords.txt","r") as f:
for line in f.readlines():
data= (line.rstrip())
user,password=data.split()
print("User: ",user , "Password: ",str(fer.decrypt(password.encode()).decode()))
def add():
name =input("Account name")
password=input("Password:")
with open("passwords.txt","a") as f:
f.write(name+" "+ fer.encrypt(password.encode()).decode()+"\n")
while True:
mode =input("Add password(add) or view password(view)?").lower().strip()
if mode=="q":
break
if mode =="add":
add()
pass
elif mode =="view":
view()
pass
else:
print("invalid mode")
continue |
2e44597ea19895b45d2f5d0912e2092719ea3a7e | thomasdeneux/xplor | /xplor/xdata.py | 111,032 | 3.59375 | 4 | """xdata module is a module to define a structure to store the data in the
form of an N dimensional array as well as the description of the data and each
of the dimensions (names, types, units, scale, ...)
This module uses:
- pandas as pd
- numpy as np
- operator
- abc
There are 6 classes in this module:
- **Color**:
This class allows defining colors, either as RGB values or using
predefined strings.
- **DimensionDescription**:
For a specific dimension, DimensionDescription stores a label,a
dimension_type ('numeric', 'logical', 'string', or 'mixed'), possibly a
unit and the corresponding conversion table.
It allows to determine the dimension_type of an element, and access the
default value of a given dimension_type.
- **Header**:
Abstract class (subclasses are CategoricalHeader and MeasureHeader).
Headers contains information about a dimension of the NDimensional
data, such as a general label, the number of element, the description
of the dimension/subdimensions, and allows to access the values to
display on the axis.
- **CategoricalHeader**:
CategoricalHeader is a subclass of Header. It is used to characterize
a dimension in which the data has no regular organisation. It usually
is a list of elements. However, such elements can have interesting
features of different types. That's why such features are stored in
columns, each of them described by a DimensionDescription object.
- **MeasureHeader**:
MeasureHeader is a subclass of Header. It is used for data acquired by
equally spaced sample in a continuous dimension such as time or space.
In which case, there is only one subdimension (i.e. only one column).
- **Xdata**:
Xdata is used to store the data. Xdata is a container for an ND
(N dimensional) array with all the values/data, as well as all of the
headers describing each of the N dimensions, stored in a list. Xdata
also has the name of the whole set of data and a data_descriptor
attribute to describe the data.
There are 2 functions in this class:
- **create_dimension_description**:
create_dimension_description gives an instance of the class
DimensionDescription from a label and an column of values of type
pandas.core.series.Series.
- **check_bank_unit**:
The functions checks if this unit is in one of the conversion tables of
the bank. If so, it returns the conversion table, else, it returns None
"""
# Authors: Elodie Ikkache CNRS <elodie.ikkache@student.ecp.fr>
# Thomas Deneux CNRS <thomas.deneux@unic.cnrs-gif.fr>
#
# version 1.0
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
# Header is abstract, subclasses are MeasureHeader and CategoricalHeader
from abc import ABC, abstractmethod
# itemgetter is used to sort a list of dictionaries
from operator import itemgetter
from pprint import pprint
class Color:
""" Defines colors.
This class allows defining colors, either as RGB values or using
predefined strings.
**Parameters**
- rgb:
Either a 3-tuple with 3 integers between 0 and 255, or a predefined
string. Predefined strings are 'black', 'white', 'red', 'green',
'blue', 'yellow', 'cyan', 'magenta'
**Attributes**
- rgb:
3-tuple with 3 integers between 0 and 255
"""
def __init__(self, rgb):
if isinstance(rgb, str):
if rgb == 'black':
self.rgb = [0, 0, 0]
elif rgb == 'white':
self.rgb = [255, 255, 255]
elif rgb == 'red':
self.rgb = [255, 0, 0]
elif rgb == 'green':
self.rgb = [0, 255, 0]
elif rgb == 'blue':
self.rgb = [0, 0, 255]
elif rgb == 'yellow':
self.rgb = [255, 255, 0]
elif rgb == 'cyan':
self.rgb = [0, 255, 255]
elif rgb == 'magenta':
self.rgb = [255, 0, 255]
else:
raise Exception("String argument is not a recognized color "
"name.")
else:
try:
self.rgb = [int(x) for x in rgb]
if len(self.rgb) != 3:
raise Exception()
for i in range(3):
x = self.rgb[i]
if x < 0 or x > 255:
raise Exception("int out of range")
except:
raise Exception("Argument must be either a 3-element color "
"definition or a string color name.")
def __eq__(self, other):
return self.rgb == other.rgb
class DimensionDescription:
""" This class aims at defining a dimension.
This class allows to define a dimension with a name, a type ('numeric,
'logical', 'string', 'color' or 'mixed'), and possibly a unit for
numerical dimensions.
**Parameters**
- label:
name for the dimension
(type str (e.g. 'time'))
- dimension_type:
can be 'numeric', 'logical', 'string', 'color' or 'mixed'
- unit:
One can define only the unit (e.g. mm) or the conversions as well in
the form of a list (e.g. ['mm', 10**(-3), 'm', 1]).
(type str or list)
optional (default value = None)
**Attributes**
- label:
name of the dimension
(type str)
- dimension_type:
'numeric', 'logical', 'string', 'color' or 'mixed'
- unit:
currently used unit
(type str)
- all_units:
list of dictionaries for unit conversions
**Methods**
- set_dim_type_to_mixed:
changing the dimension_type to 'mixed' if adding values that are not
of the correct dimension_type (merging lines for instance)
- copy:
to copy a DimensionDescription instance
*(static methods)*
- infer_type(x, getdefaultvalue=False):
gives the dimension_type of the x element and possibly the associated
defaultvalue
- defaultvalue(dimension_type):
gives the default value associated to a certain dimension_type
**Examples**
t = DimensionDescription('time','numeric',['s, 1, 'ms', 10**(-3),
'min', 60, 'hour', 3600])
c = DimensionDescription('condition','string')
**Note**
Values corresponding to a DimensionDescription of dimension_type
'color' are Color objects
"""
def __init__(self,
label,
dimension_type,
unit=None):
"""Constructor of the class DimensionDescription"""
# Checking arguments and setting properties.
# label must be a string
if not isinstance(label, str):
raise Exception('label must be a string')
self._label = label
# dimension_type must be 'numeric', 'logical', 'string, or 'mixed'
if not (dimension_type in ['numeric', 'logical', 'string', 'color',
'mixed']):
raise Exception("a dimension_type must be 'numeric', 'logical',"
"'string', 'color' or 'mixed'")
self._dimension_type = dimension_type
# only 'numeric' dimensions can have a unit, and this is not mandatory
if unit is None:
self._unit = None
self._all_units = None
elif dimension_type != 'numeric':
raise Exception("only numeric DimensionDescriptions can have a"
" unit")
# the unit can be given in the form of a string ...
elif isinstance(unit, str):
self._unit = unit
self._all_units = [{'unit': unit, 'value': 1.0}]
# ...or in the form of a list of linked units and conversion
# coefficients
elif not unit: # pythonic way of checking whether a list is empty,
# by using the implicit booleanness
raise Exception("there must be at least one unit")
elif isinstance(unit, list):
list_length = len(unit)
if list_length % 2 != 0:
raise Exception("unit must be a string with the unit symbol or"
" a list of the symbols of the unit followed"
"by the conversion indicator"
" (e.g. ['mm', 10**(-3), 'm', 1]")
# One of the units must be the reference.
# That means that one conversion coefficient must be equal to one.
reference = False
self._all_units = []
for i in range(0, list_length, 2):
# assign pairs of items to unit (string) and value (float)
try:
d = {'unit': str(unit[i]), 'value': float(unit[i+1])}
except:
raise Exception("unit name must be a string and conversion"
" coefficient must be a numerical scalar")
self._all_units += [d]
# take the first unit with value 1 has reference
if d['value'] == 1 and not reference:
reference = True
self._unit = d['unit']
if not reference:
raise Exception("one of the conversion coefficients must be "
"equal to one to define a reference")
# sort the list of units according conversion coefficients
self._all_units.sort(key=itemgetter('value'))
# Checking if the type of unit is either str, list or if it is None.
else:
raise Exception("unit must be a string with the unit symbol or a "
"list of the symbols of the unit followed by "
"the conversion indicator (e.g. "
"['mm', 10**(-3), 'm', 1])")
self._check_type_fun = None
# Attributes label, dimension_type, unit and all_units can be seen but not
# modified outside of the class (only get methods, no setters).
@property
def label(self):
"""name for the dimension (type str (e.g. 'time'))"""
return self._label
@property
def dimension_type(self):
"""'numeric', 'logical', 'string', 'color' or 'mixed'"""
return self._dimension_type
@property
def unit(self):
"""currently used unit (type str)"""
return self._unit
@property
def all_units(self):
"""conversion table (type list of dict)"""
return self._all_units
def __eq__(self, other):
return ((self._label == other._label) and (self._unit == other._unit)
and (self._all_units == other._all_units))
def set_dim_type_to_mixed(self):
"""change the dimension_type to mixed"""
self._dimension_type = 'mixed'
def copy(self):
"""copy a DimensionDescription instance"""
obj = DimensionDescription(self.label, self.dimension_type)
obj._unit = self._unit
if self._all_units is None:
obj._all_units = None
else:
obj._all_units = self._all_units.copy()
return obj
def check_type(self, x, raise_error=False):
"""check that a given value satisfies dimension_type"""
if self.dimension_type == 'mixed':
ok = True
else:
if self._check_type_fun is None:
# Check type
if self.dimension_type == 'mixed':
self._check_type_fun = lambda u: True
elif self.dimension_type == 'logical':
self._check_type_fun = lambda u: isinstance(u, bool)
elif self.dimension_type == 'string':
self._check_type_fun = lambda u: isinstance(u, str)
elif self.dimension_type == 'numeric':
self._check_type_fun = (
lambda u: type(u) in [int, float, complex,
np.float64, np.int64])
elif self.dimension_type == 'color':
self._check_type_fun = lambda u: isinstance(u, Color)
else:
raise Exception
if isinstance(x, list):
ok = True
for elem in x:
ok = self._check_type_fun(elem)
if not ok:
break
else:
ok = self._check_type_fun(x)
# Return check result, or raise an error
if raise_error:
if not ok:
raise Exception("Value does not satisfy dimension_type '"
+ self.dimension_type + "'")
else:
return ok
@staticmethod
def infer_type(x, getdefaultvalue=False):
"""infer_type is a static method to guess the dimension_type of an
element x and if required, the associated default value"""
if isinstance(x, bool):
dim_type = 'logical'
elif isinstance(x, str):
dim_type = 'string'
elif type(x) in [int, float, complex, np.float64, np.int64]:
dim_type = 'numeric'
elif isinstance(x, Color):
dim_type = 'color'
else:
dim_type = 'mixed'
if getdefaultvalue:
return dim_type, DimensionDescription.defaultvalue(dim_type)
else:
return dim_type
# Calculating a default value for the different dimension_types.
@staticmethod
def defaultvalue(dimension_type):
"""defaultvalue is a static method to access the default value of a
given dimension_type"""
if dimension_type == 'numeric':
return 0
elif dimension_type == 'logical':
return False
elif dimension_type == 'string':
return ''
elif dimension_type == 'color':
return Color((0, 149, 182))
# it is a nice color, different from that of the background
elif dimension_type == 'mixed':
return None
else:
raise Exception("This function only gives the default value for"
" the following types: 'numeric', 'logical', "
"'string', 'color' or 'mixed'")
def create_dimension_description(label, column=None):
"""the function creates an instance of DimensionDescription.
create_dimension_description gives an instance of the class
DimensionDescription from a label and an column of values of type
pandas.core.series.Series.
If column is None, the DimensionDescription instance will be of
dimension_type 'mixed' by default.
When using this function, no unit is specified, so
dimension_description.unit will be None.
**Parameters**
- label:
label for the DimensionDescription instance
(type str)
- column:
values to determine the dimension_type of the DimensionDescription
(type pandas.core.series.Series, shape (n,1))
**returns**
DimensionDescription instance
"""
if not isinstance(label, str):
raise Exception("label must be of type str")
# if no table of value is given:
if column is None:
return DimensionDescription(label, 'mixed')
elif not isinstance(column, pd.core.series.Series):
raise Exception("column must be of type pandas.core.series.Series")
elif len(column.shape) != 1:
raise Exception("column must be of shape (n,1)")
# if a table of value is given, we must determine the dimension_type
# we must check all the elements to make sure it is not a 'mixed' type
dimension_type = DimensionDescription.infer_type(column[0])
for i in range(column.shape[0]):
if DimensionDescription.infer_type(column[i]) != dimension_type:
dimension_type = 'mixed'
break
return DimensionDescription(label, dimension_type)
class Header(ABC):
""" This abstract class allows the creation of headers for the different
dimensions of a dataset.
Header is an abstract class that has two subclasses: CategoricalHeader and
MeasureHeader.
A Header object fully describes a dimension.
A CategoricalHeader is used for data with no regular organisation.
It usually correspond to a list of elements. However, such elements can
have interesting features of different types. That's why such features are
stored in columns, each of them described by a DimensionDescription object.
A MeasureHeader is used for data acquired with regular intervals in a
continuous dimension such as time or space. In which case, there is only
one subdimension (i.e. only one column witch is not stored).
**Attributes**
- label:
name of the dimension (type str)
- column_descriptors:
list of the DimensionDescription of each of the columns of values
- is_measure:
true if the header is a MeasureHeader instance, false if it is a
CategoricalHeader instance
- is_categorical_with_values:
true if it is an instance of CategoricalHeader and that values is not
None. If it is a categorical header but with no column or a measure
header, it is false.
- is_undifferentiated:
true if it is a categorical header with no values
(not is_categorical_with_values)
**Methods**
*(abstract methods)*
- n_elem:
number of element in the column(s)/ number of samples
- is_categorical:
differentiate measure and categorical headers for the properties
is_measure, is_categorical_with_values and is_undifferentiated
- __eq__:
compares all the fields of the headers (returns True if all the
fields are the same) it can be used by writing header1 == header2
- get_n_columns:
gives the number of columns (1 for MeasureHeader, 0 to n for
CategoricalHeader)
- get_units:
gives the list of the unit used for each column ('no unit' is
returned for each column with no specified unit)
- get_all_units:
gives the list of conversion table for each column ('no unit' is
returned for each column with no specified unit)
- disp:
gives the main attributes of a Header
- get_value(line_num, column=None):
gives the value located at the line line_num and at the column column
(defined by it's label or it's number) or the fist one. Since we use
python, we have decided that to access the first element of the
column, line_num must be equal to 0.
- get_item_name(line_num):
line_num can here be an integer or a list of integer. The function
returns the corresponding values of the first column.
- copy:
creates a copy of the header
*(non abstract method)*
- check_header_update(flag, ind, new_header):
flag: 'all', 'dim_chg', 'new', 'remove', 'chg', 'perm','chg&new' or
'chg&rm'
ind: numpy.array of shape (n,)
basics checks when updating data and giving a new header
"""
# Define an abstract constructor which will not be used, but serves for
# the the code analyzer to learn the attributes mandatory for a Header
# class
@abstractmethod
def __init__(self):
self._label = None
self._column_descriptors = None
self._n_elem = None
# Attributes label and column_descriptors can be seen but not modified
# outside of the class (only get methods, no setters).
@property
def label(self):
"""general label of the header"""
return self._label
@property
def column_descriptors(self):
"""list of DimensionDescription instances describing each column"""
return self._column_descriptors
# Properties is_measure, is_undifferentiated, is_categorical_with_values
# help to differentiate different types of headers faster in other modules
@property
def is_measure(self):
"""fast way to differentiate measure headers from categorical ones"""
return not self.is_categorical
@property
def is_categorical_with_values(self):
"""fast way to test if a header is categorical with values
(ie list of elements)"""
return self.is_categorical and self.n_column > 0
@property
def is_undifferentiated(self):
"""fast way to test if a header is categorical with no values"""
return self.is_categorical and self.n_column == 0
# Methods
def check_header_update(self, flag, ind, new_header):
"""basics checks when updating data and giving a new header"""
# check types of parameters
assert isinstance(new_header, Header)
# 'dim_chg' flag allows any change!
if flag == 'dim_chg':
return
# check that the types are coherent
if self.is_categorical != new_header.is_categorical:
raise Exception("both headers must be of same type")
# check that labels are preserved
if new_header._label != self._label:
raise Exception("both headers must have the same label")
# check that column descriptors are preserved (note that there can
# be additional columns though)
if (new_header._column_descriptors[:len(self._column_descriptors)] !=
self._column_descriptors):
raise Exception("sub-labels are not preserved")
# no need to check n_elem for flag 'all'
if flag == 'all':
return # no constraint on n_elem
# check n_elem
if flag == 'new':
nc = len(ind)
elif flag in ['chg' 'perm']:
nc = 0
elif flag == 'remove':
nc = -len(ind)
elif flag == 'chg&new':
nc = len(ind[1])
elif flag == 'chg&rm':
nc = -len(ind[1])
else:
raise Exception("Unknown flag")
if new_header.n_elem != self._n_elem + nc:
raise Exception("the new headers has the wrong number of elements")
# not checking values (if CategoricalHeader) or units/start/scale (
# if Measure Header... that would be too long
# abstract methods
@abstractmethod
def n_elem(self):
"""gives the the number of elements/samples in that dimension"""
pass
@abstractmethod
def is_categorical(self):
"""used for the properties is_measure, is_categorical_with_values and
is_undifferentiated, fast way to differentiate categorical and measure
headers"""
pass
@abstractmethod
def __eq__(self, other):
"""Override the default Equals behavior"""
pass
@property
@abstractmethod
def n_column(self):
"""returns the number of columns"""
pass
@abstractmethod
def get_units(self):
"""gives a list of the units of all the columns"""
pass
@abstractmethod
def get_all_units(self):
"""gives a list of the conversion tables for the units of all the
columns"""
pass
@abstractmethod
def disp(self):
"""display some information about the header"""
pass
@abstractmethod
def get_value(self, line, column=None):
"""get the value of the line of number line of the column column
(defined by it's label or number) or the first column"""
pass
@abstractmethod
def get_item_name(self, line_num):
"""get the value(s) of the line(s) in line_num (it can be an int or a list
of int), of the first column"""
pass
@abstractmethod
def copy(self):
"""creates a copy of the Header instance"""
pass
class CategoricalHeader(Header):
""" This class allows the creation of a header for a categorical dimension
of a dataset.
CategoricalHeader is used for categorical dimensions of a dataset. This
means that this dimension is either not continuous or that the data has not
been collected regularly in this dimension. Therefore, their is no scale,
measure for this dimension. It is more a collection of objects.
A CategoricalHeader has a general label as well as one or several
DimensionDescription objects stored in column_descriptors to describe each
of the features. For each feature, values can be given (e.g. for 'fruits'
values would be 'apple', 'pear', 'blueberry', 'watermelon'...) or be a list
of numbers. The first case corresponds to 'is_categorical_with_values', the
second to 'is_undifferentiated'
**Parameters**
- label:
name of the header
(type: str)
- column_descriptors:
description of the dimension of each feature
(type str, DimensionDescription or a list of such elements)
(optional, the case with no column is possible. The legend would then
be a list of int [1, 2, ...], it is undifferentiated)
- values:
content of the various subdimensions
(type DataFrame from pandas (pandas.core.frame.DataFrame) of shape
(n_elem, len(column_descriptors))
(optional if it is just undifferentiated series of measures and that
n_elem is given)
- n_elem:
number of element in the column(s)
(type int)
(optional if values is specified)
**Attributes**
- label:
name of the dimension
(type str)
- column_descriptors:
list of the DimensionDescription of each of the columns of values
- values:
content of the various subdimensions (pandas DataFrame
(pandas.core.frame.DataFrame)of shape (n_elem, len(column_descriptors))
**Methods**
*(methods imposed by inheritance)*
- n_elem:
number of element in the column(s)/ number of samples number of lines
of values
- is_categorical:
differentiate measure and categorical headers for the properties
is_measure, is_categorical_with_values and is_undifferentiated
- is_categorical:
returns True since it is the class CategoricalHeader
- __eq__:
compares all the fields of the headers (returns True if all the
fields are the same) it can be used by writing header1 == header2
- n_column:
gives the number of columns (1 for MeasureHeader, 0 to n for
CategoricalHeader)
- get_units:
gives the list of the unit used for each column ('no unit' is returned
for each column with no specified unit)
- get_all_units:
gives the list of conversion table for each column ('no unit' is
returned for each column with no specified unit)
- disp:
gives the main attributes of a Header
- get_value(line_num, column=None):
gives the value located at the line line_num and at the column column
(defined by it's label or it's number) or the fist one. Since we use
python, we have decided that to access the first element of the
column, line_num must be equal to 0.
- get_item_name(line_num):
line_num can here be an integer or a list of integer. The function
returns the corresponding values of the first column
- copy:
creates a copy of the categorical header
*(other methods)*
- add_column(column_descriptor, values):
column_descriptor must be of type str or DimensionDescription
values must be of type pandas.core.series.Series this method allows
to created a new categorical header from the attributes of a previous
categorical header, while adding a new column (it can be useful for
selections or to add colors)
- update_categorical_header(flag, ind, values):
flags can be: 'all', 'new', 'chg', 'chg&new', 'chg&rm', 'remove',
'perm'
idn indicates were the changes take place
values contains the new values
This method allows filters to create a new categorical header from
the current one, with some changes in the values
- merge_lines(ind):
When merging some data, the corresponding header's lines must be
merged as well. merge_lines returns for each column all the
encountered values with no repetitions in the from of a pandas Series.
"""
# noinspection PyMissingConstructor
def __init__(self,
label,
column_descriptors=None,
values=None,
n_elem=None):
"""Constructor of the class CategoricalHeader"""
# label is not optional and must be of type string
# label can be different from the labels of the columns
assert isinstance(label, str), "The header's label must be of type str"
# It is possible not to provide column descriptors and values: in
# this case the values will be a table with zero column, and n_elem
# must be provided to inform about the number of rows.
if values is None:
assert n_elem is not None, \
"if there are no values, n_elem must be provided"
assert column_descriptors is None, \
"if there are no values, there are no columns to be described"
values = pd.DataFrame(np.zeros((n_elem, 0)))
column_descriptors = []
# values is a DataFrame
# we have to check that it has the correct shape
# labels of the data_frame will not be taken into consideration
assert isinstance(values, pd.core.frame.DataFrame), \
"values must be a pandas DataFrame"
if n_elem is None:
n_elem = values.shape[0]
else:
assert n_elem == values.shape[0], \
"n_elem does not match the shape of values"
# column descriptors can be provided as string, DimensionDescription
# object (if n_column==1), or list thereof
n_column = values.shape[1]
if (isinstance(column_descriptors, str)
or isinstance(column_descriptors, DimensionDescription)):
# convert sting or DimensionDescription to 1-element list
column_descriptors = [column_descriptors]
else:
assert isinstance(column_descriptors, list), \
("column_descriptors must be of type str, "
"DimensionDescription or a list of such elements")
assert len(column_descriptors) == n_column, \
"column_descriptors does not match the number of values columns"
# create DimensionDescription objects or check their type
for i in range(n_column):
dim_descriptor = column_descriptors[i]
if isinstance(dim_descriptor, str):
column_descriptors[i] = create_dimension_description(
dim_descriptor, values[i])
elif isinstance(column_descriptors[i], DimensionDescription):
for j in range(n_elem):
dim_descriptor.check_type(values[i][j], True)
else:
raise Exception("all column_descriptors elements must be "
"either of type str or DimensionDescription")
# that's it, set properties
self._label = label
self._values = values
self._column_descriptors = column_descriptors
# private property but with get access
@property
def n_elem(self):
"""number of elements/samples in that dimension, line number of values
"""
return self.values.shape[0]
@property
def is_categorical(self):
"""CategoricalHeader instances are all categorical"""
return True
@property
def values(self):
"""values is a pandas DataFrame"""
return self._values
# methods
def __eq__(self, other):
"""Override the default Equals behavior"""
# the two headers must have the same type
if not isinstance(other, CategoricalHeader):
return False
# label, column descriptors and values must be the same (but not
# necessarily additional properties that might be added later such
# as _id)
return (
(other._label == self._label)
and (other._column_descriptors == self._column_descriptors)
and (other._values.equals(self._values))
)
@property
def n_column(self):
"""returns the number of columns"""
return len(self._column_descriptors)
def get_units(self):
"""gives a list of the units of all the columns"""
return [x.unit for x in self._column_descriptors]
def get_all_units(self):
"""gives a list of the conversion tables for the units of all the
columns"""
return [x.all_units for x in self._column_descriptors]
def disp(self):
"""display some information about the header"""
print("CategoricalHeader: ", self._label)
print("columns:")
columns = self._column_descriptors
for i in range(self.n_column):
label = str(columns[i].label)
if columns[i].unit is None:
unit = ''
else:
unit = ' (' + columns[i].unit + ')'
print(label + unit)
print("n_elem:" + str(self.n_elem))
def get_value(self, line, column=None):
"""get the value of the line of number line of the column defined by
column"""
if not isinstance(line, int):
raise Exception("line must be of type int")
if line >= self.n_elem or line < 0:
raise Exception("line must be in [0, n_elem[")
if column is None:
if self.n_column == 0:
return []
else:
raise Exception("not implemented yet (should return the whole "
"line)") # TODO
if isinstance(column, int):
if column >= self.n_column or column < 0:
raise Exception("column is a str or an int in [0, n_col[")
return self._values[column][line]
elif isinstance(column, str):
for j in range(self.n_column):
if column == self._column_descriptors[j].label:
return self._values[j][line]
raise Exception("column is either the label of a column or it's"
"number (int)")
else:
raise Exception("column is either the label of a column or it's"
"number (int)")
# if it is a string
def get_item_name(self, line):
"""get the value(s) of the line(s) in line_num (it can be an int or a list
of int), of the first column"""
# this function is the same for both the headers, but it could be
# modified to choose witch column we want for categorical headers
if isinstance(line, int):
if line >= self.n_elem or line < 0:
raise Exception("line_num must be in [0, n_elem[")
if self.n_column:
return self.get_value(line, 0)
else:
return str(line)
elif isinstance(line, list):
if self.n_column:
return [self.get_value(i, 0) for i in line]
else:
return [str(i) for i in line]
else:
raise Exception("line_num must be an int or a list of int")
def add_column(self, column_descriptor, values):
"""this method allows to add a column to a categorical header"""
if not isinstance(values, pd.core.series.Series):
raise Exception("values must be of type pd.core.series.Series")
elif values.shape[0] != self._values.shape[0]:
raise Exception("values must have the correct amount of lines")
if isinstance(column_descriptor, str):
column_descriptor = create_dimension_description(column_descriptor,
values)
elif not isinstance(column_descriptor, DimensionDescription):
raise Exception("column_descriptor must be of type str or "
"DimensionDescription")
else:
# if it was a given DimensionDescriptor, let's check that the
# dimension_type correspond to that of the values
column_descriptor.check_type(values)
column_descriptors = self._column_descriptors + [column_descriptor]
new_values = self._values.copy()
new_values[len(column_descriptors)-1] = values
return(CategoricalHeader(self._label,
column_descriptors,
new_values))
def update_categorical_header(self, flag, ind, values):
"""updates the values of a categorical header"""
# flag 'all': all the values can change, they are all given
# in values argument of type pandas DataFrame
if flag == 'all':
if (ind is None) or (ind == []) or (ind == range(self.n_elem)):
if not isinstance(values, pd.core.frame.DataFrame):
raise Exception("values must be a pandas DataFrame")
elif values.shape[1] != self._values.shape[1]:
raise Exception("values must keep the same number of "
"columns")
column_descriptors = self._column_descriptors
for j in range(values.shape[1]):
if column_descriptors[j].dimension_type != 'mixed':
for i in range(values.shape[0]):
# noinspection PyPep8
if (column_descriptors[j].dimension_type !=
DimensionDescription.infer_type(
values[j][i])):
column_descriptors[j].set_dim_type_to_mixed()
return CategoricalHeader(self._label,
column_descriptors,
values=values)
else:
raise Exception("ind must be empty or the list of all the "
"indices that have changed")
# flag 'new': adding new lines, some of which can be the merging of
# many lines
elif flag == 'new':
if (ind is None) or (isinstance(ind, list)):
if not isinstance(values, list):
raise Exception("values must be a list of pandas Series")
new_values = self._values.copy()
# no need for deep copy for the descriptors
new_descriptors = self.column_descriptors
if new_descriptors is None:
new_descriptors = []
for s in values:
j = self.n_column
if not isinstance(s, pd.core.series.Series):
raise Exception("values must be a list of pandas "
"Series")
elif s.shape[0] != j:
raise Exception("all series in values must have the"
" same number of elements that the "
"number of column of the header")
for i in range(j):
new_descriptors[i].check_type(s[i], True)
new_values = new_values.append(s, ignore_index=True)
return CategoricalHeader(self._label,
new_descriptors,
values=new_values)
else:
raise Exception("ind must be empty or the list of all the "
"indices that have changed")
# flag 'chg': changing some lines (keep the same number of lines)
elif flag == 'chg':
if not isinstance(ind, list):
raise Exception("ind must be the list of the indices of the"
" lines that have changed")
elif not isinstance(values, list):
raise Exception("values must be a list of the new lines "
"(pandas series)")
elif len(values) != len(ind):
raise Exception("values and ind must have the same length")
new_values = self._values.copy()
new_descriptors = self.column_descriptors
j = self.n_column
for i in range(len(ind)):
if not isinstance(ind[i], int):
raise Exception("ind must be the list of the indices of"
"the lines that have changed")
elif (ind[i] < 0) or (ind[i] >= self.n_elem):
raise Exception("for a chg flag, indices must be in range"
" of n_elem")
elif not isinstance(values[i], pd.core.series.Series):
raise Exception("new lines must be pandas series")
elif values[i].shape[0] != j:
raise Exception("all series must have the same number of "
"element as the number of column of the "
"header")
for cc in range(j):
dim_type = new_descriptors[cc].dimension_type
if (dim_type != 'mixed') or (
dim_type != DimensionDescription.infer_type(
values[i][cc])):
new_descriptors[i].set_dim_type_to_mixed()
new_values.iloc[ind[i]] = values[i]
return CategoricalHeader(self._label,
new_descriptors,
new_values)
# flag 'remove': suppress some lines
elif flag == 'remove':
if not isinstance(ind, list):
raise Exception("ind must be the list of the indices of the"
" lines that have changed")
for i in ind:
if not isinstance(i, int):
raise Exception("all indices must be of type int")
elif (i < 0) or (i >= self.n_elem):
raise Exception("indices must correspond to an existing"
" line")
if (values is not None) & (values != []):
raise Exception("no new values can be given when only "
"removing lines")
new_values = self._values.copy()
new_values = new_values.drop(new_values.index[ind])
new_values = new_values.reset_index(drop=True)
return CategoricalHeader(self._label,
self._column_descriptors,
new_values)
# flag 'perm': change the lines order
elif flag == 'perm':
if (values is not None) & (values != []):
raise Exception("no new values can be given when only "
"permuting lines")
elif not isinstance(ind, list):
raise Exception("ind must be the list of the indices of the"
" lines that have changed")
elif len(ind) != self.n_elem:
raise Exception("ind must be the list of all the indices in "
"the new order")
new_values = pd.DataFrame()
for i in range(len(ind)):
if not isinstance(ind[i], int):
raise Exception("all indices must be integers")
new_values = new_values.append(self._values.iloc[ind[i]])
new_values = new_values.reset_index(drop=True)
return CategoricalHeader(self._label,
self._column_descriptors,
new_values)
# flag 'chg&new': combination of 'chg' and 'new'
elif flag == 'chg&new':
if not isinstance(ind, list):
raise Exception("ind must be a list of the list of the "
"indices that have changed and the list of "
"those to remove")
elif not isinstance(values, list):
raise Exception("values is of type list")
elif len(values) != 2:
raise Exception("values must contains the values to change "
"and the values to add")
elif not (isinstance(values[0], list) and
isinstance(values[1], list)):
raise Exception("values must contains the values to change "
"and the values to add in two lists")
elif isinstance(ind[0], list):
ind_chg = ind[0]
else:
ind_chg = ind
# let's first change the lines that needs to be changed...
if len(values[0]) != len(ind_chg):
raise Exception("all the lines to be changed must be given "
"a value")
new_values = self._values.copy()
new_descriptors = self.column_descriptors
j = self.n_column
for i in range(len(ind_chg)):
if not isinstance(ind_chg[i], int):
raise Exception("all indices must be of type int")
elif (ind_chg[i] < 0) or (ind_chg[i] >= self.n_elem):
raise Exception("for a chg action, indices must be in "
"range of n_elem")
elif not isinstance(values[0][i], pd.core.series.Series):
raise Exception("new lines must be pandas series")
elif values[0][i].shape[0] != j:
raise Exception("all series must have the same number of "
"element as the number of column of the "
"header")
for cc in range(j):
dim_type = new_descriptors[cc].dimension_type
if (dim_type != 'mixed') or (
dim_type != DimensionDescription.infer_type(
values[0][i][cc])):
new_descriptors[i].set_dim_type_to_mixed()
new_values.iloc[ind_chg[i]] = values[0][i]
# ...now let's add the new lines
for s in values[1]:
if not isinstance(s, pd.core.series.Series):
raise Exception("values must be a list of pandas Series")
elif s.shape[0] != j:
raise Exception("all series in values must have the same "
"number of elements that the number of "
"column of the header")
for i in range(j):
dim_type = new_descriptors[i].dimension_type
if (dim_type != 'mixed') or (
dim_type != DimensionDescription.infer_type(s[i])):
new_descriptors[i].set_dim_type_to_mixed()
new_values = new_values.append(s, ignore_index=True)
return CategoricalHeader(self._label,
new_descriptors,
new_values)
# flag 'chg&rm': combination of 'chg' and 'rm'
elif flag == 'chg&rm':
if not isinstance(ind, list):
raise Exception("ind must be a list of the list of the "
"indices that have changed and the list of "
"those to remove")
elif not isinstance(values, list):
raise Exception("values is of type list")
elif len(ind) != 2:
raise Exception("ind must contains the lines to change "
"and the lines to remove")
elif not (isinstance(ind[0], list) and
isinstance(ind[1], list)):
raise Exception("values must contains the values to change "
"and the values to add in two lists")
# let's first change the lines that needs to be changed...
if len(values) != len(ind[0]):
raise Exception("all the lines to be changed must be given "
"a value")
new_values = self._values.copy()
new_descriptors = self.column_descriptors
j = self.n_column
for i in range(len(ind[0])):
if not isinstance(ind[0][i], int):
raise Exception("all indices must be of type int")
elif (ind[0][i] < 0) or (ind[0][i] >= self.n_elem):
raise Exception("for a chg action, indices must be in "
"range of n_elem")
elif not isinstance(values[i], pd.core.series.Series):
raise Exception("new lines must be pandas series")
elif values[i].shape[0] != j:
raise Exception("all series must have the same number of "
"element as the number of column of the "
"header")
for cc in range(j):
dim_type = new_descriptors[cc].dimension_type
if (dim_type != 'mixed') or (
dim_type != DimensionDescription.infer_type(
values[i][cc])):
new_descriptors[i].set_dim_type_to_mixed()
new_values.iloc[ind[0][i]] = values[i]
# ...now let's remove the unwanted lines
for i in ind[1]:
if not isinstance(i, int):
raise Exception("all indices must be of type int")
elif (i < 0) or (i >= self.n_elem):
raise Exception("indices must correspond to an existing"
" line")
new_values = new_values.drop(new_values.index[ind[1]])
new_values = new_values.reset_index(drop=True)
return CategoricalHeader(self._label,
new_descriptors,
new_values)
# all the accepted flags were listed before, so the argument is not
# valid
raise Exception("the given flag must be 'all', 'perm', 'chg', 'new'"
" 'remove', 'chg&new', or 'chg&rm'")
def merge_lines(self, ind):
"""creating the values (pandas Series) for merged lines"""
if not isinstance(ind, list):
raise Exception("ind must be a list of indices")
n_col = len(self._column_descriptors)
merge = []
for j in range(n_col):
merge.append([])
for i in ind:
if not isinstance(i, int):
raise Exception("all indices must be of type int")
elif i < 0 or i > self.n_elem:
raise Exception("indices must correspond to an element of "
"values")
for j in range(n_col):
if not (self._values[j][i] in merge[j]):
merge[j].append(self._values[j][i])
for j in range(n_col):
if self._column_descriptors[j].dimension_type == 'color':
red = 0
green = 0
blue = 0
for i in (merge[j]):
red += i.rgb[0]
green += i.rgb[1]
blue += i.rgb[2]
n = len(merge[j])
merge[j] = Color((red/n, green/n, blue/n))
return pd.Series(merge)
def copy(self):
"""creates a copy of a categoricalHeader: note that the list of column
descriptor elements is a 'simple copy' as its elements themselves
are only shallow copied"""
return CategoricalHeader(self._label,
self._column_descriptors.copy(),
self._values.copy())
class MeasureHeader(Header):
""" This class allows the creation of a header for a measurable dimensions
of a dataset.
MeasureHeader is used for a measurable dimensions of a dataset. This
means that this dimension is continuous and that the data has been
collected regularly in this dimension. Therefore, a scale, a start
attributes can be defined.
A MeasureHeader has a general label and only one column (there is only one
feature of interest). This column is described by a single
DimensionDescription object, but it is still stored in a list
(column_descriptors) in order to keep the similarity between the different
types of headers. The values are not stored because they can be calculated
easily from the start and scale attributes and the n_elem property.
**Parameters**
- label:
name of the header
(type str)
- start:
first value of this dimension
(type float or int)
- n_elem:
number of element in the column
(type int)
- scale:
interval between the values of this dimension
(type float or int)
- unit:
One can define only the unit (e.g. mm) or the conversions as well in
the form of a list (e.g. ['mm', 10**(-3), 'm', 1])
(type str or list)
(optional)
- check_bank:
Default value of check_bank is False. If is it True, a unit must be
specified, in order to check in the bank of conversion tables if one
exists for the given unit.
(optional)
- column_descriptors:
description of the dimension (it's label must be the same as the
general label of the header)
(type DimensionDescription)
(optional)
**Attributes**
- label:
name of the dimension (type str)
- column_descriptors:
list of one DimensionDescription instance
- unit:
main unit for this dimension (i.e. for which conversion value is one)
- start:
first value of this dimension (type float)
- scale:
interval between the values of this dimension (type float)
**Methods**
*(methods imposed by inheritance)*
- n_elem:
number of element in the column(s)/ number of samples
- is_categorical:
differentiate measure and categorical headers for the properties
is_measure, is_categorical_with_values and is_undifferentiated
- __eq__:
compares all the fields of the headers (returns True if all the
fields are the same) it can be used by writing header1 == header2
- n_column:
gives the number of columns (1 for MeasureHeader, 0 to n for
CategoricalHeader)
- get_units:
gives the list of the unit used for each column ('no unit' is
returned for each column with no specified unit)
- get_all_units:
gives the list of conversion table for each column ('no unit' is
returned for each column with no specified unit)
- disp:
gives the main attributes of a Header
- get_value(line_num, column = None):
gives the value located at the line line_num and at the column column
(defined by it's label or it's number) or the fist one.Since we use
python, we have decided that to access the first element of the
column, line_num must be equal to 0.
- get_item_name(line_num):
line_num can here be an integer or a list of integer. The function
returns the corresponding values of the first column.
*(other methods)*
- update_measure_header(start = None, n_elem = None,scale = None):
creates a new measure header from the attributes of a previous one,
and the specified changes
- copy:
creates a copy of a MeasureHeader instance
"""
# noinspection PyMissingConstructor
def __init__(self,
label,
start,
n_elem,
scale,
unit=None,
check_bank=False,
column_descriptors=None):
"""Constructor of the class MeasureHeader"""
# label must be of type str
if not isinstance(label, str):
raise Exception("label must be of type str")
self._label = label
# start must be of type int or float
if not (isinstance(start, float) or isinstance(start, int)):
raise Exception("start must be of type float or int")
self._start = float(start)
# n_elem must be of type int
if not isinstance(n_elem, int):
raise Exception("n_elem must be of type int")
self._n_elem = n_elem
# scale must be of type int or float
if not (isinstance(scale, float) or isinstance(scale, int)):
raise Exception("scale must be of type float or int")
self._scale = float(scale)
# case with a column_descriptors parameter
if isinstance(column_descriptors, DimensionDescription):
if column_descriptors.label != label:
raise Exception(
"the general label and the label from the "
"column_descriptors must be the same"
)
elif unit is not None:
raise Exception(
"you can either choose to use unit (and possibly"
" check_bank) or to use column_descriptors, not both"
)
self._column_descriptors = [column_descriptors]
elif column_descriptors is not None:
raise Exception("column_descriptors must be of type"
" DimensionDescription")
elif not isinstance(check_bank, bool):
raise Exception("check_bank must be a boolean")
elif unit is None:
if check_bank:
raise Exception("Specify a unit so as to checkout the bank")
dim_descriptor = DimensionDescription(label, 'numeric')
self._column_descriptors = [dim_descriptor]
elif isinstance(unit, str) or isinstance(unit, list):
if check_bank:
all_units = check_bank_unit(unit)
if all_units is None:
dim_descriptor = DimensionDescription(label,
'numeric',
unit)
else:
units = []
for dic in all_units:
units += [dic['unit'], dic['value']]
dim_descriptor = DimensionDescription(label,
'numeric',
units)
else:
dim_descriptor = DimensionDescription(label, 'numeric', unit)
self._column_descriptors = [dim_descriptor]
else:
raise Exception("unit must be a str or a list")
# private property but with get access
@property
def is_categorical(self):
"""MeasureHeader instances are all not categorical"""
return False
@property
def unit(self):
"""main unit (i.e. with conversion value equal to 1)"""
return self._column_descriptors[0].unit
@property
def start(self):
"""int or float, first value of the dimension"""
return self._start
@property
def scale(self):
"""interval between the values of this dimension"""
return self._scale
@property
def n_elem(self):
"""number of elements in the dimension"""
return self._n_elem
# methods
def __eq__(self, other):
"""Override the default Equals behavior"""
# the two headers must have the same type
if not isinstance(other, MeasureHeader):
return False
if self._label != other._label:
return False
if self._start != other._start:
return False
if self.n_elem != other._n_elem:
return False
if self._scale != other._scale:
return False
self_descriptor = self._column_descriptors[0]
other_descriptor = other._column_descriptors[0]
if self_descriptor.label != other_descriptor.label:
return False
if self_descriptor.dimension_type != other_descriptor.dimension_type:
return False
if self_descriptor.unit != other_descriptor.unit:
return False
if self_descriptor.all_units != other_descriptor.all_units:
return False
return True
@property
def n_column(self):
"""returns the number of columns"""
return 1
def get_units(self):
"""gives the unit if it exist, in the form of a list to be compatible
with CategoricalHeaders"""
if self._column_descriptors[0].unit is None:
return ['no unit']
return [self._column_descriptors[0].unit]
def get_all_units(self):
"""gives the conversion tables in the form of a list with a single
element to be compatible with Categorical headers"""
if self._column_descriptors[0].unit is None:
return ['no unit']
return [self._column_descriptors[0].all_units]
def disp(self):
"""display some information about the header"""
print("MeasureHeader: " + self._label)
print("unit: " + self.get_units()[0])
print("start: " + str(self._start))
print("scale: " + str(self._scale))
print("n_elem: " + str(self._n_elem))
def get_value(self, line, column=None):
"""get the value of the line of number line of the first column"""
if not (column is None or column == 0):
raise Exception("Measure headers have only one column, column"
"argument must be None or 0")
if not isinstance(line, int):
raise Exception("line must be of type int")
if line >= self._n_elem or line < 0:
raise Exception("line must be in [0, n_elem[")
# Since we use python, we have decided that to access the first element
# of the column, line must be equal to 0.
return self._start + line * self._scale
def get_item_name(self, line_num):
"""get the value(s) of the line(s) in line_num (it can be an int or a list
of int), of the first column"""
if isinstance(line_num, int):
if line_num >= self._n_elem or line_num < 0:
raise Exception("line_num must be in [0, n_elem[")
return self.get_value(line_num)
elif isinstance(line_num, list):
item_names = []
for n in line_num:
if not isinstance(n, int):
raise Exception("all line numbers must be integers")
elif n >= self._n_elem or n < 0:
raise Exception("line_num must be in [0, n_elem[")
item_names += [self.get_value(n)]
return item_names
raise Exception("line_num must be an int or a list of int")
def update_measure_header(self,
start=None,
n_elem=None,
scale=None):
"""creates a new measure header from the attributes of a previous one,
and the specified changes"""
if start is None:
start = self._start
elif not (isinstance(start, int) or isinstance(start, float)):
raise Exception("start must be of type int or float")
if n_elem is None:
n_elem = self._n_elem
elif not isinstance(n_elem, int):
raise Exception("n_elem must be of type int")
if scale is None:
scale = self._scale
elif not (isinstance(scale, float) or isinstance(scale, int)):
raise Exception("scale must be of type int or float")
return(MeasureHeader(self._label,
start,
n_elem,
scale,
column_descriptors=self._column_descriptors[0]))
def copy(self):
"""creates a copy of a measure header"""
descriptor = self.column_descriptors[0].copy()
return MeasureHeader(self.label,
self.start,
self.n_elem,
self.scale,
column_descriptors=descriptor)
class Xdata:
"""This class allows the creation of a ND dataset, with headers for each
dimension and a name.
Xdata is used to store the data. Xdata is a container for an ND
(N dimensional) array with all the values/data, as well as all of the
headers describing each of the N dimensions, stored in a list. Xdata also
has the name of the whole set of data and a data_descriptor attribute to
describe the data.
Xdata includes a handling of events.
TODO: explain better the event part
**Parameters**
- name:
name of the dataset (type str)
- data:
N dimensional numpy array with the data itself
- headers:
list of the headers describing each of the N dimensions
- unit:
simple unit or list of conversion
**Attributes**
- data:
N dimensional numpy.ndarray with the data itself
- headers:
list of the headers describing each of the N dimensions
- name:
name of the dataset (type str)
- data_descriptor:
DimensionDescription instance describing the dataset
**Methods**
- get_n_dimensions:
gives the number of dimensions of xdata (it corresponds to the
number of headers)
- shape:
gives the shape of the data (it corresponds to the number of elements
for each dimension)
- copy:
creates a copy of a Xdata instance
- update_data(new_data):
Simply changing some values in data by giving a whole new numpy array.
Those changes can change the length of measure headers or categorical
headers that are undifferentiated. This method returns a new Xdata
instance.
- update_xdata(flag, dim, ind, data_slices, modified_header):
- flag
- 'data_chg' to only change some data (it can modify the length of
measure headers and undifferentiated headers but not
categorical_with_values headers), this flag is not supposed to be
used: to simply change the data, one must use update_data.
However, the flag can be 'all' but with no new header, in witch
case, we transform it to the 'data_chg' flag (this is why it is
tolerated as an argument as well)
- 'all' to change the data and modify the header (possible
modifications are given for modified_header)
- 'chg' to change some lines of a header and corresponding data
- 'new' to add lines in a dimension
- 'remove' to remove some lines
- 'chg&new' to change and add some lines
- 'chg&rm' to change and remove some lines
- 'perm' to permute some lines
- dim:
(int) number of the modified header
- ind:
(list of int) indices of lines that are changing
- data_slices:
new values for the modified lines
- modified_header:
same header as before but with a few changes (adding columns,
lines, changing values depending of the type of header).
This method allows to update a header and the corresponding data,
the shape of data might be modified but the dimensions are still
representing the same thing(DimensionDescriptions are not changed,
(except for dimension_type that might become 'mixed' if some lines are
merged)).It returns a new data instance. TODO : change the returns part
- modify_dimensions(flag, dim, new_data, new_headers):
- flag
- 'global' to change everything,
- 'dim_chg' to change one dimension/dimensions,
- 'dim_insert' to insert a dimension/dimensions,
- 'dim_rm' to remove a dimension/dimensions,
- 'dim_perm' to permute the dimensions
- dim:
list of the dimensions to be changed
- new_data:
full numpy.array with the whole data (except for flag
'dim_perm')
- new_headers:
list of the new headers
This methods allows to modify the structure of a Xdata instance, i.e.
to modify the DimensionDescriptions in the list of headers (and
therefore the data) new headers do not represent the same thing as
before. This method also allows to change the number of dimensions.
It returns a new Xdata instance. TODO : change the returns part
"""
def __init__(self,
name,
data,
headers,
unit):
"""Constructor of the class Xdata"""
# name must be a string
if not isinstance(name, str):
raise Exception("name must be of type str")
self._name = name
# data must be a numpy array and headers a list with the same length
if not isinstance(data, np.ndarray):
raise Exception("data must be of type numpy.ndarray")
elif not isinstance(headers, list):
raise Exception("headers must be of type list")
elif len(headers) != len(data.shape):
raise Exception("each dimension must be described by a header")
self._data = data
for h in range(len(headers)):
if not isinstance(headers[h], Header):
raise Exception("headers must only contain header elements")
if headers[h].n_elem != data.shape[h]:
raise Exception("the number of elements must be the same in "
"the data and in the header")
self._headers = headers
# unit must allow creation of a DimensionDescription instance
if isinstance(unit, str) or isinstance(unit, list) or (unit is None):
self._data_descriptor = DimensionDescription(name, 'numeric', unit)
else:
raise Exception("unit must a string or a list of conversion")
@property
def name(self):
"""name of the data with the complementary information stored in
headers and data_descriptor"""
return self._name
@property
def headers(self):
"""list of the headers for each dimension"""
return self._headers
@property
def data(self):
"""ND numpy.array of numerical data"""
return self._data
@property
def data_descriptor(self):
"""DimensionDescription instance to describe the content of data"""
return self._data_descriptor
def get_n_dimensions(self):
"""gives the number of dimensions of the data"""
return len(self.headers)
def shape(self):
"""gives the number of element in each dimension"""
return self.data.shape
def copy(self):
"""gives a copy of a Xdata instance"""
data = self.data.copy()
headers = []
for h in self.headers:
headers.append(h.copy())
if self.data_descriptor.all_units is None:
unit = None
else:
unit = []
for i in self.data_descriptor.all_units:
unit.append(i['unit'])
unit.append(i['value'])
return Xdata(self.name, data, headers, unit)
def update_data(self, new_data):
"""Creating a new Xdata instance, with updated data and the same
headers as before (except for the length of some measure headers and
undifferentiated headers)"""
# checking the number of dimension
if len(new_data.shape) != self.get_n_dimensions():
raise Exception("update_data method does not allow to change the "
"number of dimensions, please use "
"modify_dimensions method instead")
# for each dimension, check if the number of element has changed
# if it has changed, make sure this change is allowed
# if so, update the header
new_xdata = self.copy()
for dim in range(self.get_n_dimensions()):
if new_data.shape[dim] != self.headers[dim].n_elem:
old_h = new_xdata.headers[dim]
if self.headers[dim].is_categorical_with_values:
raise Exception("categorical headers with values can't "
"have new not defined elements")
elif self.headers[dim].is_undifferentiated:
n = new_data.shape[dim] - self.headers[dim].n_elem
if n > 0:
values = [pd.Series([])] * n
h = old_h.update_categorical_header(
'new', None, values)
new_xdata.headers[dim] = h
else: # the number element has decreased
ind = range(n)
h = old_h.update_categorical_header(
'rm', ind, None)
new_xdata.headers[dim] = h
else: # the header is a measure header
h = old_h.update_measure_header(
n_elem=new_data.shape[dim])
new_xdata.headers[dim] = h
# once all headers are updated, update the data itself
new_xdata._data = new_data
return new_xdata
# TODO : notify instead of returns
def update_xdata(self, flag, dim, ind, data_slices, modified_header):
"""creates a new Xdata instance with the same attributes as the
previous one, except for lines changed both in the data and the
corresponding header"""
if not isinstance(dim, int):
raise Exception("dim is of type int")
elif (dim < 0) or (dim >= self.get_n_dimensions()):
raise Exception("dim must correspond to an existing dimension")
nd = self.get_n_dimensions()
old_header = self.headers[dim]
# for flag 'all': the whole content of the header has been modified
# data_slices is a numpy array with all the data
# check that flag 'all' is not in fact a flag 'data_chg'
if flag == 'all':
# checking that ind is coherent
if not ((ind is None) or (isinstance(ind, list))):
raise Exception("ind must be None, an empty list, or the list"
" of all indices")
# checking that modified_header is a Header
if not isinstance(modified_header, Header):
raise Exception("modified_header must be of type Header")
# checking that flag is not in fact 'data_chg'
# i.e. that the header has changed
if old_header == modified_header:
flag = 'data_chg'
# checking that data_slices can replace data
if not isinstance(data_slices, np.ndarray):
raise Exception("data_slices must be a numpy array for a flag "
"'all'")
elif len(data_slices.shape) != nd:
raise Exception("data_slices must have the same number of "
"dimensions as data")
for n in range(nd):
# 'all' flag does not change the number of elements in the
# various dimensions except for the one that is being modified
if n == dim:
if data_slices.shape[dim] != modified_header.n_elem:
raise Exception("the new data and the new header must"
" have the same number of elements in"
" the concerned dimension")
elif modified_header.label != old_header.label:
raise Exception("label of the header can't be changed"
" with this method")
elif old_header.is_measure:
if modified_header.unit != old_header.unit:
raise Exception("flag 'all' can't change the unit"
" of the header")
elif modified_header.all_units != old_header.all_units:
raise Exception("flag 'all' can't change the unit"
" of the header")
else:
if data_slices.shape[n] != self.shape()[n]:
raise Exception("'all' flag only allows one dimension"
" to change its number of elements")
new_xdata = self.copy()
new_xdata._data = data_slices
new_xdata._headers[dim] = modified_header
return new_xdata, flag
if flag == 'data_chg':
# This flag is not supposed to be used except if the given flag was
# 'all' but the header was the same
# header must be None or the same as the old one
if not ((modified_header is None) or
(modified_header == old_header)):
raise Exception("'data_chg' flag can't change the header")
if not ((ind is None) or (isinstance(ind, list))):
raise Exception("ind must be None, an empty list, or the list"
" of all indices")
elif not isinstance(data_slices, np.ndarray):
raise Exception("data_slices must be a numpy array for a flag "
"'data_chg'")
elif data_slices.shape != self.data.shape:
raise Exception("flag 'data_chg' can't change the dimensions "
"nor number of elements in the dimensions")
new_xdata = self.copy()
new_xdata._data = data_slices
return new_xdata, flag
elif flag == 'chg':
# lets first check the header
if not isinstance(modified_header, Header):
raise Exception("modified_header must be of type Header")
elif (modified_header.is_measure or
modified_header.is_undifferentiated):
if modified_header != old_header:
raise Exception("measure headers and undifferentiated "
"ones can't be modified by a flag 'chg'")
else: # then it's a categorical_with_values header
if old_header.n_elem != modified_header.n_elem:
raise Exception("'chg' flag can't change the number of "
"elements in the dimension")
elif (old_header.n_column !=
modified_header.n_column):
raise Exception("'chg' flag can't change the number of "
"columns of the header")
elif (old_header.get_all_units() !=
modified_header.get_all_units()):
raise Exception("'chg' flag can't change the units")
elif old_header.label != modified_header.label:
raise Exception("'chg' flag can't change labels")
for i in range(old_header.n_column):
if (old_header.column_descriptors[i].label !=
modified_header.column_descriptors[i].label):
raise Exception("'chg' flag can't change labels")
# note: we didn't check that the values haven't changed for the
# lines that are not supposed to be modified in order to fasten the
# update for huge sets of data. Such changes are usually done by
# filters, that are tested to do the right thing
# now lets check that ind and data_slices have correct type and
# same length
if not isinstance(ind, list):
raise Exception("ind must be of type list")
elif not isinstance(data_slices, list):
raise Exception("data_slices must be of type list")
elif len(ind) != len(data_slices):
raise Exception("data_slices must have the same number of "
"element as ind")
new_xdata = self.copy()
change_slice = [slice(None, None, None)] * (
self.get_n_dimensions())
for i in range(len(ind)):
change_slice[dim] = ind[i]
if not isinstance(ind[i], int):
raise Exception("all indices must be of type int")
elif not isinstance(data_slices[i], np.ndarray):
raise Exception("all data_slices must be of type "
"numpy.ndarray")
elif len(data_slices[i].shape) != (len(self.data.shape) - 1):
raise Exception("data_slice doesn't have a correct shape")
for j in range(len(data_slices[i].shape)):
if j < dim:
if data_slices[i].shape[j] != self.data.shape[j]:
raise Exception("data_slice doesn't have a correct"
" number of elements")
if j > dim:
if data_slices[i].shape[j] != self.data.shape[j + 1]:
raise Exception("data_slice doesn't have a correct"
" number of elements")
# now lets modify the data ...
new_xdata._data[tuple(change_slice)] = data_slices[i]
# ...and replace the header
new_xdata._headers[dim] = modified_header
return new_xdata, flag
elif flag == 'new':
# lets first test ind
if not (isinstance(ind, list) or (ind is None)):
raise Exception("ind must be None, or an empty list, or the "
"list of new indices")
# now lets check data_slices
elif not isinstance(data_slices, list):
raise Exception("data_slices must be of type list")
for i in range(len(data_slices)):
if not isinstance(data_slices[i], np.ndarray):
raise Exception("all data_slices must be of type "
"numpy.ndarray")
elif len(data_slices[i].shape) != (len(self.data.shape) - 1):
raise Exception("data_slice doesn't have a correct shape")
for j in range(len(data_slices[i].shape)):
if j < dim:
if data_slices[i].shape[j] != self.data.shape[j]:
raise Exception("data_slice doesn't have a correct"
" number of elements")
if j > dim:
if data_slices[i].shape[j] != self.data.shape[j + 1]:
raise Exception("data_slice doesn't have a correct"
" number of elements")
# now we check the header
if not isinstance(modified_header, Header):
raise Exception("modified_header must be of type Header")
elif (modified_header.is_measure != old_header.is_measure) or (
modified_header.is_undifferentiated !=
old_header.is_undifferentiated):
raise Exception("header can't change its type with flag 'new'")
if modified_header.n_elem != old_header.n_elem + len(data_slices):
raise Exception("the number of elements added in a "
"dimension must be the same in data and "
"in the header")
if modified_header.is_categorical_with_values:
if (old_header.n_column !=
modified_header.n_column):
raise Exception("'new' flag can't change the number of "
"columns of the header")
elif (old_header.get_all_units() !=
modified_header.get_all_units()):
raise Exception("'new' flag can't change the units")
elif old_header.label != modified_header.label:
raise Exception("'new' flag can't change labels")
for i in range(old_header.n_column):
if (old_header.column_descriptors[i].label !=
modified_header.column_descriptors[i].label):
raise Exception("'new' flag can't change labels")
# note: we didn't check that the values haven't changed for the
# lines that are not supposed to be modified in order to fasten the
# update for huge sets of data. Such changes are usually done by
# filters, that are tested to do the right thing
new_xdata = self.copy()
# Now lets replace the header
new_xdata._headers[dim] = modified_header
# And recreate the data (can't change the size of a numpy array)
shape = list(self.shape())
shape[dim] += len(data_slices)
new_data_array = np.zeros(tuple(shape))
old_data = [slice(None, None, None)] * nd
old_data[dim] = slice(0, self._headers[dim].n_elem, None)
new_xdata._data = new_data_array
new_xdata._data[tuple(old_data)] = self.data
for i in range(len(data_slices)):
new_data = old_data
new_data[dim] = self._headers[dim].n_elem + i
slice_of_data = np.array([data_slices[i]])
new_xdata._data[tuple(new_data)] = slice_of_data
return new_xdata, flag
elif flag == 'remove':
# lets first check that ind and data_slices has correct type
if not isinstance(ind, list):
raise Exception("ind must be of type list")
elif not ((data_slices is None) or (data_slices == [])):
raise Exception("data_slices must be empty")
for i in range(len(ind)):
if not isinstance(ind[i], int):
raise Exception("all indices must be of type int")
# now lets check the header and its number of elements
if not isinstance(modified_header, Header):
raise Exception("modified_header must be of type Header")
elif (modified_header.is_measure != old_header.is_measure) or (
modified_header.is_undifferentiated !=
old_header.is_undifferentiated):
raise Exception("header can't change its type with flag "
"'remove'")
if modified_header.n_elem != old_header.n_elem - len(ind):
raise Exception("the number of elements removed in a "
"dimension must be the same in data and "
"in the header")
if modified_header.is_categorical_with_values:
if (old_header.n_column !=
modified_header.n_column):
raise Exception("'remove' flag can't change the number of"
" columns of the header")
elif (old_header.get_all_units() !=
modified_header.get_all_units()):
raise Exception("'remove' flag can't change the units")
elif old_header.label != modified_header.label:
raise Exception("'remove' flag can't change labels")
for i in range(old_header.n_column):
if (old_header.column_descriptors[i].label !=
modified_header.column_descriptors[i].label):
raise Exception("'remove' flag can't change labels")
# note: we didn't check that the values haven't changed for the
# lines that are not supposed to be modified in order to fasten the
# update for huge sets of data. Such changes are usually done by
# filters, that are tested to do the right thing
new_xdata = self.copy()
# Now lets replace the header
new_xdata._headers[dim] = modified_header
new_xdata._data = np.delete(new_xdata._data, ind, dim)
return new_xdata, flag
elif flag == 'chg&new':
# lets first check data_slices
if not isinstance(data_slices, list):
raise Exception("data_slices must be a list of two elements: "
"first the list of the lines that have "
"changed, second the list of new lines")
elif len(data_slices) != 2:
raise Exception("data_slices must be a list of two elements: "
"first the list of the lines that have "
"changed, second the list of new lines")
elif not (isinstance(data_slices[0], list) and
isinstance(data_slices[1], list)):
raise Exception("data_slices must be a list of two elements: "
"first the list of the lines that have "
"changed, second the list of new lines")
# now lets check ind
if not isinstance(ind, list):
raise Exception("ind must be the list of indices of the lines"
" to be changed")
elif isinstance(ind[0], list):
if len(ind) != 2:
raise Exception("ind must be the list of indices of the "
"lines to be changed")
elif not ((ind[1] is None) or isinstance(ind[1], list)):
raise Exception("the list of new lines to add must be "
"empty,, None or the list of the indices")
ind = ind[0]
# now lets check the modified header and check that the length of
# the arguments is coherent
if not isinstance(modified_header, Header):
raise Exception("modified_header must be of type Header")
elif (modified_header.is_measure != old_header.is_measure) or (
modified_header.is_undifferentiated !=
old_header.is_undifferentiated):
raise Exception("header can't change its type with flag "
"'chg&new'")
if (modified_header.n_elem !=
old_header.n_elem + len(data_slices[1])):
raise Exception("the number of elements added in a "
"dimension must be the same in data and "
"in the header")
if modified_header.is_categorical_with_values:
if (old_header.n_column !=
modified_header.n_column):
raise Exception("'chg&new' flag can't change the number "
"of columns of the header")
elif (old_header.get_all_units() !=
modified_header.get_all_units()):
raise Exception("'chg&new' flag can't change the units")
elif old_header.label != modified_header.label:
raise Exception("'chg&new' flag can't change labels")
for i in range(old_header.n_column):
if (old_header.column_descriptors[i].label !=
modified_header.column_descriptors[i].label):
raise Exception("'chg&new' flag can't change labels")
# note: we didn't check that the values haven't changed for the
# lines that are not supposed to be modified in order to fasten the
# update for huge sets of data. Such changes are usually done by
# filters, that are tested to do the right thing
if len(ind) != len(data_slices[0]):
raise Exception("all changed slices must be given new values")
new_xdata = self.copy()
new_xdata._headers[dim] = modified_header
shape = list(self.shape())
shape[dim] += len(data_slices)
new_data_array = np.zeros(tuple(shape))
old_data = [slice(None, None, None)] * nd
old_data[dim] = slice(0, self._headers[dim].n_elem, None)
new_xdata._data = new_data_array
# lets copy the 'old' values
new_xdata._data[tuple(old_data)] = self.data
# and change the lines before adding the new ones
change_slice = [slice(None, None, None)] * nd
for i in range(len(ind)):
change_slice[dim] = ind[i]
if not isinstance(ind[i], int):
raise Exception("all indices must be of type int")
elif not isinstance(data_slices[0][i], np.ndarray):
raise Exception("all data_slices must be of type "
"numpy.ndarray")
elif len(data_slices[0][i].shape) != len(self.data.shape) - 1:
raise Exception("data_slice doesn't have a correct shape")
for j in range(len(data_slices[0][i].shape)):
if j < dim:
if data_slices[0][i].shape[j] != self.data.shape[j]:
raise Exception("data_slice doesn't have a correct"
" number of elements")
if j > dim:
if (data_slices[0][i].shape[j] !=
self.data.shape[j + 1]):
raise Exception("data_slice doesn't have a correct"
" number of elements")
# slices and indices are correct, lets modify the data
new_xdata._data[tuple(change_slice)] = data_slices[0][i]
# now lets add the new lines
for i in range(len(data_slices[1])):
if not isinstance(data_slices[1][i], np.ndarray):
raise Exception("all data_slices must be of type "
"numpy.ndarray")
elif len(data_slices[1][i].shape) != len(self.data.shape) - 1:
raise Exception("data_slice doesn't have a correct shape")
for j in range(len(data_slices[1][i].shape)):
if j < dim:
if data_slices[1][i].shape[j] != self.data.shape[j]:
raise Exception("data_slice doesn't have a correct"
" number of elements")
if j > dim:
if (data_slices[1][i].shape[j] !=
self.data.shape[j + 1]):
raise Exception("data_slice doesn't have a correct"
" number of elements")
new_data = old_data
new_data[dim] = self._headers[dim].n_elem + i
slice_of_data = np.array([data_slices[1][i]])
new_xdata._data[tuple(new_data)] = slice_of_data
return new_xdata, flag
elif flag == 'chg&rm':
# lets first check data_slices
if not isinstance(data_slices, list):
raise Exception("data_slices must be a list of the lines to "
"change")
# now lets check ind
if (not isinstance(ind, list)
or len(ind) != 2
or not isinstance(ind[0], list)
or not isinstance(ind[1], list)):
raise Exception("ind must be the list of the list of indices "
"of the lines to be changed and the list of "
"the lines to be removed")
# now lets check the modified header and check that the length of
# the arguments is coherent
if not isinstance(modified_header, Header):
raise Exception("modified_header must be of type Header")
elif (modified_header.is_measure != old_header.is_measure) or (
modified_header.is_undifferentiated !=
old_header.is_undifferentiated):
raise Exception("header can't change its type with flag "
"'chg&rm'")
if modified_header.n_elem != old_header.n_elem - len(ind[1]):
raise Exception("the number of elements removed in a "
"dimension must be the same in data and "
"in the header")
if modified_header.is_categorical_with_values:
if (old_header.n_column !=
modified_header.n_column):
raise Exception("'chg&rm' flag can't change the number "
"of columns of the header")
elif (old_header.get_all_units() !=
modified_header.get_all_units()):
raise Exception("'chg&rm' flag can't change the units")
elif old_header.label != modified_header.label:
raise Exception("'chg&rm' flag can't change labels")
for i in range(old_header.n_column):
if (old_header.column_descriptors[i].label !=
modified_header.column_descriptors[i].label):
raise Exception("'chg&rm' flag can't change labels")
# note: we didn't check that the values haven't changed for the
# lines that are not supposed to be modified in order to fasten the
# update for huge sets of data. Such changes are usually done by
# filters, that are tested to do the right thing
if len(ind[0]) != len(data_slices):
raise Exception("all changed slices must be given new values")
new_xdata = self.copy()
new_xdata._headers[dim] = modified_header
# let's change the lines before removing some
change_slice = [slice(None, None, None)] * nd
for i in range(len(ind)):
change_slice[dim] = ind[0][i]
if not isinstance(ind[0][i], int):
raise Exception("all indices must be of type int")
elif not isinstance(data_slices[i], np.ndarray):
raise Exception("all data_slices must be of type "
"numpy.ndarray")
elif len(data_slices[i].shape) != len(self.data.shape) - 1:
raise Exception("data_slice doesn't have a correct shape")
for j in range(len(data_slices[i].shape)):
if j < dim:
if data_slices[i].shape[j] != self.data.shape[j]:
raise Exception("data_slice doesn't have a correct"
" number of elements")
if j > dim:
if data_slices[i].shape[j] != self.data.shape[j + 1]:
raise Exception("data_slice doesn't have a correct"
" number of elements")
# slices and indices are correct, lets modify the data
new_xdata._data[tuple(change_slice)] = data_slices[i]
# now lets remove the lines we don't want to keep
new_xdata._data = np.delete(new_xdata._data, ind[1], dim)
return new_xdata, flag
elif flag == 'perm':
# data_slices must be None, because all the values will be
# calculated from the permutation
if data_slices is not None:
raise Exception("data_slices must be None for a 'perm' flag")
# now let's check the Header
if not isinstance(modified_header, Header):
raise Exception("modified_header must be of type Header")
elif (modified_header.is_measure or
modified_header.is_undifferentiated):
if modified_header != old_header:
raise Exception("measure headers and undifferentiated "
"ones can't be modified by a flag 'perm'")
else: # then it's a categorical_with_values header
if old_header.n_elem != modified_header.n_elem:
raise Exception("'perm' flag can't change the number of "
"elements in the dimension")
elif (old_header.n_column !=
modified_header.n_column):
raise Exception("'perm' flag can't change the number of "
"columns of the header")
elif (old_header.get_all_units() !=
modified_header.get_all_units()):
raise Exception("'perm' flag can't change the units")
elif old_header.label != modified_header.label:
raise Exception("'perm' flag can't change labels")
for i in range(old_header.n_column):
if (old_header.column_descriptors[i].label !=
modified_header.column_descriptors[i].label):
raise Exception("'perm' flag can't change labels")
# note: we didn't check that the values haven't changed for the
# lines that are not supposed to be modified in order to fasten the
# update for huge sets of data. Such changes are usually done by
# filters, that are tested to do the right thing
# now lets check that ind is a permutation of the indices of the
# lines
if len(ind) != self.headers[dim].n_elem:
raise Exception("ind is not a permutation of the indices")
for i in range(self.headers[dim].n_elem):
if i not in ind:
raise Exception("ind is not a permutation of the indices")
# now lets permute the data and replace the header
new_xdata = self.copy()
new_xdata._headers[dim] = modified_header
permute_slice = [slice(None, None, None)] * nd
old_slice = [slice(None, None, None)] * nd
for i in range(len(ind)):
if i != ind[i]:
# this test saves some time if not all the lines are
# permuted
permute_slice[dim] = ind[i]
old_slice[dim] = i
new_xdata._data[permute_slice] = self.data[old_slice]
return new_xdata, flag
# all accepted flags with this method are already taken care of
# flag argument is either not a flag or not one accepted by this method
raise Exception("flag must be 'all', 'chg', 'new', 'remove', 'perm' "
"'chg&new' or 'chg&rm'")
# TODO : notify instead of returns
def modify_dimensions(self, flag, dim, new_data, new_headers):
"""creates a new Xdata instance with changes for the dimensions"""
if flag == 'global':
# lets first check that dim is coherent
if (dim is not None) and dim != []:
raise Exception("for a 'global' flag, everything is replaced,"
" dim must be empty")
# other checks will be done in the constructor
if self.data_descriptor.all_units is None:
unit = None
else:
unit = []
for i in self.data_descriptor.all_units:
unit.append(i['unit'])
unit.append(i['value'])
new_xdata = Xdata(self.name, new_data, new_headers, unit)
return new_xdata, flag
elif flag == 'dim_chg':
try:
headers = self.headers.copy()
if len(dim) != len(new_headers):
raise Exception("dim must have the same length as "
"new_headers")
for i in range(len(dim)):
headers[dim[i]] = new_headers[i].copy()
if self.data_descriptor.all_units is None:
unit = None
else:
unit = []
for i in self.data_descriptor.all_units:
unit.append(i['unit'])
unit.append(i['value'])
new_xdata = Xdata(self.name, new_data, headers, unit)
return new_xdata, flag
except:
raise Exception("incorrect arguments")
elif flag == 'dim_insert':
try:
headers = self.headers.copy()
if len(dim) != len(new_headers):
raise Exception("dim must have the same length as "
"new_headers")
for i in range(len(dim)):
# like the insert method for lists, if the index is out
# of range, the new element will just be appended at the
# end of the xdata element
headers.insert(dim[i], new_headers[i])
if self.data_descriptor.all_units is None:
unit = None
else:
unit = []
for i in self.data_descriptor.all_units:
unit.append(i['unit'])
unit.append(i['value'])
new_xdata = Xdata(self.name, new_data, headers, unit)
return new_xdata, flag
except:
raise Exception("incorrect arguments")
elif flag == 'dim_rm':
if not (new_headers is None or new_headers == []):
raise Exception("when removing dimensions, no new dimension "
"must be given")
try:
headers = []
if len(dim) != self.get_n_dimensions() - len(new_data.shape):
raise Exception("dim must the number of dimensions to "
"remove")
for i in range(len(self.headers)):
if i not in dim:
headers.append(self.headers[i].copy())
if self.data_descriptor.all_units is None:
unit = None
else:
unit = []
for i in self.data_descriptor.all_units:
unit.append(i['unit'])
unit.append(i['value'])
new_xdata = Xdata(self.name, new_data, headers, unit)
return new_xdata, flag
except:
raise Exception("incorrect arguments")
elif flag == 'dim_perm':
# lets first check that dim is a permutation of the dimensions
if len(dim) != len(self.headers):
raise Exception("dim is not a permutation of the dimensions")
for i in range(len(self.headers)):
if i not in dim:
raise Exception("dim is not a permutation of the "
"dimensions")
# now lets build the headers and the data if they are not given
if new_headers is None:
new_headers = []
for d in dim:
new_headers.append(self.headers[d].copy())
if new_data is None:
new_data = np.transpose(self.data, dim)
# if new_headers or new_data is given, it's not checked in order to
# save some computation time
if self.data_descriptor.all_units is None:
unit = None
else:
unit = []
for i in self.data_descriptor.all_units:
unit.append(i['unit'])
unit.append(i['value'])
try:
new_xdata = Xdata(self.name, new_data, new_headers, unit)
return new_xdata, flag
except:
raise Exception("arguments are not valid")
# all accepted flags with this method are already taken care of
# flag argument is either not a flag or not one accepted by this method
raise Exception("flag must be 'global', 'dim_chg', 'dim_insert', "
"'dim_rm', or 'dim_perm'")
# TODO : notify instead of returns
def check_bank_unit(unit):
"""The functions checks if this unit is in one of the conversion tables of
the bank. If so, it returns the conversion table, else, it returns None
**Parameters**
- unit: type str, name of the unit
**returns**
a conversion table for the given unit if it exists in the bank
"""
# TODO
return []
def disp(obj):
"""generic disp method"""
try:
pprint(vars(obj))
except TypeError:
pprint(obj)
if __name__ == '__main__':
c = MeasureHeader('toto', 1, 25, 3, 's')
|
af6f8328f1e6a304734b2e31c7f70405bb4ad2bb | jhoneal/Python-class | /tuition.py | 256 | 3.5 | 4 | """Suppose that the tuition for a university is $10,000 this
year and tuition increases 7% every year. In how
many years will the tuition be doubled?"""
year = 0
tuition = 10000
while tuition < 20000:
tuition = tuition * 1.07
year+=1
print(year)
|
c88ddb412c2866c3dec02904916afebe2a70ef5c | stephen-weber/Project_Euler | /Python/Problem0128_Hexagonal_Tile_Differences.py | 5,646 | 3.703125 | 4 | """
Hexagonal tile differences
Problem 128
A hexagonal tile with number 1 is surrounded by a ring of six hexagonal tiles, starting at "12 o'clock" and numbering the tiles 2 to 7 in an anti-clockwise direction.
New rings are added in the same fashion, with the next rings being numbered 8 to 19, 20 to 37, 38 to 61, and so on. The diagram below shows the first three rings.
By finding the difference between tile n and each its six neighbours we shall define PD(n) to be the number of those differences which are prime.
For example, working clockwise around tile 8 the differences are 12, 29, 11, 6, 1, and 13. So PD(8) = 3.
In the same way, the differences around tile 17 are 1, 17, 16, 1, 11, and 10, hence PD(17) = 2.
It can be shown that the maximum value of PD(n) is 3.
If all of the tiles for which PD(n) = 3 are listed in ascending order to form a sequence, the 10th tile would be 271.
Find the 2000th tile in this sequence.
Answer:
14516824220
Completed on Sat, 20 Apr 2013, 07:32
"""
import time
ras=time.time()
xxx=100000000
import time
ras=time.time()
import random
pill=0
import itertools
def is_Prime(n):
#Miller-Rabin test for prime
if n==1:
return False
if n==2:
return True
if n%2==0:
return False
s = 0
d = n-1
while d%2==0:
d>>=1
s+=1
assert(2**s * d == n-1)
def trial_composite(a):
if pow(a, d, n) == 1:
return False
for i in range(s):
if pow(a, 2**i * d, n) == n-1:
return False
return True
for i in range(8):#number of trials
a = random.randrange(2, n)
if trial_composite(a):
return False
return True
r=0
num=0
pd=3 #for 1 and 2 and 8 see check below
def number_primes_in_hex():
global num
global r
global pill
r=2
t=set()
global pd
check=[]
p=8
n=3*r**2-3*r+2
while pd<2001:
check=[]
if p==n+6*r:
r+=1
n=3*r**2-3*r+2
num=6*r #number in ring
## if p>n and p<(n+r):
## check=[(-num+6),(-num+5),(+num),(+num+1)]
## elif p>(n+r) and p <(n+2*r):
## check=[(-num+5),(-num+4),(+num+1),(+num+2)]
## elif p>(n+2*r) and p < (n+3*r):
## check=[(-num+4),(-num+3),(+num+2),(+num+3)]
## elif p>(n+3*r) and p < (n+4*r):
## check=[(-num+3),(-num+2),(+num+3),(+num+4)]
## elif p>(n+4*r) and p < (n+5*r):
##
## check=[(-num+2),(-num+1),(+num+4),(+num+5)]
##
## elif p>(n+5*r) and p < (n+num-1):
##
## check=[(-num+1),(-num),(+num+5),(+num+6)]
if p==n:
check=[(+num),(+num+1),(+2*num+5),(+num-1),(-num+6)]
## elif p==(n+r):
## check=[(-num+5),(+num),(+num+1),(num+2)]
## elif p==(n+2*r):
## check=[(-num+4),(+num+1),(+num+2),(+num+3)]
## elif p==(n+3*r):
## check=[(-num+3),(+num+2),(+num+3),(+num+4)]
elif p==(n+num-1):
check=[(-num+1),(-2*num+7),(-num),(+num+5),(+num+6)]
## elif p==(n+5*r):
##
## check=[(-num+1),(+num+4),(+num+5),(+num+6)]
## elif p==(n+4*r):
## check=[(-num+2),(+num+3),(+num+4),(+num+5)]
##
t=0
for item in check:
y=abs(item)
if is_Prime(y):
t+=1
if t==3:
pd+=1
print pd,":","this is one ",p,time.time()-pill
pill=time.time()
#print p,":",r,n,offset,check
#number_primes_in_hex()
"""
given r n=(0,6*r-1)
corners n%r==0
"""
"""
if p==1:
check=[2,3,4,5,6,7]
elif p==2:
check=[9,8,19,7,1,3]
elif p==3:
check=[9,2,1,4,11,10]
elif p==4:
check=[3,1,5,13,12,11]
elif p==5:
check=[4,1,6,15,14,13]
elif p==6:
check=[1,7,17,16,15,5]
elif p==7:
check=[1,2,19,18,17,16,6]
else:
"""
def in_hex():
global num
global r
global pill
r=2
t=set()
global pd
check=[]
p=8
n=3*r**2-3*r+2
while pd<2000:
num=6*r #number in ring
p+=6*r-1
check=[(-num+1),(-2*num+7),(-num),(+num+5),(+num+6)]
t=0
for item in check:
y=abs(item)
if is_Prime(y):
t+=1
if t==3:
pd+=1
#print pd,":",p
#number in ring
p+=1
r+=1
num=6*r
check=[(+num),(+num+1),(+2*num+5),(+num-1),(-num+6)]
t=0
for item in check:
y=abs(item)
if is_Prime(y):
t+=1
if t==3:
pd+=1
#print pd,":", p
print pd,":", p," in ",time.time()-ras
in_hex()
|
832b19d9240c1eaba514a954983dbd3a4b09f90c | PacktPublishing/Mastering-OpenCV-4-with-Python | /Chapter10/01-chapter-content/k_means_color_quantization.py | 2,269 | 3.859375 | 4 | """
K-means clustering algorithm applied to color quantization
"""
# Import required packages:
import numpy as np
import cv2
from matplotlib import pyplot as plt
def show_img_with_matplotlib(color_img, title, pos):
"""Shows an image using matplotlib capabilities"""
# Convert BGR image to RGB
img_RGB = color_img[:, :, ::-1]
ax = plt.subplot(2, 3, pos)
plt.imshow(img_RGB)
plt.title(title)
plt.axis('off')
def color_quantization(image, k):
"""Performs color quantization using K-means clustering algorithm"""
# Transform image into 'data':
data = np.float32(image).reshape((-1, 3))
# print(data.shape)
# Define the algorithm termination criteria (the maximum number of iterations and/or the desired accuracy):
# In this case the maximum number of iterations is set to 20 and epsilon = 1.0
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 20, 1.0)
# Apply K-means clustering algorithm:
ret, label, center = cv2.kmeans(data, k, None, criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# At this point we can make the image with k colors
# Convert center to uint8:
center = np.uint8(center)
# Replace pixel values with their center value:
result = center[label.flatten()]
result = result.reshape(img.shape)
return result
# Create the dimensions of the figure and set title:
fig = plt.figure(figsize=(16, 8))
plt.suptitle("Color quantization using K-means clustering algorithm", fontsize=14, fontweight='bold')
fig.patch.set_facecolor('silver')
# Load BGR image:
img = cv2.imread('landscape_1.jpg')
# Apply color quantization:
color_3 = color_quantization(img, 3)
color_5 = color_quantization(img, 5)
color_10 = color_quantization(img, 10)
color_20 = color_quantization(img, 20)
color_40 = color_quantization(img, 40)
# Plot the images:
show_img_with_matplotlib(img, "original image", 1)
show_img_with_matplotlib(color_3, "color quantization (k = 3)", 2)
show_img_with_matplotlib(color_5, "color quantization (k = 5)", 3)
show_img_with_matplotlib(color_10, "color quantization (k = 10)", 4)
show_img_with_matplotlib(color_20, "color quantization (k = 20)", 5)
show_img_with_matplotlib(color_40, "color quantization (k = 40)", 6)
# Show the Figure:
plt.show()
|
1f39ae582667b7a12e07d832ea04b6643431fdb3 | skanwat/python | /learnpython/fibonacciseries.py | 218 | 3.625 | 4 | def fibo(x):
if x == 1:
return 1
elif x == 0:
return 0
else:
return (fibo(x-1) + fibo(x-2))
list=[]
for x in range(1,10):
z=fibo(x)
list.append(z)
print(z)
|
714e830023ebcc948a0ff84c9a4c3e668623bbf4 | ngxson/storeData | /controle3/ex2.py | 364 | 3.625 | 4 |
def ed(L,M=[]):
if not(L):
return M
a = L.pop(0)
if a not in M:
M.append(a)
return ed(L,M)
def ed_iterative(L):
M=[]
for a in L:
if a not in M:
M.append(a)
return M
L = [2,3,2,6,8,9,9,10,9,3,6,7,8,8,9]
print(ed(L))
L = [2,3,2,6,8,9,9,10,9,3,6,7,8,8,9]
print(ed_iterative(L))
|
3457645d7c25b94e4d323124d595133f60dad9b9 | cp4011/Algorithms | /LeetCode/4_寻找两个有序数组的中位数.py | 2,955 | 3.5 | 4 | """给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
你可以假设 nums1 和 nums2 不会同时为空。
示例 1:
nums1 = [1, 3]
nums2 = [2]
则中位数是 2.0
示例 2:
nums1 = [1, 2]
nums2 = [3, 4]
则中位数是 (2 + 3)/2 = 2.5
"""
''' left_part | right_part
A[0], A[1], ..., A[i-1] | A[i], A[i+1], ..., A[m-1]
B[0], B[1], ..., B[j-1] | B[j], B[j+1], ..., B[n-1]
需满足: 1. len(left_part)=len(right_part)
2. max(left_part)<=min(right_part)
将{A,B}中的所有元素划分为相同长度的两个部分,且其中一部分中的元素总是大于另一部分中的元素。median= max(left_part)+min(right_part) / 2
只需满足: 1. i+j=m−i+n−j(或:m - i + n - j + 1m−i+n−j+1) 如果 n≥m,只需要使 i=0∼m, j= (m+n+1) / 2 - i
2. B[j−1]≤A[i] 以及A[i−1]≤B[j]
j= (m+n+1) / 2 - i, +1目的是在m+n是奇数时 将中位数放在左边,有return maxLeft,中位数放到左边可以顺利返回,
而放到右边会发生什么?这行代码需要换为return minRight = min(A[i],B[j]),但是i和j并不是始终都会在合法范围内,
以{}{1}为例,一定不能出现A[i]。综上,加一是为了防止数组越界。
时间复杂度:O(log(min(m,n))),
首先,查找的区间是[0,m]。 而该区间的长度在每次循环之后都会减少为原来的一半。 所以,我们只需要执行log(m) 次循环。
由于m≤n,所以时间复杂度是 O(log(min(m,n)))。
'''
def median(A, B):
m, n = len(A), len(B)
if m > n: # 使得n≥m,这样j= (m+n+1) / 2 - i,确保j不是负数
A, B, m, n = B, A, n, m
if n == 0:
raise ValueError
imin, imax, half_len = 0, m, (m + n + 1) / 2
while imin <= imax:
i = (imin + imax) / 2
j = half_len - i
if i < m and B[j-1] > A[i]:
imin = i + 1 # A[i]小了,下标i右移增大(j相应就减少),以使B[j-1] <= A[i]
elif i > 0 and A[i-1] > B[j]:
imax = i - 1 # A[i-1]太大了,减小i左移,j后移 以使 A[i-1] <= B[j]
else: # i是完美的,即满足 B[j−1]≤A[i] 以及A[i−1]≤B[j]
if i == 0: max_of_left = B[j-1]
elif j == 0: max_of_left = A[i-1]
else: max_of_left = max(A[i-1], B[j-1])
if (m + n) % 2 == 1: # 当m+n为奇数:中位数为 max(A[i−1],B[j−1])
return max_of_left
if i == m: min_of_right = B[j] # m+n为偶数时:中位数是 max(A[i−1],B[j−1])+min(A[i],B[j]) / 2
elif j == n: min_of_right = A[i]
else: min_of_right = min(A[i], B[j])
return (max_of_left + min_of_right) / 2.0
|
c2f37e427da1f1dc7fcc775a034c27dcc86f2e06 | NotOrca22/learning_algorithms | /sorting.py | 8,708 | 3.96875 | 4 | from random import randint
from timeit import repeat
# # import statistics
# #
def run_sorting_algorithm(algorithm, array):
# Set up the context and prepare the call to the specified
# algorithm using the supplied array. Only import the
# algorithm function if it's not the built-in `sorted()`.
setup_code = f"from __main__ import {algorithm}" \
if algorithm != "sorted" else ""
stmt = f"{algorithm}({array})"
# Execute the code ten different times and return the time
# in seconds that each execution took
times = repeat(setup=setup_code, stmt=stmt, repeat=3, number=1)
# Finally, display the name of the algorithm and the
# minimum time it took to run
print(f"Algorithm: {algorithm}. Minimum execution time: {min(times)}")
# #
# # from random import randint
# # def quicksort(array):
# # if len(array) < 2:
# # return array
# # less, equal, more = [], [], []
# # pivot = statistics.median(array)
# # [less.append(x) if x < pivot else more.append(x) if x > pivot else equal.append(x) for x in array]
# # return quicksort(less) + equal + quicksort(more)
# #
# # def quicksort_2(array):
# # if len(array) < 2:
# # return array
# # less, equal, more = [], [], []
# # pivot = array[randint(0, len(array) - 1)]
# # [less.append(x) if x < pivot else more.append(x) if x > pivot else equal.append(x) for x in array]
# # return quicksort(less) + equal + quicksort(more)
# #
# # def binary_sort(array):
# # length = len(array)
# # b = []
# # for i in range(length):
# # if len(b) == 0:
# # b.append(array[i])
# # else:
# # start = 0
# # end = len(b) - 1
# # middle = (start + end)//2
# # while start <= end:
# # if end - start < 2:
# # if array[i] == b[middle]:
# # b.insert(array[i], middle + 1)
# # elif array[i] < b[middle]:
# # end = middle - 1
# # else:
# # start = middle + 1
# # else:
# # if array[i] >= b[0]:
# # b.append(array[i])
# # print(b, "greater")
# # else:
# # b.insert(0, array[i])
# # print(b, " less")
# # print("lol")
# #
# # b.insert(0, array[end])
# #
# # ARRAY_LENGTH = 5
# #
# # if __name__ == "__main__":
# # # Generate an array of `ARRAY_LENGTH` items consisting
# # # of random integer values between 0 and 999
# # array = [randint(1, 10) for i in range(ARRAY_LENGTH)]
# #
# # # Call the function using the name of the sorting algorithm
# # # and the array you just created
# # # run_sorting_algorithm(algorithm="quicksort_2", array=array)
# # run_sorting_algorithm(algorithm="binary_sort", array=array)
# #
# import time, sys
# force = list if sys.version_info[0] == 3 else (lambda X: X)
# class timer:
# def __init__(self, func):
# self.func = func
# self.alltime = 0
# def __call__(self, *args, **kargs):
# start = time.perf_counter()
# result = self.func(*args, **kargs)
# elapsed = time.perf_counter() - start
# self.alltime += elapsed
# print('%s: %.5f, %.5f' % (self.func.__name__, elapsed, self.alltime))
# return result
#
# @timer
# def listcomp(N):
# return [x * 2 for x in range(N)]
#
# @timer
# def mapcall(N):
# return map((lambda x: x * 2), range(N))
#
# @timer
# def forloop(N):
# M = []
# for i in range(N):
# M.append(i * 2)
#
# return M
# listcomp(500000)
# listcomp(1000000)
# listcomp(250000)
# print('allTime = %s' % listcomp.alltime)
# print('')
# mapcall(500000)
# mapcall(1000000)
# mapcall(250000)
# print('allTime = %s' % mapcall.alltime)
# forloop(50000000)
# forloop(1000000)
# forloop(250000)
# print('allTime = %s' % forloop.alltime)
# print('\n**map/comp = %s' % round(mapcall.alltime / listcomp.alltime, 3))
# print('\n**map/forloop = %s' % round(mapcall.alltime / forloop.alltime, 3))
# print('\n**comp/forloop = %s' % round(listcomp.alltime / forloop.alltime, 3))
#
# # def insertion_sort(array):
# # sorted_array = []
# # for element in array:
# # if len(sorted_array) > 0:
# # start = 0
# # end = len(sorted_array) + 1
# # mid = (len(sorted_array) + 1)//2 - 1
# # while start <= mid < end:
# # if element > sorted_array[mid]:
# # start = mid + 1
# # mid = (mid + len(sorted_array))//2
# # elif element < sorted_array[mid]:
# # end = mid - 1
# # mid = (start + mid) // 2 + 1
# # sorted_array.insert(mid, element)
# # else:
# # sorted_array.append(element)
# # return list(reversed(sorted_array))
# #
from random import randint
toSort = []
for i in range(5):
toSort.append(randint(1,1000))
# print(toSort)
# print(insertion_sort(toSort))
from random import randint
def binary_sort(arr, val, start, end):
# we need to distinugish whether we
# should insert before or after the
# left boundary. imagine [0] is the last
# step of the binary search and we need
# to decide where to insert -1
if start == end:
if arr[start] > val:
return start
else:
return start + 1
if start > end:
return start
mid = (start + end) // 2
if arr[mid] < val:
return binary_sort(arr, val, mid + 1, end)
elif arr[mid] > val:
return binary_sort(arr, val, start, mid - 1)
else:
return mid
def insertion_sort(arr):
for i in range(1, len(arr)):
val = arr[i]
j = binary_sort(arr, val, 0, i - 1)
arr = arr[:j] + [val] + arr[j:i] + arr[i + 1:]
return arr
# print("Sorted array:")
# print(insertion_sort(toSort))
def quicksort(arr):
if len(arr) > 1:
pivot = randint(0, len(arr)-1)
less = []
equal = []
more = []
for element in arr:
if element < arr[pivot]:
less.append(element)
elif element > arr[pivot]:
more.append(element)
else:
equal.append(element)
else:
return arr
return quicksort(less) + equal + quicksort(more)
# print(run_sorting_algorithm(algorithm="quicksort", array=toSort))
# print(run_sorting_algorithm(algorithm="binary_sort", array=toSort))
def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr
def merge_sort(arr):
mid = len(arr)//2
left = arr[:mid]
right = arr[mid:]
if len(left) == 1:
if len(right) == 1:
if left[0] < right[0]:
return left + right
else:
return right + left
else:
return merge(left, merge_sort(right))
elif len(right) == 1:
return merge(merge_sort(left), right)
else:
return merge(merge_sort(left), merge_sort(right))
def merge(arr1, arr2):
index1 = 0
index2 = 0
mergedList = []
if arr1 and arr2:
# while len(arr1) < len(arr2):
# arr1.append(0)
# while len(arr2) < len(arr1):
# arr2.append(0)
while index1 < len(arr1) and index2 < len(arr2):
if arr1[index1] > arr2[index2]:
mergedList.append(arr2[index2])
index2 += 1
elif arr2[index2] > arr1[index1]:
mergedList.append(arr1[index1])
index1 += 1
else:
mergedList.append(arr1[index1])
mergedList.append(arr2[index2])
index1 += 1
index2 += 1
if index1 == len(arr1):
if index2 + 1 > len(arr2):
return mergedList
else:
return mergedList + arr2[index2:]
else:
if index2 + 1 >= len(arr2):
return mergedList + arr1[index1:]
else:
pass
elif arr1:
return arr1
elif arr2:
return arr2
#
#
# print(bubbleSort(toSort))
toSort = []
for i in range(50):
for i in range(10):
toSort.append(randint(1,1000))
# print(toSort)
# print(merge_sort(toSort))
toSort = []
print(merge_sort([436, 961, 38, 533, 624, 589, 11, 77, 433, 689]))
# print(merge([1,2,4], [2,3,4])) |
3328b4aac1afac8fd81bd84f7ddd9363d62baf59 | fanzhihai/Data-Structure-Algorithms | /Sorting Algorithm/bubble_sort.py | 699 | 4.15625 | 4 | # -*- coding:utf-8
"""
# 冒泡排序
# 将数组当中的左右元素,依次比较,保证右边的元素始终大于左边的元素,保证最大的在右边,就像冒泡一样,大的气泡在下面
# @author:BigOceans
# https://github.com/fanzhihai
"""
def bubble_sort(lists):
count = len(lists)
for i in range(count):
for j in range(i+1,count):
if lists[i] > lists[j]:
lists[i], lists[j] = lists[j], lists[i]
return lists
if __name__ == '__main__':
lists = [2,5,1,3,6,9,7]
print u'原始数组:' + str(lists)
lists_sorted = bubble_sort(lists)
print u'排序数组:' + str(lists_sorted)
|
3a375f4463b0d0b9948dc72241c0868fa7907476 | fatima-rizvi/CtCI-Solutions-6th-Edition | /Ch1-Arrays-and-Strings/02_check_permutation.py | 617 | 3.890625 | 4 | # Given two strings, check if one is a permutation of the other
def check_permutation(str1, str2):
freq1 = {}
freq2 = {}
for char in str1:
if freq1.get(char):
freq1[char] += 1
else:
freq1[char] = 1
for char in str2:
if freq2.get(char):
freq2[char] += 1
else:
freq2[char] = 1
for char, count in freq1.items():
if freq2.get(char) != count:
return False
return True
print(check_permutation("asdfghjkl", "lkjhgfdsa")) # True
print(check_permutation("volleyball", "lbavloeyll")) # True
print(check_permutation("not", "correct")) # False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.