blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
45aa835d982d8814d211574aed193eb98dc7960f | yuhaoboris/LearnPythonTheHardWay | /ex_15_sample.txt | 613 | 4.0625 | 4 | # coding=utf8
# 习题1:第一个程序 A Good First Program
# 中文问题:
#
# 如果注释中存在中文,python 解释时会出现ASCII报错
# 解决这一问题,需要在文件第一行加上以下内容(双引号内的所有内容):
# "# -- coding: utf-8 --" 或
# "# -- coding: utf8 --" 或
# "# coding=utf-8" 或
# "# coding=utf8"
#
# 注意:
# 1. "utf-8" 或 "utf8" 一样可行
# 2. 当 "# coding=utf8" 时,符号 "=" 两边不能有空格,否则报错。
print "Hello World!"
print "Hello Again"
print "I like typing this."
print "This is fun."
print "Now is better than never." |
6307243682b72ebc76618a091e0cafe90d876e5a | Tushar515/hackerrank_python_problems | /if_else.py | 503 | 4.25 | 4 |
'''Task
Given an integer, , perform the following conditional actions:
If is odd, print Weird
If is even and in the inclusive range of to , print Not Weird
If is even and in the inclusive range of to , print Weird
If is even and greater than , print Not Weird
'''
#!/bin/python3
N = int(input())
if N%2!=0:
print("Weird")
elif N%2==0 and N in range(2,5):
print("Not Weird")
elif N%2==0 and N in range(6,21):
print("Weird")
elif N%2==0 and N>20:
print("Not Weird")
|
cd0d44a847da5e16f35c116e7a10869c5ef6ffdb | TIRSA30/UG9_A_71210700 | /3_A_71210700.py | 831 | 3.8125 | 4 | #Menambah catatan di program Doni
#defenisi data test case 1
Daftar1 = input("Masukan daftar belanja 1: ")
Daftar2 = input("Masukan daftar belanja 2: ")
Daftartambahan1 = input("Tambahan data ke daftar belanja 1: ")
Daftartambahan2 = input("Tambahan data ke daftar belanja 2: ")
#penyelesaian
print("Daftar belanja 1 adalah", Daftar1 +","+Daftartambahan1)
print("Daftar belanja 2 adalah", Daftar2 +","+Daftartambahan2)
#defenisi data test case 2
Daftar1 = input("Masukan daftar belanja 1: ")
Daftar2 = input("Masukan daftar belanja 2: ")
Daftartambahan1 = input("Tambahan data ke daftar belanja 1: ")
Daftartambahan2 = input("Tambahan data ke daftar belanja 2: ")
#penyelesaian
print("Daftar belanja 1 adalah", Daftar1 +","+Daftartambahan1)
print("Daftar belanja 2 adalah", Daftar2 +","+Daftartambahan2)
|
9de5cbf4f8d3f323b051f7b81cd0630397657a67 | shrikantnarvekar/Algorithims-and-Data-Structures | /binary tree.py | 1,664 | 3.796875 | 4 | class Treenode:
def __init__(self,d):
self.data=d
self.lchild=None
self.rchild=None
class Mytree:
def __init__(self,t):
self.root=t
def preorder(self,t):
if t is not None:
print(t.data)
self.preorder(t.lchild)
self.preorder(t.rchild)
def inorder(self,t):
if t is not None:
self.inorder(t.lchild)
print(t.data)
self.inorder(t.rchild)
def postorder(self,t):
if t is not None:
self.preorder(t.lchild)
self.preorder(t.rchild)
print(t.data)
def conpreorder(self,t):
if t is not None:
print(t.data)
self.preorder(t.rchild)
self.preorder(t.lchild)
def coninorder(self,t):
if t is not None:
self.inorder(t.rchild)
print(t.data)
self.inorder(t.lchild)
def conpostorder(self,t):
if t is not None:
self.preorder(t.rchild)
self.preorder(t.lchild)
print(t.data)
F=Treenode("F")
B=Treenode("B")
K=Treenode("K")
A=Treenode("A")
B=Treenode("B")
D=Treenode("D")
C=Treenode("C")
G=Treenode("G")
F.lchild=B
F.rchild=K
B.lchild=A
B.rchild=D
D.lchild=C
K.lchild=G
mt=Mytree(F)
print("preorder: ")
mt.preorder(F)
print("inorder: ")
mt.inorder(F)
print("postorder: ")
mt.postorder(F)
print("converse preorder: ")
mt.conpreorder(F)
print("converse inorder: ")
mt.coninorder(F)
print("converse postorder: ")
mt.postorder(F)
|
17584ae43615a1b023d7e4f538f137fd3c6c9fc0 | matheuszei/Python_DesafiosCursoemvideo | /0037_desafio.py | 696 | 4.125 | 4 | #Escreva um programa em Python que leia um número inteiro qualquer
# e peça para o usuário escolher qual será a base de conversão:
# 1 para binário, 2 para octal e 3 para hexadecimal.
n = int(input('Digite um número inteiro: '))
print('=' * 35)
print('Escolha qual será a base de conversão')
print('=' * 35)
print('1 - Binário \n2- Octal \n3- Hexadecimal')
print('-' * 35)
opcao = int(input('Digite a opção: '))
#Calculo / Saida de dados
if opcao == 1:
print('Binário: {}'.format(bin(n)[2:]))
elif opcao == 2:
print('Octal: {}'.format(oct(n)[2:]))
elif opcao == 3:
print('Hexadecimal: {}'.format(hex(n)[2:]))
else:
print('Opção inválida!!')
|
893973d39a27df317f99382fd37f42b617ac842f | dmigrishin/lesson1 | /dicts.py | 634 | 4.125 | 4 | cities = {"city": "Москва", "temperature": "20"}
print(cities["city"])
cities['temperature'] = int(cities['temperature'])-5
print(cities)
# if cities.get('country') == None:#Данный вариант Добавляет элемент в словарь
# cities['country'] = "Россия"
# print(cities['country'])
cities.get("country" , "Россия") # а этот не добавляет
#print(cities.get("country","Россия")) # выводит значение по умолчанию, но не добавляеьт его в словарь
cities["date"] = '27.05.2019'
print(cities)
print(len(cities)) |
3ef62aae3291b8c159ed761c9abc46dae6a8776e | sassyst/leetcode-python | /leetcode/LinkedList/ReverseNodeInKGroup.py | 1,196 | 3.609375 | 4 | from leetcode.LinkedList.ListNode import ListNode
class Solution(object):
"""
HEAD -->n1-->n2-->n3-->n4-->...-->nk-->nk+1
==>
HEAD -->nk-->nk-1-->nk-2-->...-->n1-->nk+1
"""
def reverseNextKNodes(self, head, k):
curt = head
n1 = curt.next
# if less k nodes, return null
for j in range(k):
curt = curt.next
if not curt:
return None
nk = curt
nkplus = curt.next
# reverse
prev = head
curt = head.next
while curt != nkplus:
temp = curt.next
curt.next = prev
prev = curt
curt = temp
# last: curt = nk+1,prev = nk,
# head--> h1
# nk->nk-1->nk-2->nk-3->....->head
# nk+1->nk+2->nk+3->...->...
head.next = nk
n1.next = nkplus
return n1
def reverseKGroup(self, head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
dummy = ListNode(0)
dummy.next = head
prev = dummy
while prev:
prev = self.reverseNextKNodes(prev, k)
return dummy.next
|
8892dec1b9f7deb2dc086c8129da0099f1b6be73 | AmberJing88/algorithm-datastructure | /backtracking/Hannouta.py | 306 | 4 | 4 | # datastructure and algorithmm in python
#chapter 4 4-14 solution
def move(x, y):
print("move from " + x + " to "+ y)
def Hanot(x, y, z, n):
if n==1:
move(x, z)
else:
Hanot(x, z, y, n-1)
move(x, z)
Hanot(y, x, z, n-1)
Hanot('a', 'b', 'c', 3)
|
db2525fd275ad68c5964efefd44cfd5258ef20b8 | inJAJA/Study | /keras/keras56_mnist_dnn.py | 2,414 | 3.5625 | 4 | import numpy as np
#1. 데이터
from keras.datasets import mnist
mnist.load_data()
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print(x_train.shape) # (60000, 28, 28)
print(x_test.shape) # (10000, )
print(y_train.shape) # (60000, )
print(y_test.shape) # (10000, )
# x_data전처리 : MinMaxScaler
x_train = x_train.astype('float32')/255
x_test = x_test.astype('float32')/255
# y_data 전처리 : one_hot_encoding (다중 분류)
from keras.utils.np_utils import to_categorical
y_trian = to_categorical(y_train)
y_test = to_categorical(y_test)
print(y_train.shape)
# reshape : Dense형 모델 사용을 위한 '2차원'
x_train = x_train.reshape(60000, 28*28 )
x_test = x_test.reshape(10000, 28*28)
print(x_train.shape) # (60000, 784)
print(x_test.shape) # (10000, 784)
#2. 모델 구성
from keras.models import Sequential
from keras.layers import Dense, Dropout
model = Sequential()
model.add(Dense(200, activation = 'relu',input_dim = 28*28))
model.add(Dense(100, activation = 'relu'))
model.add(Dropout(0.2)) # Dropout 사용
model.add(Dense(80, activation = 'relu'))
model.add(Dropout(0.2)) # Dropout 사용
model.add(Dense(60, activation = 'relu'))
model.add(Dropout(0.2)) # Dropout 사용
model.add(Dense(40, activation = 'relu'))
model.add(Dropout(0.2)) # Dropout 사용
model.add(Dense(20, activation = 'relu'))
model.add(Dropout(0.2)) # Dropout 사용
model.add(Dense(10, activation = 'softmax'))
model.summary()
# EarlyStopping
from keras.callbacks import EarlyStopping
es = EarlyStopping(monitor = 'val_loss', mode = 'auto', patience = 50, verbose = 1 )
#3. 훈련
model.compile(loss = 'categorical_crossentropy', optimizer = 'adam', metrics = ['acc'] )
model.fit(x_train, y_trian, epochs = 100, batch_size = 64,
validation_split =0.2,
shuffle = True, callbacks = [es])
#4. 평가, 예측
loss, acc = model.evaluate(x_test, y_test, batch_size= 64)
print('loss: ', loss)
print('acc: ', acc)
# acc: 0.9785000085830688 |
f729fee8e5ea40a479369b1d66a38ac8b8ab921f | he1016180540/Python-data-analysis | /Experiment-2/Untitled-6.py | 347 | 3.78125 | 4 | def CalculationOfInterest(principal, rate, year):
"""计算利息
Args:
principal (int): 本金
rate (float): 年利率
year (int): 存款年限
Returns:
float: 利息
"""
return principal*rate*year
print(CalculationOfInterest(10000, 0.055, 5))
print(CalculationOfInterest(10000, 0.035, 3))
|
0ac863f6711f40f1302b7f125f03bba71217b231 | Reza-Salim/Training | /28.py | 301 | 3.75 | 4 | def w(v,t):
if t <= 10:
return (33-(10* sqr(v)-v +10.5)*(33-t)/(23.1))
else:
print("Invalid Temperature!")
def sqr(x):
return pow(x,0.5)
v = float(input("Enter Velocity : "))
t = float(input("Enter Temperature : "))
print (w(v,t))
|
03a6cc76b2b51e5360390025ccc56d2505a018d5 | Grissie/EDA-I | /PRACTICA_10/Programa_01.py | 1,092 | 3.828125 | 4 | def menu(opciones):
while(True):
for opcion in (opciones):
print(opcion)
op = int(input("Ingrese una opcion: "))
if op in [1,2,3,4]:
break
return op
def agregar(x):
y=int(input("Cuantos numeros quiere guardar ?: "))
k=0
while k<y:
z=int(input("Numero a guardar: "))
x.append(z)
k=k+1
def listar(x):
y=len(x)
k=0
while k<y:
print("\t",x[k])
k=k+1
def suma(x):
y=len(x)
k=0
suma=0
while k<y:
suma=suma + x[k]
k=k+1
return suma
def main():
x=[]
while(True):
opciones = ["1->Agregar numero","2->Listar","3->Sumar","4->Salir"]
op = menu(opciones)
print("Tu opcion es: "+str(op))
if op == 1:
agregar(x)
elif op == 2:
print("La lista es: ",end="\n")
listar(x)
elif op == 3:
a=suma(x)
print("La suma es: ",a)
elif op == 4:
print("Gracias por entrar al sistema, vuelva pronto")
break
main ()
|
98901a03c877724bfd954c0ba2a5f5ec60df1410 | mohit-10/assignments | /python-assignment3.py | 1,486 | 3.96875 | 4 |
#1.1 Write a Python Program to implement your own myreduce() function which works exactly like Python's built-in function reduce()
def do_sum(x1, x2):
return x1 + x2
def my_reduce(operation,sequence):
first_element = sequence[0]
for i in sequence[1:]:
first_element=operation(first_element,i)
return first_element
input_list=[]
input_list = [int(item) for item in input("Enter the list items : ").split()]
print(type(input_list))
print(my_reduce(do_sum, input_list))
#1.2 Write a Python program to implement your own myfilter() function which works exactly like Python's built-in function filter()
def iseven(x):
if(x%2==0):
return True
else:
return False
def myfilter(anyfunc, sequence):
result = []
for item in sequence:
if iseven(item):
result.append(item)
return result
input_list=[]
input_list = [int(item) for item in input("Enter the list items : ").split()]
print(myfilter(iseven, input_list))
#2. Implement List comprehensions to produce the following lists. Write List comprehensions to produce the following Lists
#List comprehension 1
input_list = ['x','y','z']
output1 = [ item*num for item in input_list for num in range(1,5) ]
print((output1))
#List Comprehension 2
input_list = ['x','y','z']
output2 = [ item*num for num in range(1,5) for item in input_list ]
print(output2)
#List Comprehension 3
input_list = [2,3,4,5]
result = [ [item+num] for item in input_list for num in range(0,4)]
print("[2,3,4] =>" + str(result)) |
cd3daca33b80992f09cec59a3f687f1a5f5609aa | sandervw/Fall17Classes | /Com S 444/Homework/homework9/stDev.py | 542 | 3.75 | 4 | """
This function calculates standard deviation
Created by David E. Hufnagel on Nov 1, 2017
note: borrowed from code online
"""
#Calculates mean
def Mean(data):
n = len(data)
return sum(data)/float(n)
#Return the sum of square deviations of the data
def SS(data):
c = Mean(data)
ss = sum((x-c)**2 for x in data)
return ss
#Calculates the standard deviation of the data
def StDev(data):
n = len(data)
ss = SS(data)
pvar = ss/float(n)
return pvar**0.5
test = [10,2,38,23,38]
stdev = StDev(test)
print stdev |
4d8fd64e21911d7fa336207fa9a18dcce4f66e29 | Trogers32/Python_Stack | /flask/flask_fundamentals/Hello_Flask.py | 1,711 | 3.546875 | 4 | from flask import Flask, render_template # Import Flask to allow us to create our app
app = Flask(__name__, template_folder='templates') # Create a new instance of the Flask class called "app"
@app.route('/') # The "@" decorator associates this route with the function immediately following
def hello_world():
return render_template('index.html', phrase='hello', times=5) # Return the string 'Hello World!' as a response
@app.route('/dojo')
def dojo():
return "Dojo!"
@app.route('/say/<name>')
def say(name):
try:
int(name)
return "Sorry! No response. Try again."
except ValueError:
return "Hi " + name + "!"
@app.route('/repeat/<num>/<content>')
def repeater(num, content):
try:
num = int(num)
try:
int(content)
return "Sorry! No response. Try again."
except ValueError:
return (f"{content}\n" * num)
except TypeError:
return "Sorry! No response. Try again."
except ValueError:
return "Sorry! No response. Try again."
@app.route('/play')
def play1():
return render_template("index.html", times=3)
@app.route('/play/<x>')
def play2(x):
x=int(x)
return render_template("index.html", times=x, other_color="rgb(50, 143, 160)")
@app.route('/play/<x>/<color>')
def play3(x, color):
x=int(x)
return render_template("index.html", times=x, other_color=color)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def catch_all(path):
return render_template('index.html/')
if __name__=="__main__": # Ensure this file is being run directly and not from a different module
app.run(debug=True) # Run the app in debug mode. |
05e67fc58c2f8893ef89d0bf9559f8833ee9ba48 | xuychen/Leetcode | /LCOF/11-20/12/12.py | 1,092 | 3.796875 | 4 | class Solution(object):
def dfs(self, board, n_rows, n_cols, i, j, word, depth):
if not depth:
return True
if i < 0 or i >= n_rows or j < 0 or j >= n_cols or word[-depth] != board[i][j]:
return False
board[i][j] = ''
result = self.dfs(board, n_rows, n_cols, i-1, j, word, depth-1) \
or self.dfs(board, n_rows, n_cols, i+1, j, word, depth-1) \
or self.dfs(board, n_rows, n_cols, i, j-1, word, depth-1) \
or self.dfs(board, n_rows, n_cols, i, j+1, word, depth-1)
board[i][j] = word[-depth]
return result
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
if not board or not board[0]:
return False
n_rows, n_cols = len(board), len(board[0])
for i in range(n_rows):
for j in range(n_cols):
if self.dfs(board, n_rows, n_cols, i, j, word, len(word)):
return True
return False |
ec5ae64c4767e72aa31e3e7b86d0966b079bc9bd | ivanpolyakov99/PolyakovPython | /hm2_2.py | 289 | 3.5 | 4 | # 2_Amount_and_composition
try:
n = int(input("Input numb : "))
except ValueError:
print("Not numb, try again")
else:
s = 0
c = 1
while n > 0:
s = s + n % 10
c = c * (n % 10)
n = n // 10
print("Amount :", int(s), "\nComposition :", int(c))
|
4f73d33fc3207253b8ef8aa69ab320ebcdbf30a4 | smartguy-coder/HillelOnline_HW1 | /work_module.py | 2,400 | 3.8125 | 4 | """
work module for writing in file the sum of numbers (from 1 to 100),
that can be divided on given number from the file 'denom.txt'
"""
import os
def current_directory() -> None:
"""to be sure that current working directory is located where *.py file is located"""
os.chdir(os.path.dirname(os.path.abspath(__file__)))
# print(os.getcwd()) # for debug purposes
def get_denominator() -> int:
"""
Read from the file denom.txt (located in current directory) one number.
File must exist and contain just one number.
This function manages 3 exceptions:
- the file 'denom.txt' does not exist
- the file 'denom.txt' contains not a number
- the number is 0 (zero)
:return: int
"""
# just in case we change current working directory before opening the file denom.xtx
current_directory()
try:
with open('denom.txt', mode='r', encoding='UTF-8') as f:
denominator = int(f.read())
except FileNotFoundError:
print('\033[1;31mFile "denom.txt" does not exist in the current directory.\033[0m')
return None
except ValueError:
print('\033[1;31mFile "denom.txt" contains not a number.\033[0m')
return None
if denominator:
return denominator
else:
print('\033[1;31mFile "denom.txt" contains 0 (zero).\033[0m')
def get_list_of_numbers(denominator: int) -> list:
f"""
return the list with the integer numbers, that can divide on given number: {denominator},
numbers in range (0:100]
:param denominator:
:return: list
"""
list_of_numbers = [number for number in range(1, 101) if (number % denominator == 0)]
return list_of_numbers
def get_sum(list_of_numbers: list) -> int:
"""
count the total sum of all numbers in a given list
:param list_of_numbers:
:return: int
"""
total_sum = sum(list_of_numbers)
return total_sum
def write_result_in_file(number: int) -> None:
"""
function writes the given number in the file 'result.txt'
:param number:
:return: None
"""
with open("result.txt", mode='w', encoding='UTF-8') as file:
file.write(str(number))
return None
if __name__ == '__main__':
print('\033[43mYou are running the support module for main.py file.\033[0m')
|
b55fe2382c52806c7c3af0319fcc2ff1718bc9ab | JSAbrahams/mamba | /tests/resource/valid/definition/long_f_string_check.py | 191 | 3.5625 | 4 | name: str = "My name"
some_brackets: str = "\{\}"
some_more_brackets: str = "empty expressions are ignored: {}"
age: int = 30
a: str = f"My name is {name} and my age is {age - 10}."
print(a)
|
8464b19ab3950fc5f75c847153583368f9e57a4d | abhi6689-develop/Codes | /Basic_Concepts.py | 392 | 3.53125 | 4 | # word = "Asma"
# print(list(enumerate(word,100)))
# lyst = ['Eat', 'Drink', 'Sleep']
# for index,item in enumerate(lyst):
# print(index)
x = lambda a: a+10
print(x(5))
x = lambda a,b : a**b
print(x(2,3))
x = lambda a,b,c : a+b+c
print(x(5,6,7))
def myfunction(n):
return lambda a: a * n
doubler = myfunction(2)
tripler = myfunction(3)
print(doubler(33))
print(tripler(33))
|
4e26506e47f756f2b105fb58f2970ca7b82d5a7e | maayan20-meet/meet2018y1lab5 | /caught_speeding.py | 377 | 3.546875 | 4 | speed = 50
is_birthday = True
if (is_birthday = False and speed < 31) or (is_birthday = True and speed < 36):
print('no ticket')
if (is_birthday = False and speed > 31 and speed < 51) or (is_birthday = True and speed < 36 and speed < 56):
print('small ticket')
if (is_birthday = False and speed < 50) or (is_birthday = True and speed < 56):
print('big ticket!')
|
d9c5037c021ca3ec8d43e82298fe1548025d4b18 | aranyasteve/python- | /Other/hw.py | 563 | 3.78125 | 4 | # def nperson(name, age=0, address=None):
# print("name is {} age is {} address is {}".format(name, age, address))
# return name, age, address
#
# a = input("enter name : ")
# b = input("enter age : ")
# c = input("Enter address : ")
#
# name,age, address = nperson(a, address=c, age=b)
# print(age)
def genral_store():
print("200")
return 100
def backary(rs):
if rs <500:
return "Cake not avalable"
else:
return "Cake is ready"
arnya = 300
g = genral_store()
print(g)
if g:
arnya += g
print(backary(arnya))
|
fb80b00039c091e168f30e57fd4e30e7578faf09 | DillonHayes18/GraphTheoryProjectV2 | /Project.py | 1,036 | 4.21875 | 4 | import argparse
# Graph Theory Project
# Dillon Hayes - G00373320
# April 2021
# Program to take a regular expression and the name or path of the file
# as command line arguments and output the lines of the file matching the regular expression.
# User prompt for adding inputing Regular Expression & File Path
# Stores input as rexep which is type string
# Stores input as filepath which is type string
parser = argparse.ArgumentParser(description='Enter Regular Expression & File Path:')
parser.add_argument('regexp', metavar='expression', type=str,
help='a string for the search')
parser.add_argument('filepath', metavar='path', type=str,
help='a filepath for the search')
args = parser.parse_args()
# Opens the filepath and stores it as fileSearcher - closes file after
# for every line that has fileSearcher
# if the regexp is in that line, print the line
with open(args.filepath, 'r') as fileSearcher:
for line in fileSearcher:
if args.regexp in line:
print (line)
|
7b2f37b83036df7d2fee1e8258309b66cdaaff6b | meighanv/05-Python-Programming | /lab-set-lecture.py | 1,577 | 4.375 | 4 | #Set contains a collection of unique values
#and works like a mathematical set
#All the elements in a set must be unique, no two elements can have the same value
#Sets are unordered
#Elements stored in a set can be of different data types
mySet= set(['a','b','c'])
print(mySet)
mySet2 = set('abc')
print(mySet2)
mySet3 = set('aabbcc')
print(mySet3)
#All of the above appear the same when printed
#set can only take on arg
#mySet4 = set('one','two','three') is invalid
mySet4 = set('one,two,three')
print(mySet4)
newSet = set()
newSet.add(1)
newSet.add(2)
newSet.add(3)
print('newSet', newSet)
newSet.update([4,5,6])
newSet2 = ([7,8,9])
newSet.update(newSet2)
newSet.remove(1)
#using for loop to iterate
newSet3 = set('abc')
for val in newSet3:
print(val)
numbers_set([1, 2, 3])
if 1 in numbers_set:
print('The value {} is in the set'.format(val))
if 99 not in numbers_set:
print('The value {} is not in the set'.format(val))
#unions
set1= set([1,2,3,4])
set2= set([3,4,5,6])
set3= set1.union(set2)
print(set1)
print(set2)
print(set3)
set5= set1|set2
#Find intersection
set4= set1.intersection(set2)
print(set4)
set6= set1&set2
charSet = ('abc')
charSetUpper = ('ABC')
#difference
set7 = set1.difference(set2)
set8 = set2.difference(set1)
print(set1)
print(set2)
set9 = set1-set2
print(set9)
#Finding symmetric differences of sets
set10 = set1.symmetric_difference(set2)
print(set10)
set11 = set1 ^ set2
print(set11)
#Finding subset
set12 = set([1,2,3,4,5,6])
set13 = set([1,2,3])
print(set13.issubset(set12))
print(set12.issuperset(set13))
|
f174dddf83353e139c2b58d001bf3ea0e5d0c10f | rorschachwhy/mystuff | /learn-python-the-hard-way/ex1_6.py | 3,339 | 4.65625 | 5 |
#ϰ1һ
print "Hello World!"
print "Hello Again"
print "I like typing this."
print "This is fun."
print "Yay! Printing."
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'
#ϰ2עͺ;
#A comment, this is so you can read your program later.
#Anything after the # is ignored by python.
print "I could have code like this." # and the comment after is ignored
#You can also use a comment to "disable" or comment out a piece of code:
#print "This won't run."
print "This will run."
#ϰ3ֺѧ
print "I will now count my chichens:"
print "Hens", 25 + 30 / 6
print "Rooters", 100 - 25 * 3 / 4
print "Mow I will count the eggs:"
print 3 + 2 + 1 - 5 +4 % 2 - 1 / 4 + 6
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
print "Oh, that's why it's False."
print "How about some more."
print "Is it greater?", 5 > -2
print "Is it grester or equal?", 5 >= -2
print "Is it less or equal?", 5 <= -2
print "д100 - 25. * 3 / 4?", 100 - 25. * 3 / 4
#ϰ4variable
#
cars = 100
#ÿ
space_in_a_car = 4.0
#˾
drivers = 30
#˿
passengers = 90
#ûбʻ
cars_not_driven = cars - drivers
#ʻ
cars_driven = drivers
#
carpool_capacity = cars_driven * space_in_a_car
#ÿƽ˿
average_passengers_per_car = passengers / cars_driven
print "There are", cars, "cars available."
print "There are only", drivers, "drivers available."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "peole to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."
#ϰ5ıʹӡ
#ʹ˷ ASCII ַ˱ǵ˼һ # -- coding: utf-8 --
my_name = ''
my_age = 35.1 # not a lie
my_height = 74 # inches
my_weight = 180 #lbs
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print "Let's talk about %s." % my_name
print "He's %d inche tall." % my_height
print "He's %d pounds heavy." % my_weight
print "Actually that's not too heavy."
print "He's got %s eyes and %s hair." %(my_eyes, my_hair)
print "His teeth are usually %s depending on the coffee." % my_teeth
#this line is trichy, try to get it exactly right
#ע⣺ʹ %f %r %r Ƿdzõһĺǡʲôӡ
print "If I add %f, %d, and %d I get %r." % (
my_age, my_height, my_weight, my_age + my_height + my_weight)
#ϰ 6: ַ(string)ı
x = "There are %d types of people." % 10
binary = "binary"
do_not = "don't"
y = "Those who know %s and those who %s." % (binary, do_not)
print x
print y
#ַǶףǵţ
print "I said: '%r'." % x
print "I also said: '%s'." % y
#######
#ע÷
#######
hilarious = False
joke_evaluation = "Isn't that jock so funny?! %r"
print joke_evaluation % hilarious
#######
w = "This is the left said of ..."
e = "a string with a right side."
print w + e
|
4dee885190dd68ae95d609ded5adca24f7552d50 | UncleBob2/MyPythonCookBook | /datetime module timedelta timezones.py | 1,613 | 3.53125 | 4 | import datetime
import pytz
# naive datetime vs aware
assigned_d = datetime.date(2012, 12, 12)
today = datetime.date.today()
print('Assigned date = {}, Today Date = {},'.format(assigned_d, today))
print('Year = {}, Month = {}, day = {}'.format(
today.year, today.month, today.day))
# Monday 0 and Sunday 6 date.weekday()
# Monday 1 ... Saturday = 6 and Sunday 7 isoweekday()
print('today is = {}'.format(today.isoweekday()))
tdelta = datetime.timedelta(days=7)
print('Print the seven days from now', today + tdelta)
# date2 = date1 + timedelta
# timedelta = date1 + date2
bday = datetime.date(2020, 9, 24)
till_bday = bday - today
print('days until celebration', till_bday.days)
print('seconds until celebration = {:,}'.format(till_bday.total_seconds()))
dt = datetime.time(12, 30, 34, 100)
print(dt)
dt = datetime.datetime(2016, 5, 23, 12, 30, 34, 100)
print(dt)
dt = datetime.datetime(2016, 5, 23, 12, 30, 34, tzinfo=pytz.UTC)
print('Timezone aware with pytz = ', dt)
# this is best since less typing
dt_utcnow = datetime.datetime.now(tz=pytz.UTC)
print('Timezone now with pytz = ', dt_utcnow)
dt_mtn = dt_utcnow.astimezone(pytz.timezone('US/Mountain'))
print('Timezone Denver pytz = ', dt_mtn)
dt_mtn = datetime.datetime.now() # naive time
mtn_tzone = pytz.timezone('US/Mountain')
dt_mtn = mtn_tzone.localize(dt_mtn) # using localize, it is now time aware
print(dt_mtn)
#strftime - datetime to string
#strptime - string to datetime
# this is string, we need to convert to datetime to manipulate it
dt_str = 'July 26, 2015'
dt = datetime.datetime.strptime(dt_str, "%B %d, %Y")
print(dt)
|
3ed02b1de12304585cb89c527a4bc8f684499c1b | wrosko/EXDS | /Week 5/Rosko_Terwiesch_timestable.py | 1,218 | 4 | 4 | """
File: Rosko_Terwiesch_timestable.py
Authors: Wade Rosko and Mats Terwiesch
Description: User inputs some number and a starting point, program
prints a multiplication table
"""
user_number = raw_input("Please enter a number: ")
last_multiple = raw_input("Enter the maximum value of the times table: ")
print ""
# The following two while loops ensure that the user has entered
# an integer, then converts the input to a float
while True:
if user_number.isdigit() == False:
print "You must enter a positive integer!"
user_number = raw_input("Please enter a number: ")
else:
user_number = float(user_number)
break
while True:
if last_multiple.isdigit() == False:
print "You must enter a positive integer!"
last_multiple = raw_input("Enter the maximum value of the times table: ")
else:
last_multiple = float(last_multiple)
break
# While loop performs the multiplication operation, subtracts one
# until there are no more operations in the times table
while last_multiple > 0:
multiple = user_number * last_multiple
print user_number, " x ", last_multiple, " is ", multiple
last_multiple = last_multiple - 1
|
0bbd2964144d737477893da9358cd16606708497 | KhvostenkoIhor/khvostenko | /Lesson_28/dz_28_2.py | 2,996 | 4.1875 | 4 |
class Stack():
def __init__(self):
self.stack = ['a', 'rtyy']
self.lenght = 3
def try_method(method):
def wrapper(self, *string):
try:
method(self, *string)
except Exception as e:
print(f"You can't do that because {e}")
return wrapper
def stack_is_full(self):
if len(self.stack) < self.lenght:
return False
return True
def stack_is_empty(self):
if len(self.stack) == 0:
return True
return False
@try_method
def add(self, string):
if not self.stack_is_full():
self.stack.append(string)
else:
raise Exception('Stack is full!')
@try_method
def delete(self):
if not self.stack_is_empty():
a = self.stack.pop()
return a
else:
raise Exception('Stack is empty!')
def clear_stack(self):
if not self.stack_is_empty():
self.stack = []
return self.stack
@try_method
def show_last_string(self):
if not self.stack_is_empty():
print(f'The last string is "{self.stack[-1]}"')
return self.stack[-1]
else:
raise Exception('Stack is empty!')
def size(self):
return len(self.stack)
@property
def stack_size(self):
return self.lenght
@stack_size.setter
def set_size(self, value):
self.lenght = value
if __name__ == '__main__':
st_1 = Stack()
while True:
print('\nWhat to do?')
answ = input('''Enter
"q" to quit
1 to add string to stack
2 to delete the last string from stack
3 to show the last string
4 to check the stack size
5 to check if the stack is empty
6 to check if the stack is full
7 to change the stack size
8 to clear the stack
''')
if answ == 'q' or answ == '':
break
elif answ == '1':
string = input('Enter something: ')
st_1.add(string)
elif answ == '2':
st_1.delete()
elif answ == '3':
st_1.show_last_string()
elif answ == '4':
print(f'The stack size is {st_1.size()}')
elif answ == '5':
if st_1.stack_is_empty():
print('Stack is empty')
else:
print('Stack is not empty')
elif answ == '6':
if st_1.stack_is_full():
print('Stack is full')
else:
print('Stack is not full')
elif answ == '7':
while True:
a = input('Enter the new stack size: ')
try:
a = int(a)
break
except ValueError:
print('Incorrect value!')
st_1.set_size = a
elif answ == '8':
st_1.clear_stack()
|
a44137e9c6acb321f97ffc295eebc7a26e7ac804 | Sakartu/kmltoolkit | /convert_coords.py | 1,975 | 3.546875 | 4 | #!/usr/bin/env python
# -*- coding: utf8 -*-
"""
Usage:
convert_coords.py [COORD]...
Options:
COORD A set of lat/lon coordinates in any one of the most used formats. If left out, you will be asked for coords
"""
from __future__ import unicode_literals
import re
from docopt import docopt
from decimal import Decimal
__author__ = 'peter'
FLOATRE = r'\d+(?:[.,]\d+)?'
DMS_FORMAT = re.compile(r'''(\d+)[° ](\d+)[' ]({0})["]?([NS])[ ,](\d+)[° ](\d+)[' ]({0})["]?([EW])'''.format(FLOATRE), re.U | re.I)
DEG_FORMAT = re.compile(r'''([-]?{0})[ ,]([-]?{0})'''.format(FLOATRE), re.U | re.I)
def main():
args = docopt(__doc__)
if not args['COORD']:
while True:
i = raw_input('Coord: ')
parse_coord(i.decode('utf8'))
for c in args['COORD']:
parse_coord(c)
def parse_coord(c):
# DD MM SS format
m = DMS_FORMAT.search(c)
if m:
lat = Decimal(m.group(1)) + (Decimal(m.group(2)) / 60) + Decimal(m.group(3)) / 3600
lat = -lat if 's' in m.group(4).lower() else lat
lon = Decimal(m.group(5)) + (Decimal(m.group(6)) / 60) + Decimal(m.group(7)) / 3600
lon = -lon if 'w' in m.group(8) else lon
print '{0:.6f} {1:.6f}'.format(lat, lon)
# Deg format
m = DEG_FORMAT.match(c)
if m:
lat = Decimal(m.group(1))
lat_sign = 'N' if lat >= 0 else 'S'
lat_deg, lat_min, lat_sec = to_deg_min_sec(abs(lat))
lon = Decimal(m.group(2))
lon_sign = 'E' if lon >= 0 else 'W'
lon_deg, lon_min, lon_sec = to_deg_min_sec(abs(lon))
print '{0}°{1}\'{2:.2f}"{3} {4}°{5}\'{6:.2f}"{7}'.format(lat_deg, lat_min, lat_sec, lat_sign, lon_deg, lon_min, lon_sec, lon_sign)
def to_deg_min_sec(c):
deg = int(c)
_, dec = divmod(Decimal(c), Decimal(1))
min = dec * Decimal(60)
dec -= min * (Decimal(1) / Decimal(60))
sec = dec * Decimal(3600)
return int(deg), int(min), sec
if __name__ == '__main__':
main() |
429ff7130f7a111a201dde7580a38a183ce8b170 | maximalism000/guess_name | /guess_name.py | 1,909 | 3.75 | 4 | print('名前を入力してください')
true_name = list(input())
print('試行回数を入力してください')
N = int(input())
game_continue = True
LEN_NAME = '=====名前は%d文字です=====' % len(true_name)
user_change = '''
======================回答者に渡してください=========================
'''
print(user_change)
rule = '''名前当てゲームのルールを説明します。
最初に、出題者が名前と試行回数を決めます。
次に、回答者は、名前の文字数と試行回数を知ることできます。
回答者が名前を入力すると、それに対して更に多くの情報が得られます。
hit: 文字が名前に含まれており、尚且つ、位置が正しい
ball: 文字が名前に含まれているが、位置が正しくない
strike: 文字が名前に含まていない
ではゲームを始めます\n\n'''
print(rule)
print(LEN_NAME)
print('=====試行回数は%d回です=====' % N)
while game_continue:
for i in range(N):
guess_name = list(input())
hit = 0
ball = 0
strike = 0
if len(guess_name) == len(true_name):
for j in range(len(true_name)):
if guess_name[j] == true_name[j]:
hit += 1
elif guess_name[j] in true_name:
ball += 1
else:
strike += 1
else:
print(LEN_NAME)
print('hit: %d\nball: %d\nstrike: %d\n' % (hit, ball, strike))
if hit == len(true_name):
print('正解!')
game_continue = False
break
else:
print('=====試行回数は残り%d回です=====\n名前を予測してください' % (N - i - 1))
if (N - i - 1) == 0:
print('GAME OVER')
game_continue = False
break
|
20165158a1c02b20f9f48dcea7d879074cd7e49c | JosephLevinthal/Research-projects | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4161/codes/1800_2573.py | 548 | 3.59375 | 4 | from numpy import*
p = array(eval(input("peso: ")))
a = array(eval(input("altura: ")))
n = size(p)
t = zeros(n)
y = 0
for x in p:
t[y] = round(x/(a[y]**2) , 2)
y = y + 1
print(t)
print("O MAIOR IMC DA TURMA EH:", max(t))
if max(t) < 17:
print("MUITO ABAIXO DO PESO")
elif 17<max(t)<=18.49:
print("ABAIXO DO PESO")
elif 18.5<max(t)<=24.99:
print("PESO NORMAL")
elif 25<max(t)<=29.99:
print("ACIMA DO PESO")
elif 30<max(t)<=34.99:
print("OBESIDADE")
elif 35<max(t)<=39.99:
print("OBESIDADE SEVERA")
elif max(t)>40:
print("OBESIDADE MORBIDA") |
ff75e73bc877ebbbe8cff0833b93d51361ff1bc1 | erjan/coding_exercises | /count_all_valid_pickup_and_delivery_options.py | 658 | 3.71875 | 4 | '''
Given n orders, each order consist in pickup and delivery services.
Count all valid pickup/delivery possible sequences such that delivery(i) is always after of pickup(i).
Since the answer may be too large, return it modulo 10^9 + 7.
'''
def countOrders(self, n: int) -> int:
a = 1
for i in range(2, n+1):
a *= i*(2*i-1)
return a % (10**9 + 7)
----------------------------------------------------------------------
class Solution:
def countOrders(self, n: int) -> int:
n=2*n
ans=1
while n>=2:
ans = ans *((n*(n-1))//2)
n-=2
ans=ans%1000000007
return ans
|
e34ac9775f0d33c5740330b02997749da951be61 | hellcodeX/first_python | /list_comprehension.py | 988 | 4.0625 | 4 | if __name__ == '__main__':
a = range(5)
b = []
for num in a:
b.append(num * 2)
print(b)
# аналогичное с помощю генераторов списка
c = [num * 2 for num in a]
print(c)
range1 = [num * 3 for num in range(1, 6)]
print(range1)
a = [1, 10, 12, 4, 3, 20, 55]
a_filtered = []
for num in a:
if num < 10:
a_filtered.append(num)
print(a_filtered)
# аналогичное с помощю генераторов списка
b_filtered = [num for num in a if num < 10]
print(b_filtered)
print([num ** 2 for num in b_filtered if num <= 3])
words = ["hello", "hey", "goodbye", "guitar", "piano"]
print([word.capitalize() for word in words if len(word) < 6])
print([num * 2 for num in range(10, 1, -1) if num % 2 == 0]) # range третим аргументом принимает шаг
print([word + "." for word in words if len(word) > 5])
|
e0bb980636408dfbbe5798a07001fa37291814e9 | brennanharrison/Kattis | /lineup.py | 332 | 3.875 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[11]:
n= int(input())
x = 0
oL = []
while x < n:
u = input()
oL.append(u)
x+=1
oLSort = oL[:]
oLSort.sort()
oLReverse = oLSort[:]
oLReverse.reverse()
if oL == oLSort:
print('INCREASING')
elif oL == oLReverse:
print('DECREASING')
else:
print('NEITHER')
|
7751dd10e0dd20589f44264609871785dfb60dd9 | zlr20/running-robot-simulation | /running_robot_v2.0/controllers/double_barrier/double_barrier.py | 1,059 | 3.625 | 4 | from controller import Robot,Motor
robot = Robot()
#仿真步长
timestep = int(robot.getBasicTimeStep())
wheel1 = robot.getDevice("wheel1")
wheel2 = robot.getDevice("wheel2")
TouchSensor1 = robot.getDevice("t_sensor1")
TouchSensor1.enable(timestep)
TouchSensor2 = robot.getDevice("t_sensor2")
TouchSensor2.enable(timestep)
robot.setCustomData(str(0))
def step(num):
cnt = 0
Touch_Flag=0
while robot.step(timestep) != -1:
#print(w print(TouchSensor.getValue())heel.getVelocity()) #just for test
if TouchSensor1.getValue() or TouchSensor2.getValue():
if Touch_Flag==0:
print("barrier touched!")
Touch_Flag=1
robot.setCustomData(str(Touch_Flag))
cnt = cnt + 1
if cnt == num:
break
while True:
#角度和停顿时间
wheel1.setPosition(0)
wheel2.setPosition(0)
step(5000//timestep)
wheel1.setPosition(-1.57)
wheel2.setPosition(-1.57)
step(10000//timestep)
print('happy')
|
b9d2cd848160c59c54cad4fc0acafb450808bfee | kamilczerwinski22/Statistics | /statistics/classes_1/exG/exG_pt2.py | 2,807 | 4.0625 | 4 | # A script for showing number of wins trajectory for player A.
# Part 1: Player A's capital depending on number of the game
# Author: Kamil Czerwiński, Jagiellonian University, CS 2020/2021
import matplotlib.pyplot as plt
import random
def play_game(a_capital: int, b_capital: int, p: float) -> list:
"""
Function for performing single game.
:param a_capital: Capital of player A
:param b_capital: Capital of player B
:param p: Probability to win single round by player A
:return: List of (turn, capital) tuples containing player's A capital each turn.
"""
# initial variables
population: list = ['A', 'B']
weights: list = [p, 1 - p]
player_a_capital_turns: list = [(0, a_capital)]
turn: int = 0
# main game
while True:
if random.choices(population, weights)[0] == 'A':
a_capital += 1
b_capital -= 1
else:
a_capital -= 1
b_capital += 1
turn += 1
player_a_capital_turns.append((turn, a_capital))
if a_capital == 0:
break
if b_capital == 0:
break
return player_a_capital_turns
def generate_color() -> tuple:
"""Helper function for generating random color.
:return: Tuple (r, g, b) signifying color"""
r: float = random.random()
b: float = random.random()
g: float = random.random()
return r, g, b
def generate_game_grap(a_capital: int, b_capital: int) -> None:
"""
Function for performing multiple games and generating adequate graph.
:param a_capital: Capital of player A
:param b_capital: Capital of player B
:return: None
"""
# initial variables
probabilities: list = [0.25, 0.5, 0.75]
results_data: list = []
# main program logic
for probability in probabilities:
result = play_game(a_capital=a_capital, b_capital=b_capital, p=probability)
results_data.append(result)
print(results_data)
# draw graph
fig, ax = plt.subplots()
for current_plot_data, current_p in zip(results_data, probabilities):
color = generate_color()
x_values = [pair[0] for pair in current_plot_data]
y_values = [pair[1] for pair in current_plot_data]
ax.step(x_values, y_values, color=color, zorder=3, label=f'p={current_p}')
ax.grid(zorder=1)
ax.locator_params(axis='x', nbins=22)
plt.yticks(range(0, a_capital + b_capital + 1, round((a_capital + b_capital) / 20)))
plt.ylabel(f"Capital")
plt.xlabel(f"Current game number")
plt.title(f"Player A's capital for different probabilities\n"
f"with initial capital A={a_capital}, B={b_capital}", loc='left')
plt.legend()
# fig.savefig("example1_pt2.png")
plt.show()
if __name__ == '__main__':
generate_game_grap(20, 20)
|
de822c48507a3128d0920d89d1590bc64ab2405e | geraldthedev/IS211_Assignment8 | /despat.py | 2,371 | 3.75 | 4 | import random
import argparse
def roll_die():
"""Roll a 6 face die"""
return random.randint(1, 6)
class Die:
def __init__(self, faces=6):
self.faces = faces
def roll(self):
return random.randint(1, self.faces)
class Player:
def __init__(self, name):
self.name = name
self.total = 0
# turn total might note be necessary here
self.turn_total = 0
def get_total(self):
return self.total
def __str__(self):
return "Player {self.name} total = {self.total}"
def display(self):
print(self.__str__())
class Game:
def __init__(self, players, die):
self.players = players
self.die = die
die = roll_die()
def play(self):
r = True
h = False
active_player = 0
choice = input("Roll(r) or Hold(h)? ")
# loop until one player total turn >= 100
while not self.check_winner():
pass
turn_total = 0
while choice is not r or die is not 1:
print("rolling the dice")
if choice is "r":
die = Die.roll()
if die != 1:
turn_total= turn_total + die
player_total = Player.get_total() + turn_total
print(player_total)
# get an active player
# active player turn total = 0
# loop until hold or roll is 1
# ask for roll or hold
# if roll, roll the die
# if roll != 1: Update turn total
#
# if hold, update player's total = total + turn total
# if not (the player rolled a one)
def check_winner(self):
"""Check if one player has more than 100 points"""
# if a player has a total > 100, return True else return False
for player in self.players:
if player.total >= 100:
return True
return False
if __name__ == '__main__':
# parser = argparse.ArgumentParser()
# parser.add_argument("--numPlayers", help="URL to the datafile", type=int)
# args = parser.parse_args()
print("Welcome to the Pig Game")
common_die = Die()
players = [Player("One"), Player("Two")]
game = Game(players, common_die)
game.play()
|
0e654d8c170bdab02ee13d7228204243c61e06cf | whitefly/leetcode_python | /有限状态机/65_valid_number.py | 2,063 | 3.515625 | 4 | """
思入:
方法1: 高级版->比较多条件,利用有限状态机
方法2: 初级版->写个re正则
方法3: 无脑版->利用python的float()
状态机中实现中的一些坑
1.'-.1','3.e3'可以过
2.'.'过不了
"""
class Solution:
Digit = 0
Signal = 1
Blank = 2
Dot = 3
E = 4
Other = 5
End = 6
T = 98
F = 99
statusTable = [
[2, 1, 0, 9, F, F, F], # 开始态0
[2, F, F, 9, F, F, F], # 符号态1
[2, F, 8, 3, 5, F, T], # 数字态(整数部分,非e)
[4, F, 8, F, 5, F, T], # 小数点态(有整数部分 例子'1.', 分开小数点状态是为了防止'.'通过)
[4, F, 8, F, 5, F, T], # 数字态(小数部分,非e)
[7, 6, F, F, F, F, F], # e态
[7, F, F, F, F, F, F], # 符号态(e幂符号)
[7, F, 8, F, F, F, T], # 数字态(e幂数值)
[F, F, 8, F, F, F, T], # 空格态
[4, F, F, F, F, F, F] # 小数点态(无整数部分,例'.1')
]
def get_element(self, c):
if 48 <= ord(c) <= 57:
return self.Digit
if c == ' ':
return self.Blank
if c == "+" or c == '-':
return self.Signal
if c == '\0':
return self.End
if c == 'e':
return self.E
if c == '.':
return self.Dot
else:
return self.Other
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
string = s + '\0' # 手动加一个\0结束符,在静态语言中是不用加的
now_S = 0
for c in string:
e = self.get_element(c)
now_S = (self.statusTable[now_S])[e] # 输入行为后,新转移后的状态
if now_S == self.T or now_S == self.F:
return now_S == self.T
def isNumber2(self, s):
try:
float(s)
return True
except:
return False
if __name__ == '__main__':
a = "35.e3 1" # '-.1'
s1 = Solution()
print(s1.isNumber2(a))
|
8298b0514566fb67460fe4685f29c8f02fdd70e9 | tskiranmayee/Python | /4.Strings&Lists/listMethods.py | 1,227 | 4.21875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon May 10 18:08:35 2021
@author: tskir
"""
"""List as an Array"""
x1 = ['a', 'b', 'c']
x1.append('d')
print("x1 after append()=",x1) #Adds an element at the end of the list"""
x2=['w','x']
x1.clear() #Removes all the elements from the list
print("x1 after clear()=",x1)
x3=[]
x3=x2.copy() #Returns a copy of the list
print("x3 after copy()=",x3)
print("count of w in x3 =",x3.count('w')) #Returns the number of elements with the specified value
x4=('g','h') #declaring tuple
x3.extend(x4) #Add the elements of a list (or any iterable), to the end of the current list
print("x3 after extend() with a tuple x4 =",x3)
r=x3.index('x')
print("Index of x in x3:",r) #Returns the index of the first element with the specified value
q='e'
x3.insert(1,q) #Adds an element at the specified position
print("x3 after insert() at position 1=",x3)
x3.pop(2)
print("x3 after pop() at index 2:",x3) #Removes the element at the specified position
x3.remove('w')
print("x3 after remove() for value w:",x3) #Removes the first item with the specified value
x3.reverse()
print("Reverse of list x3:",x3) #Reverses the order of the list
x3.sort()
print("Sort the list x3:",x3) #Sorts the list
|
4fe25cbf26295bc0d647ab8d288c50d262003072 | rohitdandona/NRooks-NQueens-Problem | /nrooks_queens.py | 5,864 | 4.0625 | 4 | # nrooks_queens.py : Solve the N-Rooks/N-Queens problem!
#
# The N-rooks/N-Queens problem is: Given an empty NxN chessboard, place N rooks/Queens on the
# board so that no rooks/queen can take any other.
# This is N, the size of the board.
import time
import sys
N=375
# Count # of pieces in given row
def count_on_row(board, row):
return sum( board[row] )
# Count # of pieces in given column
def count_on_col(board, col):
return sum( [ row[col] for row in board ] )
# Count total # of pieces on board
def count_pieces(board):
return sum([ sum(row) for row in board ] )
# Count total # of pieces present on each possible diagonal on the board
def count_on_diag(board):
# Sum of each right diagonal
check = N - 1
diagonal_sums = []
for r in range(0, N):
diag_sum = 0
for c in range(0, N):
if (c <= check):
diag_sum += board[c][r]
r += 1
check -= 1
if diag_sum <= 1:
diagonal_sums.append(True)
else:
diagonal_sums.append(False)
check = N - 1
for r in range(1, N):
diag_sum = 0
c = 0
check -= 1
temp = r
while c <= check:
diag_sum += board[temp][c]
c += 1
temp += 1
if diag_sum <= 1:
diagonal_sums.append(True)
else:
diagonal_sums.append(False)
# Sum of each left diagonal
check = N - 1
for r in reversed(range(N)):
diag_sum = 0
for c in range(0, N):
if (c <= check):
diag_sum += board[c][r]
r -= 1
check -= 1
if diag_sum <= 1:
diagonal_sums.append(True)
else:
diagonal_sums.append(False)
check = 0
for r in range(1, N):
diag_sum = 0
c = N - 1
check += 1
temp = r
while c >= check:
diag_sum += board[temp][c]
c -= 1
temp += 1
if diag_sum <= 1:
diagonal_sums.append(True)
else:
diagonal_sums.append(False)
return diagonal_sums
# Return a string with the board rendered in a human-friendly format
def printable_board(board):
return "\n".join([ " ".join([ "Q" if col else "_" for col in row ]) for row in board])
# Add a piece to the board at the given position, and return a new board (doesn't change original)
def add_piece(board, row, col):
return board[0:row] + [board[row][0:col] + [1, ] + board[row][col + 1:]] + board[row + 1:]
# Get list of successors of given board state
def successors(board):
return [add_piece(board, r, c) for r in range(0, N) for c in range(0, N)]
# Get list of successors of given board state (N+1 and "moves" problem fixed)
def successors2(board):
succ = []
for r in range(0, N):
for c in range(0, N):
new_b = add_piece(board, r, c)
if new_b != board:
total_sum = 0
for row in new_b:
total_sum += sum(row)
if total_sum <= N:
succ.append(new_b)
return succ
def successors3(board):
succ = []
index = 0
index_list_row = []
index_list_col = []
for row in board:
if any(row):
index_list_row.append(index)
index_list_col.append(row.index(1))
index += 1
if index_list_col:
next_col = max(index_list_col) + 1
else:
next_col = 0
for r in range(0, N):
if r not in index_list_row and next_col < N:
new_b = add_piece(board, r ,next_col)
succ.append(new_b)
return succ
# check if board is a goal state (rook)
def is_goal_rook(board):
return count_pieces(board) == N and \
all([count_on_row(board, r) <= 1 for r in range(0, N)]) and \
all([count_on_col(board, c) <= 1 for c in range(0, N)])
# check if board is a goal state (queen)
def is_goal_queen(board):
return count_pieces(board) == N and \
all([count_on_row(board, r) <= 1 for r in range(0, N)]) and \
all([count_on_col(board, c) <= 1 for c in range(0, N)]) and \
all(count_on_diag(board))
# Solve n-rooks!
def solve(initial_board):
fringe = [initial_board]
while len(fringe) > 0:
for s in successors3( fringe.pop() ):
if is_goal_rook(s):
return(s)
fringe.append(s)
return False
# Solve n-queens!
def nqueens_solve(initial_board):
fringe = [initial_board]
while len(fringe) > 0:
for s in successors3( fringe.pop() ):
if is_goal_queen(s):
return(s)
fringe.append(s)
return False
# The board is stored as a list-of-lists. Each inner list is a row of the board.
# A zero in a given square indicates no piece, and a 1 indicates a piece.
ans = raw_input("Would you also like to find the N Queens solution for N = "+str(N)+" (Y or N): ")
# Begin execution of N rooks problem...
initial_board = [[0]*N]*N
print("N Rooks Problem !")
print ("Starting from initial board:\n" + printable_board(initial_board) + "\n\nLooking for a solution with " + str(N) +" rooks...\n")
start_time = time.time()
solution = solve(initial_board)
print (printable_board(solution) if solution else "Sorry, no solution found. :(")
print("\n")
if ans == "N":
print("--- %s seconds ---\n\n" % (time.time() - start_time))
sys.exit(0)
# Begin execution of N queens problem...
initial_board = [[0]*N]*N
print("N Queens Problem !")
print ("Starting from initial board:\n" + printable_board(initial_board) + "\n\nLooking for a solution with " + str(N) +" queens...\n")
solution = nqueens_solve(initial_board)
print (printable_board(solution) if solution else "Sorry, no solution found. :(")
print("--- %s seconds ---" % (time.time() - start_time))
|
66f824c3dc59aeec03ef118278b7183c5af458ae | koundinyagoparaju/leetcode | /src/python/addTwoNumber2.py | 1,128 | 3.671875 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
import math
class Solution(object):
def addTwoNumbers(self, l1, l2):
finalList = ListNode(0)
head = finalList
carry = 0
while(l1 is not None or l2 is not None or carry > 0):
sum = 0
if l1 is not None:
sum = l1.val
l1 = l1.next
if l2 is not None:
sum = sum + l2.val
l2 = l2.next
print('sum', sum, 'cary', carry)
finalList.val = (sum + carry) if((sum + carry) < 10) else (sum + carry)% 10
print('finalList.value', finalList.val)
carry = int(math.floor((sum + carry)/10))
if(l1 is not None or l2 is not None or carry > 0):
finalList.next = ListNode(0)
finalList = finalList.next
print('finalList',head)
return head
|
5cee14c6682a74102420c1b493dc1b6f8760cbe7 | hcrocks007/Algorithms-Explanation | /Basic Math/mean.py | 482 | 4.1875 | 4 | def mean_calculator():
# First we take the list of numbers
list_of_numbers = input('Enter numbers').split(' ')
# Calculating sum
sum_of_numbers = 0
for i in range(0,len(list_of_numbers)):
sum_of_numbers = sum_of_numbers + int(list_of_numbers[i])
# Counting the numbers in the list
count = len(list_of_numbers)
# Calculating mean
mean = sum_of_numbers / count
# Returning mean
return mean
|
bf92913149ee2727c99e3d18ea47964b8dece9f5 | miblazej/pie | /uniform.py | 675 | 3.65625 | 4 | import numpy as np
def coin():
a = np.random.randint(2)
return a
def random_generator(a, b): # gauusian distribution
przedzial = b - a
przedzial_t = przedzial
bits = 0
# calculation of numbers of bit required to represent przedzial
while przedzial:
przedzial >>= 1
bits += 1
while 1:
number = 0
temp = bits
while temp:
c = coin()
number <<= 1
number ^= c
temp -= 1
if number <= przedzial_t:
break
return number + a
d = []
for i in range(100):
d.append(random_generator(0, 100))
print('a')
|
1199bbd1a14a040380347a5ad61fabfd4d6121ca | jvrs95/Python | /Exercício1opcional.py | 283 | 3.875 | 4 | a = input ("Digite o nome do cliente:")
b = input ("Digite o dia de vencimento:")
c = input ("Digite o mês de vencimento:")
d = input ("Digite o valor da fatura:")
print("Olá,", a)
print("A sua fatura com vencimento em", b, "de", c, "no valor de R$", d, "está fechada.") |
879177675de35ee006412b4e3fd8e522ed281047 | Genyu-Song/LeetCode | /Algorithm/Searching/Backtracking/N-Queens.py | 5,569 | 3.875 | 4 | # -*- coding: UTF-8 -*-
'''
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.
'''
class Solution:
def solveNQueens(self, n):
board = [['.'] * n for _ in range(n)]
count = 0
output = []
def check_one(row, col):
if 0 <= row < n and 0 <= col < n:
if board[row][col] == '.':
for i in range(-n+1, n):
if 0 <= row + i < n and 0 <= col + i < n:
if board[row + i][col + i] == 'Q':
return False
for i in range(-n+1, n):
if 0 <= row + i < n and 0 <= col - i < n:
if board[row + i][col - i] == 'Q':
return False
return True
else:
return False
def check_two(row, col):
if 0 <= row < n and 0 <= col < n:
if board[row][col] == '.':
for i in range(-n+1, n):
if 0 <= row + i < n:
if board[row + i][col] == 'Q':
return False
return True
else:
return False
def could_place(row, col):
return check_one(row, col) and check_two(row, col)
def backtrack(row=0):
for col in range(n):
if could_place(row, col):
board[row][col] = 'Q'
if row + 1 == n:
output.append(board[:])
board[row] = ['.'] * n
else:
backtrack(row + 1)
board[row - 1] = ['.'] * n
backtrack()
for i in range(len(output)):
for j in range(len(output[0])):
output[i][j] = ''.join(output[i][j])
return output
class Solution2:
def solveNQueens(self, n):
# used / visited 等可使用HashTable(set()) / 组[False for i xxx] /
output = []
dales = set()
hills = set()
cols = set()
x = [i for i in range(n)]
def __convert2board(stack, n):
return ["." * stack[i] + "Q" + "." * (n - stack[i] - 1) for i in range(n)]
def backtrack(row=0, stack=[]):
if row == n:
board = __convert2board(stack, n)
output.append(board)
return
for i in range(n):
if i not in cols and i + row not in dales and i - row not in hills:
cols.add(i)
dales.add(i + row)
hills.add(i - row)
stack.append(i)
backtrack(row + 1, stack)
cols.remove(i)
dales.remove(i + row)
hills.remove(i - row)
stack.pop()
backtrack()
return output
class Solution3:
def solveNQueens(self, n):
output = []
cols = [False for _ in range(n)]
dales = [False for _ in range(2 * n - 1)]
hills = [False for _ in range(2 * n - 1)]
x = [i for i in range(n)]
def __convert2board(stack):
return ['.' * stack[i] + 'Q' + '.' * (n - stack[i] - 1) for i in range(n)]
def backtrack(row=0, stack=[]):
if row == n:
board = __convert2board(stack)
output.append(board)
return
for i in range(n):
if not cols[i] and not dales[i + row] and not hills[row - i]:
cols[i] = True
dales[i + row] = True
hills[row - i] = True
stack.append(i)
backtrack(row + 1, stack)
cols[i] = False
dales[i + row] = False
hills[row - i] = False
stack.pop()
backtrack()
return output
class Solution4:
def solveNQueens(self, n):
res = []
cols = set()
hills = set()
dales = set()
def could_place(i, j):
return i - j not in hills and i + j not in dales and j not in cols
def place_queen(i, j, path):
cols.add(j)
hills.add(i - j)
dales.add(i + j)
cur = ''
for x in range(n):
if x != j:
cur += '.'
else:
cur += 'Q'
path.append(cur[:])
def remove_queen(i, j, path):
cols.remove(j)
hills.remove(i - j)
dales.remove(i + j)
path.pop(-1)
def backtrack(i=0, path=[]):
if i == n:
res.append(path[:])
return
else:
for j in range(n):
if could_place(i, j):
place_queen(i, j, path)
backtrack(i + 1, path)
remove_queen(i, j, path)
backtrack()
return res
if __name__ == '__main__':
board = Solution4().solveNQueens(n=4)
for i in range(len(board)):
print(board[i]) |
d3ee4cb98d68b6704424eddd527e87f34afa3fa3 | Thorqueor/L3_project_IA | /IA_FINAL_DJ_OL/ProjetIA/IA/ProjetFinal.py | 24,874 | 3.59375 | 4 | '''
Created on 03 mar. 2017
@author: Denou Julien
python version 2.7.13
'''
#!/usr/bin/python
# -*- coding: latin-1 -*-
import os, sys
import random
from random import randint
import copy
import time
from Tkinter import *
class Solution:
""" La classe Solution est defini par :
- L'etat courant du Taquin
- Les differentes heuristiques et leurs valeurs de cout
- L'affichage du Taquin courant
- On defini la classe Solution de la facon suivante : """
def __init__(self, taquin):
self.restaquin = taquin
def SolutionH(self):
""" On defini les differentes heuristiques utilisees de la facon suivante :
Ces heuristiques utilisent la Distance de Manhattan totale
c'est la distance de chaque piece entre sa place actuelle et sa position finale en nombre de places.
Nous utiliserons 6 heuristiques differentes avec des couts differents. """
tq = self.restaquin
#print("Affichage du taquin dans Solution")
#tq.afficherEtat()
""" On teste les 6 heuristiques dans une boucle while """
distance = 1
numeroHeuristique = []
complexiteTemps = []
nbmouv = []
nbEtat = []
complexite = list()
while distance < 7:
"""
Pour une distance inferieure a 7 car nous avons 6 heuristiques
On creer l'arbre binaire de recherche (abr) qui prendra en parametre le Taquin courant et
un autre parametre pour le calcul de l'heuristique
"""
abr = Arbre(tq, distance)
abr.noeudCourant.taquin
""" Creation du timer pour definir la complexite en Temps """
start_time = time.time()
""" On boucle la recherche tant qu'on a pas atteint un Etat du But """
while abr.noeudCourant.heuristique != 0:
"""On selectionne la meilleure Heuristique dans la Frontiere"""
indice = abr.choisirH()
meilleur = abr.frontiere[indice]
abr.noeudCourant = copy.deepcopy(meilleur)
abr.creerFils(abr.noeudCourant.directPrec, distance)
"""On retire le Noeud courant de la Frontiere"""
del abr.frontiere[indice]
"""On insert le Noeud courant dans l'ensemble des Explores"""
tmp = copy.deepcopy(meilleur)
insertion = True
for i in abr.explore:
if abr.comparerTaquin(i.taquin.taq, tmp.taquin.taq):
insertion = False
break
if insertion:
abr.explore.append(tmp)
indice = copy.deepcopy(abr.noeudCourant.g)
mouv = []
"""
Une fois trouvee la solution, on remonte l'arbre de recherche,
tout en inserant dans la liste des mouvements, les directions empruntees
"""
while indice != 0:
mouv.append(copy.deepcopy(abr.noeudCourant.directPrec))
tmp = copy.deepcopy(abr.noeudCourant.noeudPapa)
abr.noeudCourant = copy.deepcopy(tmp)
indice -= 1
numeroHeuristique.append(distance)
nbEtat.append(len(abr.explore))
nbmouv.append(len(mouv))
complexiteTemps.append(time.time()-start_time)
complexite.append(time.time()-start_time)
print 'Pour Heuristique = {} Nb Etats = {} Solution en {} mouvements et Complexite en Temps : {} secondes'.format(repr(numeroHeuristique[distance-1]), repr(nbEtat[distance-1]), repr(nbmouv[distance-1]), repr(complexiteTemps[distance-1]))
""" On reprends l'etat initial """
taquinDebut = copy.deepcopy(tqInit)
indice=0
mouv.reverse()
""" Pour cela on applique les differentes directions enregistrees pour arriver a la Solution en sens inverse """
while indice != len(mouv):
if mouv[indice] == 0:
taquinDebut.depN()
elif mouv[indice] == 1:
taquinDebut.depE()
elif mouv[indice] == 2:
taquinDebut.depS()
elif mouv[indice] == 3:
taquinDebut.depO()
time.sleep(3)
indice += 1
distance+=1
""" On reprend l'Etat Initial pour essayer une autre Heuristique """
tq = copy.deepcopy(tqInit)
a = min(complexiteTemps)
print 'La complexite en Temps minimum est : {} pour heuristique {}'.format(a ,complexiteTemps.index(a)+1)
def afficher(self, taquin):
i=0
for y in range(0,3,1):
for x in range(0,3,1):
if self.taquin.taq[i] != 0:
self.can.create_rectangle ((5+100*x),(5+100*y),(100+100*x),(100+100*y),fill='white')
self.can.create_text((50+100*x),(50+100*y),text=self.taquin.taq[i])
else:
self.can.create_rectangle ((5+100*x),(5+100*y),(100+100*x),(100+100*y),fill='black')
i=i+1
class Interface(Frame):
"""
Interface principale on affiche le taquin
et que l'on ajoute les boutons Quitter et Solution
Il faudrait ajouter le tableau recapitulatif
"""
def __init__(self, fenetre, taquinInit, **kwargs):
Frame.__init__(self, fenetre, width=350, height=350, **kwargs)
self.pack(fill=BOTH)
self.can = Canvas(fenetre, width=300, height=300,bg='black')
self.can.pack(side="top" , padx=20, pady=70)
self.taquin = taquinInit
""" Affichage du taquin """
i=0
for y in range(0,3,1):
for x in range(0,3,1):
if self.taquin.taq[i] != 0:
self.can.create_rectangle ((5+100*x),(5+100*y),(100+100*x),(100+100*y),fill='white')
self.can.create_text((50+100*x),(50+100*y),text=self.taquin.taq[i])
i=i+1
""" Affichage des boutons """
self.bouton_quitter = Button(self, text="Quitter", command=self.quit)
self.bouton_quitter.pack(side="bottom")
self.bouton_cliquer = Button(self, text="Solution", fg="blue", command=self.cliquer)
self.bouton_cliquer.pack(side="top")
def cliquer(self):
"""S'il y a eu un clic sur Solution,
on creer l'objet Solution en lui donnant le Taquin courant en parametre
et enfin on lance la fonction de resolution"""
rsd = Solution(self.taquin)
rsd.SolutionH()
fenetre2 = Tk()
champ_label = Label(fenetre2, text="Resultats des Heuristiques ")
champ_label.pack()
"""
Ici a ajouter le tableau avec les solution et le comparatif des heuristiques A FAIRE
print("Solutions des heuristiques : ")
print(self.complexiteTemps)
print(self.numeroHeuristique)
min.complexiteTemps
"""
def afficher(self, taquin):
""" Permet d'afficher le taquin actuel """
i=0
for y in range(0,3,1):
for x in range(0,3,1):
if self.taquin.taq[i] != 0:
self.can.create_rectangle ((5+100*x),(5+100*y),(100+100*x),(100+100*y),fill='white')
self.can.create_text((50+100*x),(50+100*y),text=self.taquin.taq[i])
else:
self.can.create_rectangle ((5+100*x),(5+100*y),(100+100*x),(100+100*y),fill='black')
i=i+1
""" Les fonctions suivantes permetent de deplacer la case
vide selon la touche directionnelle choisie. Ces boutons ont ete extrait d'Internet les sources sont en fichier Readme """
def monter(self, event):
print("HAUT")
self.taquin.depN()
self.afficher(self.taquin)
self.taquin.afficherEtat()
def descendre(self, event):
print("BAS")
self.taquin.depS()
self.afficher(self.taquin)
self.taquin.afficherEtat()
def gauche(self, event):
print("GAUCHE")
self.taquin.depO()
self.afficher(self.taquin)
self.taquin.afficherEtat()
def droite(self, event):
print("DROITE")
self.taquin.depE()
self.afficher(self.taquin)
self.taquin.afficherEtat()
class Taquin :
"""
La classe Taquin est definie par :
- Les valeurs 0 a 8 servant de cases du Taquin
- La position des valeurs en parametres
- Les methodes permettant de retrouver la position d'une case
- Les methodes permettant de connaitre la distance entre une valeur et sa place ideale
- Les methodes permettant de permuter les cases
Cette classe permet d'enregistrer un Etat du Taquin
"""
def __init__(self):
self.xvide = 0
self.yvide = 0
self.precedent = 0
self.taq = [0,1,2,3,4,5,6,7,8]
def xPosition(self, valeur):
""" Cette methode renvoie la position x de la valeur """
n = self.taq.index(valeur)/3 - self.taq.index(valeur)//3
m = 0
if n == 0 :
m = 0
elif n < 0.5 :
m = 1
else:
m = 2
return m
def yPosition(self, valeur):
""" Cette methode renvoie la position x de la valeur """
return self.taq.index(valeur)//3
def distanceSolution(self, valeur):
""" Cette methode retourne la distance de Manhattan entre la valeur en parametre et
la position ou elle devrait etre dans l'Etat du but"""
xA = self.xPosition(valeur)
xB = self.xPosition(self.taq[valeur])
yA = self.yPosition(valeur)
yB = valeur//3
return abs(xA - xB) + abs(yA - yB)
def heuristique(self, j):
""" methode qui renvoie l'heuristique du taquin"""
poids = [
[36,12,12,4,1,1,4,1,0],
[8,7,6,5,4,3,2,1,0],
[8,7,6,5,4,3,2,1,0],
[8,7,6,5,3,2,4,1,0],
[8,7,6,5,3,2,4,1,0],
[1,1,1,1,1,1,1,1,0],
]
if j==2 or j==4 or j==6:
p=1
else:
p=4
pi=j-1
i=0
res=0
while i<8:
res += poids[pi][i]*self.distanceSolution(i)/p
i+=1
return res
def valeurPosition(self, X, Y):
""" Retourne la valeur aux position X et Y """
return self.taq[(X * 3) + Y]
def deplacement(self, mouv):
"""Cette methode effectue un deplacement selon un mouvement donne"""
x = xPosition(0)
y = yPosition(0)
if mouv == 0 :
self.depN(self, x, y)
elif mouv == 1 :
self.depE(self, x, y)
elif mouv == 2 :
self.depS(self, x, y)
elif mouv == 3 :
self.depO(self, x, y)
else:
return 0
""" Les 4 fonctions suivantes verifient la possibilite d'un deplacement """
def nordPossible(self):
if self.xvide == 0 :
return False
else :
return True
def sudPossible(self):
if self.xvide == 2:
return False
else:
return True
def estPossible(self):
if self.yvide == 2:
return False
else:
return True
def ouestPossible(self):
if self.yvide == 0 :
return False
else :
return True
""" Les 4 fonctions suivantes deplacent le 0 """
def depN(self):
if self.nordPossible() :
temp = self.taq[(self.xvide * 3) + self.yvide]
self.taq[(self.xvide * 3) + self.yvide] = self.taq[((self.xvide - 1) * 3) + self.yvide]
self.taq[((self.xvide - 1) * 3) + self.yvide] = temp
self.xvide = self.xvide - 1
def depS(self):
if self.sudPossible() :
temp = self.taq[(self.xvide * 3) + self.yvide]
self.taq[(self.xvide * 3) + self.yvide] = self.taq[((self.xvide + 1) * 3) + self.yvide]
self.taq[((self.xvide + 1) * 3) + self.yvide] = temp
self.xvide = self.xvide + 1
def depE(self):
if self.estPossible() :
temp = self.taq[(self.xvide * 3) + self.yvide]
self.taq[(self.xvide * 3) + self.yvide] = self.taq[((self.xvide) * 3) + self.yvide + 1]
self.taq[((self.xvide) * 3) + self.yvide + 1] = temp
self.yvide = self.yvide + 1
def depO(self):
if self.ouestPossible() :
temp = self.taq[(self.xvide * 3) + self.yvide]
self.taq[(self.xvide * 3) + self.yvide] = self.taq[((self.xvide) * 3) + self.yvide - 1]
self.taq[((self.xvide) * 3) + self.yvide - 1] = temp
self.yvide = self.yvide - 1
"""Cette methode permet de melanger n fois le Taquin"""
def melanger(self, n):
while n > 0:
self.melangerUnefois()
n = n - 1
def melangerUnefois(self):
""" Cette methode permet de melanger 1 fois le Taquin aleatoirement """
aleatoire = randint(0, 3)
if aleatoire == 0 :
self.depN()
elif aleatoire == 1 :
self.depS()
elif aleatoire == 2 :
self.depE()
elif aleatoire == 3 :
self.depO()
def afficherEtat(self):
""" Affiche l'etat du taquin dans la console """
str = "Etat du taquin\n{}|{}|{}\n{}|{}|{}\n{}|{}|{}".format(repr(self.taq[0]), repr(self.taq[1]), repr(self.taq[2]), repr(self.taq[3]), repr(self.taq[4]), repr(self.taq[5]), repr(self.taq[6]), repr(self.taq[7]), repr(self.taq[8]))
print(str)
class Noeud:
"""
La classe Noeud est defini par :
- L'etat courant du Taquin
- Le pere du Taquin courant
- Les fils du Taquin courant
- L'heuristique utilisee pour arriver au Taquin courant
- Le nombre de mouvements pour obtenir Le Taquin courant ici defini par le parametre nbMouv
- La fonction d'evaluation du Taquin courant ici defifinie par feval
- La direction precedente
- On defini la classe Noeud et ses parametres de facon suivante :
"""
def __init__(self, noeudPrecedent, paramTaquin, paramDirectPrec, paramG, distElem):
self.noeudPapa = noeudPrecedent
self.directPrec = paramDirectPrec
self.taquin = paramTaquin
self.heuristique = self.taquin.heuristique(distElem)
self.fils = []
self.g=paramG
self.f=self.g+self.heuristique
class Arbre:
"""
La classe Arbre est definie par :
- Son sommet (l'Etat Initial du Taquin)
- Son Noeud courant
- La liste de Noeuds a la Frontiere
- La liste de Noeuds deja explores
- Les methodes de creation des Fils
- La methode de comparaison de deux Taquins
- La methode de choix d'heuristique
"""
""" On prends en parametre le Taquin initial """
def __init__(self, paramTaquin, distElem):
self.sommet = Noeud(None, paramTaquin, None, 0, distElem)
self.noeudCourant = self.sommet
self.frontiere = []
self.explore = []
self.explore.append(self.sommet)
self.creerFils(None, distElem)
""" Methode de creation des fils et ajout a la frontiere si non explores """
def creerFils(self, directPrec, distElem):
listeTmp = []
tmpTq = copy.deepcopy(self.noeudCourant)
""" Verification de la possibilite de deplacement et creation des fils """
if tmpTq.taquin.nordPossible():
tmpTq.taquin.depN()
self.noeudCourant.fils.append(Noeud(self.noeudCourant, tmpTq.taquin, 0, self.noeudCourant.g+1, distElem))
tmpTq.g +=1
tmpTq.heuristique = tmpTq.taquin.heuristique(distElem)
tmpTq.f = tmpTq.g + tmpTq.heuristique
tmpTq.directPrec = 0
tmpTq.noeudPapa = copy.deepcopy(self.noeudCourant)
listeTmp.append(tmpTq)
tmpTq = copy.deepcopy(self.noeudCourant)
if tmpTq.taquin.estPossible():
tmpTq.taquin.depE()
self.noeudCourant.fils.append(Noeud(self.noeudCourant, tmpTq.taquin, 1, self.noeudCourant.g+1, distElem))
tmpTq.g +=1
tmpTq.heuristique = tmpTq.taquin.heuristique(distElem)
tmpTq.f = tmpTq.g + tmpTq.heuristique
tmpTq.directPrec = 1
tmpTq.noeudPapa = copy.deepcopy(self.noeudCourant)
listeTmp.append(tmpTq)
tmpTq = copy.deepcopy(self.noeudCourant)
if tmpTq.taquin.sudPossible():
tmpTq.taquin.depS()
self.noeudCourant.fils.append(Noeud(self.noeudCourant, tmpTq.taquin, 2, self.noeudCourant.g+1, distElem))
tmpTq.g +=1
tmpTq.heuristique = tmpTq.taquin.heuristique(distElem)
tmpTq.f = tmpTq.g + tmpTq.heuristique
tmpTq.directPrec = 2
tmpTq.noeudPapa = copy.deepcopy(self.noeudCourant)
listeTmp.append(tmpTq)
tmpTq = copy.deepcopy(self.noeudCourant)
if tmpTq.taquin.ouestPossible():
tmpTq.taquin.depO()
self.noeudCourant.fils.append(Noeud(self.noeudCourant, tmpTq.taquin, 3, self.noeudCourant.g+1, distElem))
tmpTq.g +=1
tmpTq.heuristique = tmpTq.taquin.heuristique(distElem)
tmpTq.f = tmpTq.g + tmpTq.heuristique
tmpTq.directPrec = 3
tmpTq.noeudPapa = copy.deepcopy(self.noeudCourant)
listeTmp.append(tmpTq)
tmpTq = copy.deepcopy(self.noeudCourant)
""" Verification de l'existance des fils dans la frontiere et dans la liste des Etats Explores """
for i in listeTmp:
insertion = True
for j in self.frontiere:
if self.comparerTaquin(i.taquin.taq, j.taquin.taq):
insertion = False
break
for j in self.explore:
if self.comparerTaquin(i.taquin.taq, j.taquin.taq):
insertion = False
break
if insertion:
self.frontiere.append(i)
""" Comparaison de 2 Taquin : s'ils sont pareils de type boolean """
def comparerTaquin(self, tq1, tq2):
pareil = True
i = 0
while i<9:
if tq1[i]!=tq2[i]:
pareil = False
break
i+=1
return pareil
"""
On choisi comme Noeud courant, le Noeud qui a la Fonction d'Evaluation la plus basse dans la Frontiere
On reprends l'indice du tableau Frontiere du meilleur Noeud
"""
def choisirH(self):
minimal = 5000
i=0
IndiceMeilleurNoeud=0
while i < len(self.frontiere):
if minimal > self.frontiere[i].f:
minimal = self.frontiere[i].f
IndiceMeilleurNoeud=i
i = i+1
return IndiceMeilleurNoeud
if __name__ == "__main__" :
tq = Taquin()
tq.afficherEtat()
tq.melanger(30)
tqInit = copy.deepcopy(tq)
print("Melange du taquin")
tq.afficherEtat()
"""On cree une fenetre"""
fenetre = Tk()
champ_label = Label(fenetre, text="Taquin Intelligence Artificielle")
champ_label.pack()
interface = Interface(fenetre, tq)
"""Creation des evenements clavier, ceux-ci ont ete tires d'internet"""
fenetre.bind("<Up>", interface.monter)
fenetre.bind("<Down>", interface.descendre)
fenetre.bind("<Left>", interface.gauche)
fenetre.bind("<Right>", interface.droite)
"""On boucle sur l'interface graphique"""
interface.mainloop()
interface.destroy() |
f635a9222bbc1d03ace657bca71fb237984cab49 | smrsassa/Studying-python | /curso/PY1/condicao/ex8.py | 226 | 3.796875 | 4 | salario = int(input('seu salario'))
if salario<=1250:
aumento = salario*1.15
print ('salario com aumento {:.2f}'.format(aumento))
else:
aumento = salario*1.1
print ('salario com almento {:.2f}'.format(aumento)) |
7b1e7eb73ef32188e8427139bea0272b4504096e | wangaqiang/python- | /2.linux系统编程/2.多线程/线程代码/5.mutual_lock.py | 888 | 3.578125 | 4 | from threading import Thread,Lock
g_num = 0
def task1():
global g_num
for i in range(100000):
mutax.acquire() #与另一个子线程抢着上锁 加锁加在越少的地方越好
g_num+=1
mutax.release() #成功上锁后解锁
print("子线程1的结果为%d"%g_num)
def task2():
global g_num
for i in range(100000):
mutax.acquire() #返回的是bool值
g_num+=1
mutax.release()
print("子线程2的结果为%d"%g_num)
# 创建一把互斥锁
mutax = Lock()
t1 = Thread(target=task1)
t1.start()
t2 = Thread(target=task2)
t2.start()
print("主线程的结果为%d"%g_num)
# 结论:当多个线程同时修共享的数据时,需要进行同步控制.
# 同步的意思是协同步调,指协同,协作.
# 此时引进互斥锁,原理是阻止了线程并发运行,存在问题是出现死锁. |
804d3a67d2014264bbf8c21ccbf5d7f7501d2a0c | loganyu/leetcode | /problems/2496_maximum_value_of_a_string_in_an_array.py | 1,317 | 4.4375 | 4 | '''
The value of an alphanumeric string can be defined as:
The numeric representation of the string in base 10, if it comprises of digits only.
The length of the string, otherwise.
Given an array strs of alphanumeric strings, return the maximum value of any string in strs.
Example 1:
Input: strs = ["alic3","bob","3","4","00000"]
Output: 5
Explanation:
- "alic3" consists of both letters and digits, so its value is its length, i.e. 5.
- "bob" consists only of letters, so its value is also its length, i.e. 3.
- "3" consists only of digits, so its value is its numeric equivalent, i.e. 3.
- "4" also consists only of digits, so its value is 4.
- "00000" consists only of digits, so its value is 0.
Hence, the maximum value is 5, of "alic3".
Example 2:
Input: strs = ["1","01","001","0001"]
Output: 1
Explanation:
Each string in the array has value 1. Hence, we return 1.
Constraints:
1 <= strs.length <= 100
1 <= strs[i].length <= 9
strs[i] consists of only lowercase English letters and digits.
'''
class Solution:
def maximumValue(self, strs: List[str]) -> int:
ans = 0
for string in strs:
if any(c.isalpha() for c in string):
ans = max(ans, len(string))
else:
ans = max(ans, int(string))
return ans
|
776e2aef5a7b3181c3eba48e327565c9441826ad | KylePreston/Tools_and_GUI | /Seattle_Tip_Calculator.py | 506 | 4.03125 | 4 | # Seattle Tip Calculator
# Kyle Preston 2013
bill = input ('\nWhat is the total before tax? ')
# Sales tax in Seattle, WA (2013)
tax = 0.095
bill = bill + bill*tax
print ("\nWith Seattle tax, that makes the total $%.2f." % bill)
tip = input('Enter the percentage of tip you want to leave: ')
if (tip > 40):
print ("\nWow! Must have been excellent service!")
total = bill + bill*(tip/100.)
tip = bill * (tip/100.)
print ("\nYour total is: $%.2f." % total)
print ("and your tip amount is: $%.2f.\n" % tip)
|
8d6e4a038c977f833e0bf87612f910110058d082 | arozcoder16/My-Codes | /Variables - Username and Password.py | 226 | 3.546875 | 4 | user = "rockets"
password = "raptors"
c_user = input("Enter username: ")
c_password = input("Enter password: ")
if c_user == user and c_password == password:
print("Welcome")
else:
print("Login Failed")
|
e9cd7ea95a5df1d7107b6a1a1726e21ba0b84b68 | eliangcs/projecteuler | /p76.py | 1,144 | 3.78125 | 4 | """
https://projecteuler.net/problem=76
It is possible to write five as a sum in exactly six different ways:
4 + 1
3 + 2
3 + 1 + 1
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1
How many different ways can one hundred be written as a sum of at least two
positive integers?
"""
p_cache = {}
def p(n, k):
"""
Return the number of ways of writing n as a sum where the minimum component
number is k.
For example, p(5, 1) = 5 because it has the following five ways:
4 + 1
3 + 1 + 1
2 + 2 + 1
2 + 1 + 1 + 1
1 + 1 + 1 + 1 + 1
And p(5, 2) = 1 because it only has one way:
3 + 2
"""
# Base case
if n == 2:
if k == 1:
return 1
return 0
if n == 3:
if k == 1:
return 2
return 0
if k > n / 2:
return 0
if (n, k) not in p_cache:
# Induction
p_cache[(n, k)] = sum([p(n - k, i) for i in xrange(k, n / 2 + 1)]) + 1
return p_cache[(n, k)]
def get_num_ways(n):
return sum([p(n, k) for k in xrange(1, n / 2 + 1)])
if __name__ == '__main__':
print get_num_ways(100)
|
fa2e83d91f23e2fef9fe2e9bb00aa0d2ee10dc6c | juliocpmelo/so_examples | /python_examples/threads/thread_sync.py | 867 | 3.578125 | 4 |
import threading
import time
import os
var = 10
lock = threading.Lock()
def thread_func():
global var
global lock
self_t = threading.currentThread()
while True :
print ("Sou o processo " + str(os.getpid()) + " na thread " + str(self_t.ident))
#regiao crítica, precisa ler e escrever o valor de val
lock.acquire()
print ("Valor de Var " + str(var))
var = var + 1
lock.release()
#fim da regiao crítica
time.sleep(1)
t1 = threading.Thread(target=thread_func, args=())
t2 = threading.Thread(target=thread_func, args=())
t1.start()
t2.start()
while True :
print ("Sou o processo principal " + str(os.getpid()) + " estou executando em paralelo às trhreads" + str(t1.ident) + " e " + str(t2.ident))
#regiao crítica, precisa ler e escrever o valor de val
lock.acquire()
var = var+1;
lock.release()
#fim da regiao crítica
time.sleep(1)
#
|
ad355011e8f50846f0c92390bf53172f6a9c7500 | MaksimDzhangirov/tango_with_django_2 | /manuscript/link_checker.py | 1,905 | 3.703125 | 4 | # Checks for broken links in the book chapters, printing the status of each link found to stdout.
# The Python package 'requests' must be installed and available for this simple module to work.
# Author: David Maxwell
# Date: 2017-02-14
import re
import requests
def main(chapters_list_filename, hide_success=True):
"""
hide_success = a boolean switch that determines whether to show URLs that return a HTTP 200.
If set to true, only URLs that fail will be printed.
"""
chapters_f = open(chapters_list_filename, 'r')
pattern = re.compile(r'\[([^]]+)]\(\s*(http[s]?://[^)]+)\s*\)') # http://stackoverflow.com/a/23395483
print('filename\tline_no\ttitle\turl\tstatus_code')
for filename in chapters_f:
filename = filename.strip()
if not filename or filename.startswith('{'): # Skip non-filename lines
continue
chapter_f = open(filename, 'r')
line_no = 1
for line in chapter_f:
line = line.strip()
for match in re.findall(pattern, line):
title = match[0]
url = match[1]
if (url.find("()")>0) and (url.find(")")==-1):
url = url +")"
if '127.0.0.1' in url or 'localhost' in url: # Don't check localhost URLs
continue
request = None
status_code = -1
try:
request = requests.get(url)
status_code = request.status_code
except requests.exceptions.ConnectionError:
request = None
status_code = 'FAILED_TO_CONNECT'
if hide_success and status_code == 200:
continue
title = title.replace('\t', ' ')
print('{filename}\t{line_no}\t{title}\t{url}\t{status_code}'.format(filename=filename,
line_no=line_no,
title=title,
url=url,
status_code=status_code))
line_no = line_no + 1
chapter_f.close()
chapters_f.close()
if __name__ == '__main__':
main('Book.txt', hide_success=False) |
9c04a617261bc393e02d642c98688bca2e23171e | abhinavprasad47/KTU-S1-S2-CS-IT-Python_C-programs | /Python Programmes/5_Celcius_2_Fahren_.py | 171 | 4.09375 | 4 | #Celcius To Fahrenheit
c=input("Enter the Temperature Celcius Degrees:")
#Applying The Equation
faren=(((9/5)*c)+32)
print("The Farenheit Temperature is "+str(faren))
|
075bd6674e0588a8add8e3096ae46888f051d513 | graceyqlin/Python | /GraceLinREPO/SUBMISSIONS/week_02/averages.py | 692 | 4.03125 | 4 | def averages():
try:
import math
a = int(input("Enter the first number" ))
b = int(input("Enter the second number" ))
method = int(input("Enter the method for the average (1 for arithmetic mean, 2 for geometric mean, or 3 for root-mean-square)"))
if method == 1:
print("the arthmetic mean is", format((a+b)/2,'.2f'))
elif method == 2:
print("the geometric mean is", format(math.sqrt(a*b),'.2f'))
elif method == 3:
print ("the root-mean-square is", format(math.sqrt(0.5*(a**2+b**2)),'.2f'))
else:print ("error")
except:
print("Please enter a number")
return
averages() |
806879b280c9f523a8dd3152c38597b78932dbb1 | thongchaiSH/practice-python | /phase3/ep1.py | 810 | 3.96875 | 4 | # EP1 Exception
# number1=10
# number2=0
# print(number1/number2)
'''
try:
คำสั่งรันโปรแกรมปกติ
except:
ที่ทำงานตอนโปรแกรมผิดพลาด
'''
''' Ex1
try:
number1=10
number2=0
print(number1/number2)
except:
print("Error")
finally:
print("Finally.")
'''
try:
number1 = 10
number2 = 2
print(number1/number2) # ZeroDivisionError:
except ValueError:
print("Error",ValueError)
except ZeroDivisionError:
print("ห้ามหารด้วย 0",ZeroDivisionError)
except Exception as e:
print("Error = ",e)
else: #หากรันแล้วไม่มีปัญหา Error จะทำ Else
print("จบโปรแกรม")
finally:
print("finally....")
|
d8a9a6b2028fd6eef624c65aaf58497757f61879 | ShivaniLJoshi/Banking_Project | /Term Depostie.py | 24,500 | 3.890625 | 4 | #!/usr/bin/env python
# coding: utf-8
# ## Importing the libraries
# In[2]:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
import warnings
warnings.filterwarnings('ignore')
# ## Loading and cleaning the data
# In[3]:
data = pd.read_csv('train.csv')
data.drop('Id', axis = 1, inplace = True)
print("Shape of the data is:", data.shape)
data.head()
# ## check numeric and categorical features
# In[4]:
numeric_data = data.select_dtypes(include = np.number)
numeric_col = numeric_data.columns
print('Numeric Features:')
print('====='*20)
numeric_data.head()
# In[5]:
categorical_data = data.select_dtypes(exclude = np.number)
categorical_col = categorical_data.columns
print('Categorical Features:')
print('====='*20)
categorical_data.head()
# In[6]:
data.dtypes
# ## Checking the missing values
# In[7]:
#To identify the missing values in every feature
total = data.isnull().sum() # gives the values which are missing in the form of True
percent = (total/data.isnull().count()) #total gives total missing values in each feature and count is the total of all true values of the missing values
# In[8]:
total
# In[9]:
percent
# ## Dropping the missing values
# In[10]:
#dropping features having the missing values more than 60%
data = data.drop(percent[percent > 0.6].index, axis = 1)
print(data.isnull().sum())
# In[11]:
#imputing values with mean
for column in numeric_col:
mean = data[column].mean()
data[column].fillna(mean, inplace = True)
# imputing with median (median can be used when there are outliers in the data)
#for column in numeric_col:
# median = data[column].median()
# data[column].fillna(median, inplace = True)
# ## Check for class imbalance
# In[12]:
#class imbalance is only checked on the target variable
#(normalize = True)*100 means in percentage
class_values = (data['y'].value_counts(normalize = True)*100).round(2)
print(class_values)
# In[13]:
sns.countplot(data['y'])
# ### Detect outliers in the continuous columns
# Outliers are the data points defined beyond (third quartile + 1.5*IQR) and below (first quartile -1.5*IQR) in bar plot
# In[14]:
# Illustration of detecting the outliers; percentile function divides the list in ascending order
# and finds the percentile
num_ls = [1, 2, 3, 4, 5, 6, 7, 10, 100]
# Finding the 25th and 75th percentile:
pc_25 = np.percentile(num_ls, 25)
pc_75 = np.percentile(num_ls, 75)
#Finding the IQR:
iqr = pc_75 - pc_25
print(f'25th percentile - {pc_25}, 75th percentile - {pc_75}, IQR - {iqr}')
#Calculating outliers:To calculating the outliers we need to set a threshold value beyond which
#we can consider the values as outliers
upper_threshold = pc_75 + 1.5*iqr
lower_threshold = pc_25 - 1.5*iqr
print(f'Upper - {upper_threshold}, lower - {lower_threshold}')
#plotting the outliers
plt.boxplot(num_ls)# plt.boxplot(num_ls, showfliers = False) gives the plot without outliers
# In[15]:
#Another example with more outliers
num_ls1 = [1, 2, 3, 4, 5, 6, 7, 10, 100, 120, -5, -11 ]
plt.boxplot(num_ls1)
# In[16]:
cols = list(data)# A list of all features
outliers = pd.DataFrame(columns = ['Feature', 'Number of outliers']) # Creating a new dataframe to show the outliers
for column in numeric_col:#Iterating through each feature
#First quartile (Q1)
q1 = data[column].quantile(0.25)
#third quartile
q3 = data[column].quantile(0.75)
#IQR
iqr = q3 - q1
fence_low = q1 - (1.5*iqr)
fence_high = q3 + (1.5*iqr)
#finding the number of outliers using 'and(|) condition.
total_outlier = data[(data[column] < fence_low) | (data[column] < fence_high)].shape[0]
outliers = outliers.append({'Feature': column, 'Number of outliers': total_outlier}, ignore_index = True)
outliers
# ## Exploratory data analysis (EDA) and Data Visualization
# Explotatory data analysis is an approach to analyse data sets by summerizing their main characteristics with visualizations.
# ### Univeriate analysis on categorical variable
# In[17]:
#plotting the frequency of all the values in the categorical variables.
#Selecting the categorical columns
categorical_col = data.select_dtypes(include = ['object']).columns
#plotting a bar chart for each of the categorical variable
for column in categorical_col:
plt.figure(figsize = (20, 4))
plt.subplot(121)
data[column].value_counts().plot(kind = 'bar')
plt.title(column)
# #### Observations
# From the above visuals, we can make the following observations:
# - The top three profession that our customers belong to are - administration, blue-collar jobs and technicians.
# - A huge number of the customers are married.
# - Majority of the customers do not have a credit in default
# - Many of our past customers have applied for a housing loan but very few have applied for a personal loan.
# - Cell-phones seem to the most favoured method of reaching out to the customers.
# - The plot for the target variable shows heavy imbalance in the target variable.
# - The missing values in some columns have been represented as unknown- Unknown represents missing data. In the next task, we will treat these values.
# ## Univeriate analysis on Continuous/Numeric Columns
# In[18]:
for column in numeric_col:
plt.figure(figsize = (20, 4))
plt.subplot(121)
plt.hist(data[column])
plt.title(column)
# #### Imputing unknown values of categorical columns
# One method of imputing unknown values is to directly impute them with the mode value of respective columns.
# In[19]:
#Impute missing values of categorical columns
for column in categorical_col:
mode = (data[column]).mode()[0]
data[column] = data[column].replace('unknown', mode)
# In[20]:
data['job'].value_counts()
# In[21]:
data['job'].mode()
# In[22]:
for column in numeric_col:
plt.figure(figsize = (20, 4))
plt.subplot(121)
plt.boxplot(data[column])
plt.title(column)
# #### Observation :
# 1. As we see from the histogram, the features age, duration and campaign are heavily skewed and this is due to the presence of outliers as seen on the boxplot for these features.
# 2. Looking at the plot for pdays, we can infer that majority of the customers were being contacted for the first time because as per the feature descriptionf for pdays and previous consist majority only of single value, their variance is quite less and hence we can drop them since technically will be of no help in prediction.
# In[23]:
data['pdays'].value_counts(normalize = True)
# In[24]:
data['previous'].value_counts(normalize = True)
# ### Dropping the columns pdays and previous
# In[25]:
data.drop(['pdays', 'previous'], 1, inplace = True)#here 1 is the axis i.e the column
# ### Bivartate Analysis - Categorical Columns
# In[26]:
for column in categorical_col:
plt.figure(figsize = (20,4))
plt.subplot(121)
sns.countplot(x = data[column], hue = data['y'], data = data )
plt.title(column)
plt.xticks(rotation = 90)
# ### Observation:
# The common traits seen for the customers who subscribed for term depostit are-
# - Customers having administrative jobs from the majority amongst those who have subscribed to the term deposite with technicians being the second majority.
# - They are married.
# - They hold a university degree.
# - They dont hold a credit in default.
# - Housing loan doesn't seem a priority to check for since an equal number of customers who have not subscribed to it seem to have subscribed to the term deposit.
# - Cell-phones should be the prefered mode of contact for contacting customers.
# ### Treating the outliers in continuous column
# upper threshold = 25
# lower threshold = 10
#
# > (>25 and <10) = outlier
#
# if x < lower threshold -> replace with 10
# if x > upper threshold -> replace with 25
#
# #### This process is called as "winsorization". In this method we define a confidence interval of let's say 90% and then repalce all the outliers below the 5th percentile with the value above 95th percentile with the value of 95th percentile.
# ### Example of using winsorization:
# np.percentile([1, 2, 3, 4, 5, 6, 7, 10, 100], 95)
# >output: 63.99999999999997
#
# np.percentile([1, 2, 3, 4, 5, 6, 7, 10, 100], 5)
# >output: 1.4
#
# Any value above 63.99 will be replaced by 63.99
# and any value below 1.4 will be replaced by 1.4
# In[27]:
from scipy.stats.mstats import winsorize
# In[28]:
numeric_col = data.select_dtypes(include = np.number).columns
for col in numeric_col:
data[col] = winsorize(data[col], limits = [0.05, 0.1], inclusive = (True, True))
# In[29]:
numeric_col
# #### Machine learning models do not accept string as input hence we convert the categories into numbers this process is called as "Label Encoding"
# #### And the process in which we create seperate column for each category of the categorical variable is called as "One-hot Encoding"
# In[30]:
#Illustration of label encoding:
data1 = data.copy()
# In[31]:
marital_dict = {'married': 0, 'divorced': 1, 'single': 2}
# In[32]:
data1['marital_num'] = data1.marital.map(marital_dict)
# In[33]:
data1[['marital', 'marital_num']]
# In[34]:
#Illustration of One-hot Encoding:
pd.get_dummies(data1, columns = ['marital'])
# In[35]:
data1.drop('marital_num', axis = 1, inplace = True)
# In[36]:
data1
# ## Applying vanilla models on the data
#
# Since we have prerformed preprocessing on our data and also done with the EDA part, it is now time to apply vanilla machinelearning models on the data and check their performance
#
# ### Function to label encode categorical variables
#
# Before applying ml algo, we need to recollect that any algo can only read numerical values. It is therefore, essential to encode categorical features into numerical values. Encoding of categorical variables can be performed in two ways:
#
# - Label Encoding
# - One-Hot Encoding
# In[37]:
from sklearn.preprocessing import LabelEncoder, MinMaxScaler, StandardScaler
# In[38]:
#Initialize the label encoder
le = LabelEncoder()
#Iterating through each of the categorical columns and label encoding them
for feature in categorical_col:
try:
data[feature] = le.fit_transform(data[feature])
except:
print('Error encoding'+feature)
# In[39]:
data
# ### Fit vanilla classifier models
#
# There are many classifier algorithms:
# - Logistic Regression
# - DecisionTree Classifier
# - RandomForest Classifier
# - XGBClassifier
# - GradientBoostingClassifier
#
# The code below splits the data into training data and validation data. It then fits the classification model on the train data and then makes a prediction on the validation data and outputs the roc_auc_score and roc_curve for this prediction.
# #### Preparing the train and test data
# In[40]:
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
# In[41]:
#Predictors
X = data.iloc[:,:-1]
#Target
y = data.iloc[:,-1]
#Dividing the data into train and test subsets
x_train,x_val,y_train,y_val = train_test_split(X, y, test_size = 0.2, random_state= 42)
# #### FITTING THE MODEL AND PREDICTING THE VALUES
# In[42]:
#Run Logistic Regression model
model = LogisticRegression()
#fitting the model
model.fit(x_train, y_train)
#predicting the values
y_scores = model.predict(x_val)
# #### GETTING THE METRICS TO CHECK OUR MODEL PERFORMANCE
# In[43]:
from sklearn.metrics import roc_auc_score, mean_squared_error, accuracy_score, classification_report, roc_curve, confusion_matrix
# In[44]:
#GETTING THE AUC ROC CURVE
auc = roc_auc_score(y_val, y_scores)
print('Classification Report:')
print(classification_report(y_val, y_scores))
false_positive_rate, true_positive_rate, thresholds = roc_curve(y_val, y_scores)
print('ROC_AUC_SCORE is', roc_auc_score(y_val, y_scores))
#fpr, tpr, _ = roc_curve(y_test, predictions[:,1])
plt.plot(false_positive_rate, true_positive_rate)
plt.xlabel('FPR')
plt.ylabel('TPR')
plt.title('ROC Curve')
plt.show()
# In[45]:
from sklearn.tree import DecisionTreeClassifier
#Run on Decision Tree Classifier
model = DecisionTreeClassifier()
model.fit(x_train, y_train)
y_score = model.predict(x_val)
auc = roc_auc_score(y_val, y_score)
false_positive_rate, true_positive_rate, thresholds = roc_curve(y_val, y_scores)
print('ROC_AUC_SCORE is', roc_auc_score(y_val, y_scores))
#fpr, tpr, _ = roc_curve(y_test, predictions[:,1])
plt.plot(false_positive_rate, true_positive_rate)
plt.xlabel('FPR')
plt.ylabel('TPR')
plt.title('ROC Curve')
plt.show()
# In[46]:
#Run random Forest classifier
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier()
model.fit(x_train, y_train)
y_scores = model.predict(x_val)
auc = roc_auc_score(y_val, y_scores)
print('Classification Report:')
print(classification_report(y_val, y_scores))
false_positive_rate, true_positive_rate, threshold = roc_curve(y_val, y_scores)
print('ROC_AUC_SCORE is', roc_auc_score(y_val, y_scores))
#fpr, tpr, _ = roc_curve(y_test, predictions[:,1])
plt.plot(false_positive_rate, true_positive_rate)
plt.xlabel('FPR')
plt.ylabel('TPR')
plt.title('ROC curve')
plt.show()
# In[47]:
#Run on XGBoost model
from xgboost import XGBClassifier
model = XGBClassifier()
model.fit(x_train, y_train)
y_scores = model.predict(x_val)
auc = roc_auc_score(y_val, y_scores)
print('Classification Report is:')
print(classification_report(y_val, y_scores))
false_positive_rate, true_positive_rate, threshold = roc_curve(y_val, y_scores)
print('ROC_AUC_SCORE is',roc_auc_score(y_val, y_scores))
plt.plot(false_positive_rate, true_positive_rate)
plt.xlabel('FPR')
plt.ylabel('TPR')
plt.title('ROC curve')
plt.show()
# In[48]:
#Run Gradient Boosting classifier
from sklearn.ensemble import GradientBoostingClassifier
model = GradientBoostingClassifier()
model.fit(x_train, y_train)
y_scores = model.predict(x_val)
auc = roc_auc_score(y_val, y_scores)
print('Classification Report is:')
print(classification_report(y_val, y_scores))
false_positive_rate, true_positive_rate, threshold = roc_curve(y_val, y_scores)
print('ROC_AUC_SCORE is',roc_auc_score(y_val, y_scores))
plt.plot(false_positive_rate, true_positive_rate)
plt.xlabel('FPR')
plt.ylabel('TPR')
plt.title('ROC curve')
plt.show()
# ## Feature Selection
# Now that we have applied vanilla models on our data we now have a basic understanding of what our predictions look like. Let's now use feature selection methods for identifying the best of features for each model.
#
# ## Using RFE(Recursive Feature Elimination ) for feature selection
# In this task let's use Recursive Feature Elimination for selecting the best features. RFE is a wrapper method that uses the model to identify the best features.
#
# - For the below task, we have inputted a feature. We can change the value and input the number of features you want to retain for your model
# In[49]:
from sklearn.feature_selection import RFE
#Selecting 8 number of features
#Selecting models
models = LogisticRegression()
#using rfe and selecting 8 features
rfe = RFE(models, 8)
#fitting the model
rfe = rfe.fit(X, y)
#Ranking features
feature_ranking = pd.Series(rfe.ranking_, index = X.columns)
plt.show()
print('Features to be selected for Logistic Regression model are:')
print(feature_ranking[feature_ranking.values == 1].index.tolist())
print('===='*30)
# In[50]:
#Selecting 8 number of features
#Random Forest Classifier model
models = RandomForestClassifier()
#using rfe and selecting 8 features
rfe = RFE(models, 8)
rfe = rfe.fit(X, y)
feature_ranking = pd.Series(rfe.ranking_, index = X.columns)
plt.show()
print('Features to be selected for Logistic Regression model are:')
print(feature_ranking[feature_ranking.values == 1].index.tolist())
print('===='*30)
# In[51]:
#Selecting 8 number of features
#XGBoost Classifier model
models = XGBClassifier()
#using rfe and selecting 8 features
rfe = RFE(models, 8)
rfe = rfe.fit(X, y)
feature_ranking = pd.Series(rfe.ranking_, index = X.columns)
plt.show()
print('Features to be selected for Logistic Regression model are:')
print(feature_ranking[feature_ranking.values == 1].index.tolist())
print('===='*30)
# ### Feature Selection using Random Forest
# Random Forests are often used for feature selection in a data science workflow. This is because the tree based stratergies that random forests use, rank the features based on how well they improve the purity of the node. This nodes having a very low impurity get split at the start of the tree while the nodes having a very high impurity get split towards the end of the tree. Hence, by pruning the tree after desired amount of splits, we can create a subset of the most important features.
# In[52]:
#Splitting the data into train and test data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.3, random_state = 42, stratify = y)
#Selecting the data
rfc = RandomForestClassifier(random_state = 42)
#Fitting the data
rfc.fit(X_train, y_train)
#Predicting the data
y_pred = rfc.predict(X_test)
#Feature importances
rfc_importances = pd.Series(rfc.feature_importances_, index = X.columns).sort_values().tail(10)
#plotting bar chart according to feature importance
rfc_importances.plot(kind = 'bar')
plt.show()
# #### Observation:
# We can test the features obtained from both the selection techniques by inserting the model and depending on which set of features perform better, we can retain them from the model.
#
# The feature selection techniques can differ from problem to problem and the techniques applied for an algorithm may or may not work for the other problems. In those cases, feel free to try out other methods like PCA, SelectKBest(), SelectPercentile(), ISNE etc.
# ## Grid - Search and Hyperparameter Tuning
# Hyperparameters are function attributes that we have to specify for an algorithm. By now, you should be knowing that grid search is done to find out the best set of hyperparameters for your model.
#
# #### Grid Search for Random- Forest
# In the below task, we write a code that performs hyperparameter tuning for a random forest classifier. We have used the hyperparameters max_features, max_depth and criterion for this task. Feel free to play around with this function by introducing a few more hyperparameters and changing their values.
# In[53]:
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
#splitting the data
x_train, x_val, y_train, y_val = train_test_split(X, y, test_size = 0.3, random_state = 42, stratify = y)
#selecting the classifier
rfc = RandomForestClassifier()
#Selecting the parameters
param_grid = {
'max_features':['auto', 'sqrt', 'log2'],
'max_depth':[4, 5, 6, 7, 8],
'criterion':['gini', 'entropy']
}
#using grid search with respective parameters
grid_search_model = GridSearchCV(rfc, param_grid = param_grid)
#fitting the model
grid_search_model.fit(x_train, y_train)
#printing the best parameters
print('Best parameters are:', grid_search_model.best_params_)
# ### Applying the best parameters obtained using Grid Search on Random Forest model
# In the task below, we fit a random forest model using the best parameters obtained using Grid Search. Since the target is imbalanced, we apply Synthetic Minority Oversampling (SMOTE) for undersampling and oversampling the majority and minority classes in the target respectively.
#
# #### Kindly note that SMOTE should always be applied only on the training data and not on the validation and test data.
# In[58]:
from sklearn.metrics import roc_auc_score,roc_curve,classification_report
from sklearn.model_selection import cross_val_score
from imblearn.over_sampling import SMOTE
from sklearn.linear_model import Ridge,Lasso
from yellowbrick.classifier import roc_auc
def grid_search_random_forrest_best(dataframe,target):
x_train,x_val,y_train,y_val = train_test_split(dataframe,target, test_size=0.3, random_state=42)
# Applying Smote on train data for dealing with class imbalance
smote = SMOTE(random_state = 42)
X_sm, y_sm = smote.fit_sample(x_train, y_train)
rfc = RandomForestClassifier(n_estimators=11, max_features='auto', max_depth=8, criterion='entropy',random_state=42)
rfc.fit(X_sm, y_sm)
y_pred = rfc.predict(x_val)
print(classification_report(y_val, y_pred))
print(confusion_matrix(y_val, y_pred))
visualizer = roc_auc(rfc, X_sm, y_sm, x_val, y_val)
grid_search_random_forrest_best(X,y)
# ### Applying the grid search function for random forest only on the best features obtained using RFE
# In[64]:
#Random Forest Classifier
grid_search_random_forrest_best(X[['age', 'job', 'education', 'day_of_week', 'duration', 'campaign', 'euribor3m', 'nr.employed']], y)
# ### Applying the grid search function for Logistic Regression
# In[67]:
def grid_search_log_reg(dataframe,target):
x_train,x_val,y_train,y_val = train_test_split(dataframe, target, test_size=0.3, random_state=42)
smote = SMOTE(random_state = 42)
X_sm, y_sm = smote.fit_sample(x_train, y_train)
log_reg = LogisticRegression()
param_grid = {
'C' : np.logspace(-5, 8, 15)
}
grid_search = GridSearchCV(log_reg, param_grid=param_grid)
grid_search.fit(X_sm, y_sm)
y_pred = grid_search.predict(x_val)
print(classification_report(y_val, y_pred))
print(confusion_matrix(y_val, y_pred))
visualizer = roc_auc(rfc, X_sm, y_sm, x_val, y_val)
grid_search_log_reg(X, y)
# ### Applying the grid search function for XGBoost
# In[69]:
def xgboost(dataframe,target):
#X = dataframe
#y = target
x_train,x_val,y_train,y_val = train_test_split(X, y, test_size=0.3, random_state=42)
smote = SMOTE(random_state = 42)
X_sm, y_sm = smote.fit_sample(x_train, y_train)
model = XGBClassifier(n_estimators=50, max_depth=4)
model.fit(pd.DataFrame(X_sm,columns=x_train.columns), y_sm)
y_pred = model.predict(x_val)
print(classification_report(y_val, y_pred))
print(confusion_matrix(y_val, y_pred))
visualizer = roc_auc(rfc, X_sm, y_sm, x_val, y_val)
xgboost(X, y)
# ### Ensembling
# Ensemble learning uses multiple machine learning models to obtain better predictive performance than could be obtained from any of the constituent learning algorithms alone. In the below task, we have used an ensemble of three models - RandomForestClassifier(), GradientBoostingClassifier(), LogisticRegression().
# In[73]:
from sklearn.metrics import confusion_matrix
from sklearn.ensemble import VotingClassifier
#splitting the data
x_train, x_val, y_train, y_val = train_test_split(X, y, test_size = 0.3, random_state = 42)
#using smote
smote = SMOTE(random_state = 42)
X_sm, y_sm = smote.fit_sample(x_train, y_train)
model1 = RandomForestClassifier()
model2 = GradientBoostingClassifier()
model3 = LogisticRegression()
#Fitting the model
model = VotingClassifier(estimators = [('rf', model1), ('lr', model2), ('xgb', model3)], voting = 'soft')
model.fit(X_sm, y_sm)
#Predicting values and getting the metrics
y_pred = model.predict(x_val)
print(classification_report(y_val, y_pred))
print(confusion_matrix(y_val, y_pred))
visualizer = roc_auc(model, X_sm, y_sm, x_val, y_val)
# ### Prediction on the test data
# In[74]:
# Actual Test File
test = pd.read_csv('test.csv')
# Storing the Id column
Id = test[['Id']]
# Preprocessed Test File
test = pd.read_csv('test_preprocessed.csv')
test.drop('Id',1,inplace=True)
test.head()
# In[77]:
def grid_search_log_reg(dataframe,target):
x_train,x_val,y_train,y_val = train_test_split(dataframe, target, test_size=0.3, random_state=42)
smote = SMOTE(random_state = 42)
X_sm, y_sm = smote.fit_sample(x_train, y_train)
log_reg = LogisticRegression()
param_grid = {
'C' : np.logspace(-5, 8, 15)
}
grid_search = GridSearchCV(log_reg, param_grid=param_grid)
grid_search.fit(X_sm, y_sm)
# Predict on the preprocessed test file
y_pred = grid_search.predict(test)
return y_pred
prediction = pd.DataFrame(grid_search_log_reg(X,y),columns=['y'])
submission = pd.concat([Id,prediction['y']],1)
submission.to_csv('submission.csv',index=False)
# In[ ]:
|
b5412234c660c3cae5674ce5e763239d3e87cbb0 | stumash/AlgorithmChallenges | /edu/stanford/2019_cs97si/lec04_dynamic_programming/one-dimensional-example.py | 1,354 | 3.640625 | 4 | from typing import List
def sol(xs: List[int], n: int, top_down_NOT_bottom_up=True):
"""
How manys combos of numbers in xs sum to n?
E.g. n=5, xs=[1,3,4]:
5 =
= 1 + 1 + 1 + 1 + 1 | 1
= 1 + 1 + 3 | + 1
= 1 + 3 + 1 | + 1
= 3 + 1 + 1 | + 1
= 1 + 4 | + 1
= 4 + 1 | + 1
| ----
| 6 <- there are six combos
"""
memo = [0]*(n+1)
memo[0] = 1
if top_down_NOT_bottom_up:
def dp(n):
if n < 0:
return 0
if memo[n]:
return memo[n]
return sum(dp(n-x) for x in xs)
else:
def dp(n):
for i in range(1,n+1):
for x in xs:
if i-x < 0:
continue
memo[i] += memo[i-x]
return memo[n]
return dp(n)
def test():
xs = [1,3,4]
n = 10
print(f"xs: {xs}, n: {n}, top_down_NOT_bottom_up=True")
for i in range(0, n):
print(f"{i}: {sol(xs, i, top_down_NOT_bottom_up=True)}")
print()
print(f"xs: {xs}, n: {n}, top_down_NOT_bottom_up=False")
for i in range(0, n):
print(f"{i}: {sol(xs, i, top_down_NOT_bottom_up=False)}")
|
bcca4ef6b304b67d7cdaa522fb8b8169c9bee41b | Cooops/Coding-Challenges | /CodeWars/unique_number.py | 733 | 4.25 | 4 | # http://www.codewars.com/kata/find-the-unique-number-1/train/python
"""
There is an array with some numbers. All numbers are equal except for one. Try to find it!
findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2
findUniq([ 0, 0, 0.55, 0, 0 ]) === 0.55
It’s guaranteed that array contains more than 3 numbers.
The tests contain some very huge arrays, so think about performance.
This is the first kata in series:
Find the unique number (this kata)
Find the unique string
Find The Unique
"""
# MY SOLUTION
from collections import Counter
def find_uniq(arr):
x = Counter(arr)
for x in x.most_common(2)[::-1]:
return x[0]
# TOP SOLUTION
def find_uniq(arr):
a, b = set(arr)
return a if arr.count(a) == 1 else b
|
c106bd4f036d7506fe1fd53d56bba9f0a4f522dd | msaid1996/pythonIntro | /PycharmProjects/python_intro/function_scrabble.py | 692 | 3.859375 | 4 | def scrabble(word):
point = ["a", "e", "i", "o", "u", "L", "n", "r", "s", "t"]
dgpoint = ["d", "g"]
bcpoint = ["b", "c", "m", "p"]
fhpoint = ["f", "h", "v", "w", "y"]
kpoint = ["k"]
jpoint = ["j", "x"]
qpoint = ["q", "z"]
count = 0
for i in word:
if i in point:
count += 1
if i in dgpoint:
count += 2
if i in bcpoint:
count += 3
if i in fhpoint:
count += 4
if i in kpoint:
count += 5
if i in jpoint:
count += 8
if i in qpoint:
count += 10
return count
ask = input("what is your word? ")
print(scrabble(ask))
|
04c131651d3eef286f5b87e4db388c0bad89ffa2 | jonny21099/DataBase-Email-Search | /prepDF.py | 3,645 | 3.640625 | 4 | import re
#This function writes to terms.txt file
def prepTerms(inFile):
termsFile = open("terms.txt", "w+") #Creates terms.txt with w+ (writing and reading) rights
with open(inFile, 'r') as file: #Opens inFile (xml file passed as argument)
for line in file: #for loop for each line
if line.startswith("<mail>"): #Only take lines starting with <mail>
if line.split("<subj>")[1].split("</subj>")[0] != "": #checks if <subj> content is non-empty
for term in re.split("[^A-Za-z0-9\-_]+", re.sub("&.*?;", " ", line.split("<subj>")[1].split("</subj>")[0])): #splits by all chars except [A-Za-z0-9_-], substitutes all instances of &xxx; with space char, splits by <subj> and </subj> to get contents
if len(term) > 2: #only write to file if the term length is greater than 2
termsFile.write("s-%s:%s\n" %(term.lower(), line.split("<row>")[1].split("</row>")[0])) #write the term and row id
if line.split("<body>")[1].split("</body>") != "": #checks if <body> content is non-empty
for term in re.split("[^A-Za-z0-9\-_]+", re.sub("&.*?;", " ", line.split("<body>")[1].split("</body>")[0])): #splits the same as above for <subj>
if len(term) > 2: #only write term length > 2
termsFile.write("b-%s:%s\n" %(term.lower(), line.split("<row>")[1].split("</row>")[0])) #write the term and row id
#This functions write to emails.txt file
def prepEmails(inFile):
emailsFile = open("emails.txt", "w+") #same as above but for emails.txt
with open(inFile, 'r') as file: #same as above
for line in file: #same as above
if line.startswith("<mail>"): #same as above
emailsFile.write("from-%s:%s\n" %(line.split("<from>")[1].split("</from>")[0],line.split("<row>")[1].split("</row>")[0])) #write <from> contents into file. No condition since will always have from email
if line.split("<to>")[1].split("</to>")[0] != "": #checks if <to> content is non-empty
for email in line.split("<to>")[1].split("</to>")[0].split(","): #for loop to print all emails in <to> split by ','
emailsFile.write("to-%s:%s\n" %(email,line.split("<row>")[1].split("</row>")[0])) #writes <to> contents and row id to file
if line.split("<cc>")[1].split("</cc>")[0] != "": #checks if <cc> content is non-empty
for email in line.split("<cc>")[1].split("</cc>")[0].split(","): #for loop to print all emails in <cc> split by ','
emailsFile.write("cc-%s:%s\n" %(email,line.split("<row>")[1].split("</row>")[0])) #writes <cc> contents and row id to file
if line.split("<bcc>")[1].split("</bcc>")[0] != "": #checks if <bcc> content is non-empty
for email in line.split("<bcc>")[1].split("</bcc>")[0].split(","): #for loop to print all emails in <bcc> split by ','
emailsFile.write("bcc-%s:%s\n" %(email,line.split("<row>")[1].split("</row>")[0])) #writes <bcc> contents and row id to file
def prepDates(inFile):
datesFile = open("dates.txt", "w+") #same as above but for dates.txt
with open(inFile, 'r') as file: #same as above
for line in file: #same as above
if line.startswith("<mail>"): #same as above
datesFile.write("%s:%s\n" %(line.split("<date>")[1].split("</date>")[0],line.split("<row>")[1].split("</row>")[0])) #writes <date> content and row id
def prepRecs(inFile):
recsFile = open("recs.txt", "w+") #same as above but for recs.txt
with open(inFile, 'r') as file: #same as above
for line in file: #same as above
if line.startswith("<mail>"): #same as above
recsFile.write("%s:%s" %(line.split("<row>")[1].split("</row>")[0], line)) #writes row id and full line
|
409ca415e1f91e94bbd1328112062488bb267f1f | Loai17/Y--Project | /agario.py | 1,341 | 3.640625 | 4 | import turtle, time, random
from turtle import *
from ball import Ball
turtle.colormode(255)
# qturtle.speed(100)
RUNNING=True
SLEEP=0.0077
SCREEN_WIDTH=turtle.getcanvas().winfo_width()/2
SCREEN_HEIGHT=turtle.getcanvas().winfo_height()/2
my_ball=Ball(0,0,5,5,20,"green")
NUMBER_OF_BALLS = 5
MINIMUM_BALL_RADIUS = 10
MAXIMUM_BALL_RADIUS = 100
MINIMUM_BALL_DX = -5
MAXIMUM_BALL_DX = 5
MINIMUM_BALL_DY = -5
MAXIMUM_BALL_DY = 5
BALLS = []
for ball in range(NUMBER_OF_BALLS):
x = random.randint((-SCREEN_WIDTH+MAXIMUM_BALL_RADIUS),(SCREEN_WIDTH-MAXIMUM_BALL_RADIUS))
y = random.randint((-SCREEN_HEIGHT+MAXIMUM_BALL_RADIUS),(SCREEN_HEIGHT-MAXIMUM_BALL_RADIUS))
dx = random.randint(MINIMUM_BALL_DX,MAXIMUM_BALL_DX)
dy = random.randint(MINIMUM_BALL_DY,MAXIMUM_BALL_DY)
r = random.randint(MINIMUM_BALL_RADIUS,MAXIMUM_BALL_RADIUS)
color = (random.randint(0,255),random.randint(0,255),random.randint(0,255))
new_ball = Ball(x,y,dx,dy,r,color)
BALLS.append(new_ball)
def move_all_balls():
for ball in BALLS:
ball.move(SCREEN_WIDTH,SCREEN_HEIGHT)
def collide(ball1,ball2):
if ball1==ball2:
return False
#Calculate distance between 2 balls
#Continue part 2
def check_all_balls_collision():
for ball1 in BALLS:
for ball2 in BALLS:
if(collide(ball1,ball2)):
r1=ball1.r
r2=ball2.r
move_all_balls()
turtle.mainloop() |
ac25290b5e5922b2a48bea505449675878534c2d | RonaldTheodoro/ExemploTK | /tk01/main5.py | 251 | 3.734375 | 4 | from tkinter import *
from tkinter import messagebox
root = Tk()
answer = messagebox.askquestion('Question 1', 'yes or no')
if answer == 'yes':
messagebox.showinfo('teste', 'yes')
else:
messagebox.showinfo('teste', 'no')
root.mainloop()
|
39f1bf1e53447f37e307f27f3375b978c144f245 | gauravdhama/project_euler_solutions | /Problem3.py | 631 | 3.859375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Aug 09 19:55:07 2016
@author: e065689
"""
import math
#Prime Factors
def isprime(n):
i=2
while True:
if n%i==0 and not(i==n):
return False
break
if i>=n:
break
i=i+1
return True
n = 60085147514313195
while (n%2==0):
n = n/2
i = 3
largest = 2
while True:
if isprime(i) and n%i==0:
largest = i
print largest
n = n/i
if i>=math.sqrt(n):
break
i = i+2
if n>2 and isprime(n):
largest=n
print "Final Value : "+str(largest) |
de96445f919a6ec26e76e38c3735868f28481a4e | Kamakepar2029/linux-testing | /GEN.py | 271 | 3.59375 | 4 | print ('Starting...')
a = int(input('How many MB> '))
end = a*10*10*10*10*10
f = open('testfile.try.txt', 'w')
start = 0
while (start < end):
f.write('testfile \n')
start = start + 1
print ('(Till End missing ',end / start, '% from ' ,end, ' till ', start)
f.close()
|
007434bbb33fbac3c0c3053d67af99c022c79b97 | 1877762890/python_all-liuyingyign | /day06/demon6.py | 4,600 | 3.65625 | 4 | # string="this is a dog,that is a monkey!"
# #将字符串转换成列表
# li = list(string)
#
# for i in range(0,len(li)):
# count=0 #计数器
# #排重
# flag=True #开关置为开
# for k in range(0,i):
# if li[k] == li[i]:
# flag=False #一旦发现相同字符,开关置位关闭
# break
#
# if flag == False:#判断开关是否是关闭状态,便于判断是否发现是否统计过
# continue #终止循环,继续下一轮循环
# #统计
# for j in range(0,len(li)):
# if li[i] == li[j]:
# count+=1
# print(li[i],"出现了",count,"次!")
#身份运算符 in not in
'''
方法:函数
def 方法名():
方法体
好处:一本万利,写一次,能多次使用
'''
# def sum(a,b):#申明一个方法,能接受两个数,并对接受的数据进行求和,然后使用return进行返回
# print("已登录火星")
# c=a+b
# print("任务完成,准备返回地球")
# return c
# print("准备登陆火星....")
# s=sum(1,2)
# print("返回成功!")
# print(s)
#有下列列表,请编程实现列表的数据翻转(京东金融的测试开发笔试题)
#List = [1,2,3,4,5,6,7,8,9]
#实现效果:list = [9,8,7,6,5,4,3,2,1]
list=[1,2,3,4,5,6,7,8,9]
for i in range(len(list)):
for j in range(i+1,len(list)):
if list[j] > list[i]:
list[j],list[i]=list[i],list[j]
print("list:",list)
#请编程统计列表中的每个数字出现的次数(百度初级测试开发笔试题)
'''
list = [1,4,7,5,82,1,3,4,5,9,7,6,1,10]
for index,ch in enumerate(list):
if ch in list[:index]:
continue
print(ch,"出现了",list.count(ch),"次")
'''
#使用字典的方式来存: key:value 数字:次数
# li=[1, 4, 7, 5, 82, 1, 3, 4, 5, 9, 7, 6, 1, 10]
# d={}
# for i in li:
# if i in d:
# d[i]=d[i]+1
# else:
# d[i]=1
# print(d)
# 编程实现列表的折线输出(美团笔试题)
# a = [
# [1, 2, 3 , 4],
# [5, 6, 7 , 8],
# [9, 10 , 11, 12],
# [13, 14 , 15, 16]
# ]
# 实现输出:4,3,8,2,7,12,1,6,11,16,5,10,15,9,14,13
# 姓名 年龄 性别 编号 任职公司 薪资 部门编号
'''
names=[
["何登勇","56","男","106","IBM",500,"50"],
["曹冬雪","19","女","230","微软",501,"60"],
["刘营营","19","女","210","Oracle",600,"60"],
["李汉聪","45","男","230","Tencent",700,"10"]
]
'''
#统计每个人的平均薪资
'''
sum=0
n=0
for i in range(len(names)):
sum=sum+names[i][5]
n=sum/len(names)
print(n)
'''
#统计每个人的平均年龄
'''
sum1=0
m=0
for j in range(len(names)):
sum1=sum1+int(names[j][1])
m=sum1/len(names)
print(m)
'''
#公司新来一个员工,张佳伟,45,男,220,alibaba,500,30,添加到列表中
'''
names.append(["张佳伟","45","男","220","alibaba",500,"30"])
print(names)
'''
#统计公司男女人数
'''
for i in range(0,len(names)):
count=0
flag=True
for k in range(0,i):
if names[k][2]==names[i][2]:
flag=False
break
if flag==False:
continue
for j in range(0,len(names)):
if names[i][2]==names[j][2]:
count+=1
print(names[i][2],"出现了",count,"次!")
'''
# for i in range(len(names)):
# man=0
# woman=0
# for j in range(len(names)):
# if names[i][2]==names[j][2]:
# man+=1
# if names [i][2]!=names[j][2]:
# woman+=1
# print("男人出现:",man,"次","女人出现:",woman,"次")
#每个部门的人数
'''
for i in range(0,len(names)):
count=0
flag=True
for k in range(0,i):
if names[k][6]==names[i][6]:
flag=False
break
if flag==False:
continue
for j in range(0,len(names)):
if names[i][6]==names[j][6]:
count+=1
print(names[i][6],"部门有",count,"人!")
'''
'''
a=[
[10,14,9,15],
[7,4,8,10],
[6,8,4,9],
[8,51,10,23]
]
max=0
least=0
for i in range(0,len(a)):
if a[i]>max:
max=a[i]
for j in range(0,len(a)):
if a[j]<least:
least=a[j]
print("最大为:",max,"最小为:",least)
'''
|
3509e6c9ee2d6fa2806cb80575da7f2d752c26b5 | oJacker/_python | /numpy_code/04/eigenvalues.py | 746 | 3.65625 | 4 | import numpy as np
A = np.mat("3 -2;1 0")
print ("A\n", A)
# (2) 调用eigvals函数求解特征值:
print ("Eigenvalues", np.linalg.eigvals(A))
# (3) 使用eig函数求解特征值和特征向量。该函数将返回一个元组,按列排放着特征值和对应的特征向量,其中第一列为特征值,第二列为特征向量。
eigenvalues, eigenvectors = np.linalg.eig(A)
print ("First tuple of eig", eigenvalues)
print ("Second tuple of eig\n", eigenvectors)
# (4) 使用dot函数验证求得的解是否正确。分别计算等式 Ax = ax 的左半部分和右半部分,检查是否相等。
for i in range(len(eigenvalues)):
print ("Left", np.dot(A, eigenvectors[:,i]))
print ("Right", eigenvalues[i] * eigenvectors[:,i]) |
b1c63dcfb71aaf0cd0e28cc252fa737cefad36fc | patience111/PY-CS-algo | /Using_bisection_search_to_approximate_square_root.py | 407 | 3.765625 | 4 | x=-25
epsilon=0.01
numGuesses=0
low=0.0
high=max(1.0,abs(x))
ans=(high+low)/2.0
while abs(ans**2-abs(x))>=epsilon:
print('low=', low,'high=',high,'ans=',ans)
numGuesses+=1
if ans**2<abs(x):
low=ans
else:
high=ans
ans=(high+low)/2.0
print('numGuesses=',numGuesses)
if x>0:
print(ans,'is close to square root of',x)
else:
print(-ans,'is close to square root of',x)
|
6641e5431625b62e02287442acdf78a2f2030231 | FlankL/DeepLearning | /jicheng/Student.py | 740 | 4.15625 | 4 | # 创建一个类
class Student():
# 特殊方法都是以__开头,__结尾的方法
# 特殊方法不需要我们自己调用
def __init__(self, name):
self.__name = name
def __run(self):
print(self.__name, "run")
def say(self):
self.__run()
print(self.__name, 'say')
# def getName(self):
# return self.__name
#
# def setName(self, name):
# self.__name = name
# 使用装饰器来简写getter(),setter()方法
@property
def name(self):
return self.__name
@name.setter
def name(self,name):
self.__name=name
s1 = Student('tom')
# 通过get ,set获取属性
# print(s1.getName())
s1.name='jack'
print(s1.name)
s1.say()
|
83162de4c60717aef57145b8a503dce19466310f | vsdrun/lc_public | /co_amazon/725_Split_Linked_List_in_Parts.py | 2,817 | 4.0625 | 4 | #!/usr/bin/env python
"""
https://leetcode.com/problems/split-linked-list-in-parts/description/
Given a (singly) linked list with head node root,
write a function to split the linked list into k consecutive linked
list "parts".
The length of each part should be as equal as possible:
no two parts should have a size differing by more than 1.
This may lead to some parts being null.
The parts should be in order of occurrence in the input list,
and parts occurring earlier should always have a size greater
than or equal parts occurring later.
Return a List of ListNode's representing the linked list parts that are formed.
Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ]
Example 1:
Input:
root = [1, 2, 3], k = 5
Output: [[1],[2],[3],[],[]]
Explanation:
The input and each element of the output are ListNodes, not arrays.
For example, the input root has root.val = 1, root.next.val = 2,
root.next.next.val = 3, and root.next.next.next = null.
The first element output[0] has output[0].val = 1, output[0].next = null.
The last element output[4] is null,
but it's string representation as a ListNode is [].
Example 2:
Input:
root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
Explanation:
The input has been split into consecutive parts with size difference at most 1,
and earlier parts are a larger size than the later parts.
"""
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def splitListToParts(self, root, k):
"""
:type root: ListNode
:type k: int
:rtype: List[ListNode]
idea:
max-min share idea but diff with only 1.
"""
if not root:
return [[]] * k
if not k:
return []
# O(n) count elements
cnt = 0
cnt_root = root
while cnt_root:
cnt += 1
cnt_root = cnt_root.next
base, rest = cnt / k, cnt % k
ret = []
tmp_root = root
while k:
k -= 1
tmp = []
for _ in range(base + (1 if rest > 0 else 0)):
tmp += tmp_root.val,
tmp_root = tmp_root.next
rest -= 1
ret += tmp,
return ret
def build():
return None, 3
l1 = ListNode(1)
l1.next = ListNode(2)
l1.next.next = ListNode(3)
l1.next.next.next = ListNode(4)
l1.next.next.next.next = ListNode(5)
l1.next.next.next.next.next = ListNode(6)
l1.next.next.next.next.next.next = ListNode(7)
l1.next.next.next.next.next.next.next = ListNode(8)
return l1, 13
if __name__ == "__main__":
s = Solution()
print(s.splitListToParts(*build()))
|
cc769df1892c353e1d8c1c37dff88da0aa6ee2c7 | Shikkic/exercism.io.python | /clock/clock.py | 2,172 | 3.796875 | 4 |
class Clock():
# Set initial Clock state
def __init__(self, hours, minutes):
timeDic = self.calculateMinutes(minutes)
self.minutes = timeDic['minutes']
self.hours = self.calculateHour(hours + timeDic['hours'])
self.time = self.generateTimeString()
# Add minutes to the clock (Can be positive or subtracting)
def add(self, numMinutes=0):
timeDic = self.calculateMinutes(self.minutes + numMinutes)
self.setMinutes(timeDic['minutes'])
hours = self.calculateHour(self.hours + timeDic['hours'])
self.setHours(hours)
self.time = self.generateTimeString()
return self.time
# Calculate Clock Hour in '24' from num of hours (Positive or Negative)
def calculateHour(self, numHours=0):
if numHours >= 0 and numHours < 24:
return numHours
hours = abs(numHours % 24)
return hours
# Caluclate Clock Minutes from num of minutes (Positive or Negative)
# returns a dict of hours and minutes
def calculateMinutes(self, numMinutes=0):
if numMinutes >= 0 and numMinutes < 60:
return { 'hours': 0, 'minutes': numMinutes }
hours = (numMinutes / 60)
minutes = (numMinutes % 60)
if minutes == 60:
minutes = 0
hours = hours + 1
return { 'hours': hours, 'minutes': minutes }
# Generates time string from hours and minutes
def generateTimeString(self):
hourDigit = str(self.hours)
if len(hourDigit) < 2:
hourDigit = '%d%s' % (0, hourDigit)
minuteDigit = str(self.minutes)
if len(minuteDigit) < 2:
minuteDigit = '%d%s' % (0, minuteDigit)
return '%s:%s' % (hourDigit, minuteDigit)
# ToString overide for instance
def __str__(self):
return self.time
# Equality overide for instance
def __eq__(self, other):
return self.time == other.time
# Setter for hours
def setHours(self, hours):
self.hours = hours
# Setter for minutes
def setMinutes(self, minutes):
self.minutes = minutes
|
ed9ad957887a9554453df41fd0fdb5f8148c30bc | pavelchavdarov/LoganStones | /src/LS_stone/__init__.py | 2,700 | 3.765625 | 4 |
class StoneSide:
__sides__ = {'Камень', 'Ножницы', 'Бумага'}
class CellCoordinates:
directions = [(0,1,-1), (1,0,-1), (1,-1,0), (0,-1,1), (-1,0,1), (-1,1,0)]
def cell_direction(self, dir):
return self.directions[dir]
def __init__(self, p_x, p_y, p_z):
if p_x + p_y + p_z == 0:
self.X = p_x
self.Y = p_y
self.Z = p_z
else:
self.X = self.Y = self.Z = 0
def __show__(self):
print("X=%s Y=%s Z=%s"%(self.X, self.Y, self.Z) )
def cell_set(self,p_x, p_y, p_z):
if p_x + p_y + p_z == 0:
self.X = p_x
self.Y = p_y
self.Z = p_z
def cell_add(self, hex, direction):
hex.X = hex.X + self.cell_direction(direction)[0] # X
hex.Y = hex.Y + self.cell_direction(direction)[1] # Y
hex.Z = hex.Z + self.cell_direction(direction)[2] # Z
return hex
def get_neighbours(self):
neighbours = set()
#neighbour = CellCoordinates
for i in range(len(self.directions)):
neighbour = self.cell_add(self, i)
print("neighbour[%s]=%s"%(i,neighbour))
neighbours.add(neighbour)
return neighbours
class Stone:
# 0 - side-1 = side_2, 1 - side-1 > side_2, 2 - sided_1 < side_2
def sides_retio(p_side_a, p_side_b):
if p_side_a == p_side_b:
return 0
elif p_side_a==0: # stone
if p_side_b==1: # scissors
return 1 # stone > scissors
elif p_side_b==2: # paper
return 2 # stone < paper
elif p_side_a==1: # scissors
if p_side_b==0: # stone
return 2 # scissors < stone
elif p_side_b==2: # paper
return 1 # scissors > paper
elif p_side_a==2: # paper
if p_side_b==0: # stone
return 1 # paper > stone
elif p_side_b==1: # scissors
return 2 # paper < scissors
sides_retio = staticmethod(sides_retio)
def __init__(self, p_side_a, p_side_b):
self.is_init = True
self.Side_A = p_side_a
self.Side_B = p_side_b
self.Current_Side = p_side_a
def flip_stone(self):
self.Current_Side = self.Side_B if self.Current_Side == self.Side_A else self.Side_A
def try_to_flip(self, force_side):
if Stone.sides_retio(force_side, self.Current_Side) == 1:
self.flip_stone()
|
1d529a3ee47d4aea9a744c1ae0b7e15936537baa | akhiln007/python-repo | /hello_you.py | 146 | 4.15625 | 4 | person=input("Enter your name:-")
print("Your name is:-",person,'!')
print("Your name is:-",person+'!')
print("Your name is:-",person,'!',sep='')
|
8e05bcbf3aaceec3ea04c2f8f0febb77371970c0 | addtheletters/laddersnakes | /linkedlists/singlylinkedlist.py | 668 | 3.5 | 4 | class ListNode:
def __init__(self, val, next=None):
self.val = val
self.next = next
def __str__(self):
return str(self.val) + ( (", " + str(self.next)) if self.next else "")
def __repr__(self):
return self.__str__()
# follows the links 'index' times
# returns a node further along in the list
def getAt(self, index):
place = self
for i in range(index):
place = place.next
if place == None:
return None
return place
def buildLinks(arr):
if len(arr) < 1:
return None
else:
return ListNode(arr[0], buildLinks(arr[1:]))
|
ce8cdba0cc1037514e391f65750865c7b1fbc43a | majauhar/SimpleBankingSystem-JetBrains | /banking.py | 5,092 | 3.5625 | 4 | # Author: Mohd Ali Jauhar
# IDE: PyCharm Edu
# Task: Jetbrains Academy project on Hyperskill
import random
import sqlite3
conn = None
conn = sqlite3.connect('card.s3db')
cur = conn.cursor()
def drop_table():
cur.execute("DROP TABLE card;")
conn.commit()
def create_table():
cur.execute('CREATE TABLE IF NOT EXISTS card ('
'id INTEGER,'
'number TEXT,'
'pin TEXT,'
'balance INTEGER DEFAULT 0);')
conn.commit()
# drop_table()
create_table()
def add_account(acc_num, acc_pin):
cur.execute("INSERT INTO card (number, pin) VALUES (?, ?)", (acc_num, acc_pin, ))
conn.commit()
def search_account(acc_num):
cur.execute("SELECT * FROM card WHERE (number = ?)", (acc_num, ))
output = cur.fetchall()
if len(output) == 0:
return True
return False
def add_income(amount, acc_num):
cur.execute("SELECT * FROM card WHERE (number = ?)", (acc_num, ))
balance = cur.fetchall()[0][3]
balance += amount
cur.execute("UPDATE card SET balance = ? WHERE (number = ?)", (balance, acc_num, ))
conn.commit()
def remove_income(amount, acc_num):
cur.execute("SELECT * FROM card WHERE (number = ?)", (acc_num, ))
balance = cur.fetchall()[0][3]
balance -= amount
cur.execute("UPDATE card SET balance = ? WHERE (number = ?)", (balance, acc_num, ))
conn.commit()
def delete_account(acc_num):
cur.execute("DELETE FROM card WHERE number = ?", (acc_num, ))
conn.commit()
def avail_balance(acc_num):
cur.execute("SELECT * FROM card WHERE (number = ?)", (acc_num, ))
balance = cur.fetchall()[0][3]
return balance
# --------------------------------------------------
def luhn_algorithm(account_num):
account_num = [int(x) for x in account_num]
sum = 0
for i in range(len(account_num)):
if i % 2 == 0:
account_num[i] *= 2
if account_num[i] > 9:
account_num[i] -= 9
sum += account_num[i]
if sum % 10 is 0:
return 0
return 10 - sum % 10
def new_account():
while True:
account_number = random.sample(range(10), 9)
account_number = '400000' + ''.join([str(x) for x in account_number])
check_sum = luhn_algorithm(account_number)
account_number += str(check_sum)
if (search_account(account_number)):
return account_number
def new_pin():
pin = random.sample(range(10), 4)
pin = ''.join([str(x) for x in pin])
return pin
def create_account():
card_number = new_account()
pin = new_pin()
# account_details[card_number] = pin
add_account(card_number, pin)
print('Your card number:', card_number, sep='\n')
print('Your card PIN:', pin, sep='\n')
def log_in(acc_num, acc_pin):
cur.execute("SELECT * FROM card WHERE number = ? AND pin = ?", (acc_num, acc_pin, ))
account = cur.fetchall()
conn.commit()
if len(account) == 0:
print('Wrong card number or PIN')
return
print('You have successfully logged in!')
while True:
option = int(input('''1. Balance
2. Add income
3. Do transfer
4. Close account
5. Log out
0. Exit\n'''))
if option is 1:
balance = avail_balance(acc_num)
print('Balance: {}'.format(balance))
if option is 2:
income = int(input('Enter income:\n'))
add_income(income, acc_num)
print('Income was added!')
if option is 3:
print('Transfer')
card_number = input('Enter card number:\n')
luhn_algo_last_digit = luhn_algorithm(card_number[0:15])
if (str(luhn_algo_last_digit) != card_number[15]):
print('Probably you made a mistake in the card number. Please try again!')
continue
if (search_account(card_number)):
print('Such a card does not exist.')
continue
if (acc_num == card_number):
print("You can't transfer money to the same account!")
continue
amount = int(input('Enter how much money you want to transfer:\n'))
avail_bal = avail_balance(acc_num)
if amount > avail_bal :
print('Not enough money!')
else:
add_income(amount, card_number)
remove_income(amount, acc_num)
print('Success!')
if option is 4:
delete_account(acc_num)
print('Your account has been closed!')
break
if option is 5:
print('You have successfully logged out!')
break
if option is 0:
print('Bye!')
exit()
return
# landing menu
while True:
option = int(input('''1. Create an account
2. Log into account
0. Exit\n'''))
if option is 1:
create_account()
if option is 2:
account_num = input('Enter your card number:\n')
pin = input('Enter your PIN:\n')
log_in(account_num, pin)
if option is 0:
print('Bye!')
exit()
|
6f3f54b13c86c54d5bdb9c8972d938fc79a17ea1 | LukeSlev/Database_Info_Retrieval | /src/Dev/Phase 3/yearGreater.py | 1,221 | 3.53125 | 4 | from bsddb3 import db
def yearSearch(Starting_Year):
DB_File = "ye.idx"
database = db.DB()
database.set_flags(db.DB_DUP) #declare duplicates allowed before you create the database
database.open(DB_File,None, db.DB_BTREE, db.DB_CREATE)
curs = database.cursor()
# while Starting_Year[0] == '0':
# Starting_Year = Starting_Year[1:]
# print('here', Starting_Year)
middleSet = set()
# print(str(int(Starting_Year)+1))
if (int(Starting_Year) < int(curs.first()[0].decode("utf-8"))): # too early
result = curs.set_range(curs.first()[0])
elif int(Starting_Year) < int(curs.last()[0].decode("utf-8")): # Proper Range
result = curs.set_range(str(int(Starting_Year)+1).encode("utf-8"))
else:
result = None # too late
# print("LUKE: ",result)
if(result != None):
while(result != None):
#print(result[1].decode('utf-8'))
middleSet.add(result[1].decode('utf-8'))
result = curs.next()
else:
print("No result was found")
return ()
curs.close()
database.close()
return middleSet
def main():
print(yearSearch(2018))
if __name__ == "__main__":
main()
|
b58080ee644ee1d446de4fd30974fa9783c50f58 | aaronkopplin/agar.io | /agario.py | 2,630 | 3.671875 | 4 | import pygame
import sys
import random
import time
import math
pygame.init()
class game():
def __init__(self):
self.colors = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
self.width = 1000
self.height = 1000
self.screen = pygame.display.set_mode((self.width, self.height))
self.num_points = 50
# game objects
self.points = []
self.players = []
#create points game object
self.spawn_players()
self.spawn_points()
# last step
self.run()
def spawn_players(self):
self.players.append(player())
def spawn_points(self):
for i in range(self.num_points):
self.points.append(self.new_random_point())
def add_points(self):
if len(self.points) < self.num_points:
self.points.append(self.new_random_point())
def new_random_point(self):
x = random.randint(0, self.width)
y = random.randint(0, self.height)
c = random.randint(0, len(self.colors)-1)
return point(x, y, self.colors[c])
def draw(self, color, x, y, r):
pygame.draw.circle(self.screen, color, (int(x), int(y)), r)
def draw_objects(self):
for p in self.points:
self.draw(p.color, p.x, p.y, p.r)
for p in self.players:
self.draw(p.color, p.x, p.y, p.r)
def update_players(self):
for p in self.players:
p.update()
def handle_collisions(self):
for p in reversed(self.players):
for b in reversed(self.points):
distance = math.sqrt(pow((b.x - p.x), 2) + pow((b.y - p.y), 2))
if distance < p.r + b.r:
p.increase_size()
self.points.remove(b)
def run(self):
frame = time.time()
running = True
while running:
next_frame = time.time()
if next_frame - frame > 1.0/60.0:
frame = time.time()
self.screen.fill((100, 100, 100))
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
print("left")
if event.type == pygame.QUIT:
pygame.quit()
sys.exit(0)
self.add_points()
self.handle_collisions()
self.draw_objects()
self.update_players()
pygame.display.update()
class player():
def __init__(self, x=50, y=50):
self.r = 10
self.x = x
self.y = y
self.color = (255, 255, 255)
self.speed = 1
self.easing = .01
self.growth_factor = 1
def update(self):
mouse_coordinate = pygame.mouse.get_pos()
target_x = mouse_coordinate[0]
dx = target_x - self.x
self.x += (dx * self.easing)
target_y = mouse_coordinate[1]
dy = target_y - self.y
self.y += (dy * self.easing)
def increase_size(self):
print(self.r)
self.r += 1
class point():
def __init__(self, x, y, color):
self.r = 5
self.x = x
self.y = y
self.color = color
game = game() |
291ac8f23997788d948150cd1eb1a35e9e692f7b | iskislamov/kyapr | /linq/linq.py | 1,697 | 3.734375 | 4 | def generateFibonacci():
first = 1
second = 1
while True:
second += first
first = second - first
yield second
class Range:
def __init__(self, provider):
self.provider = provider
def Select(self, foo):
return Range([foo(x) for x in self.provider()])
def Flatten(self):
return Range([y for x in self.provider for y in x])
def Where(self, predicate):
return Range(filter(predicate, self.provider))
def Take(self, count):
return Range(self.generate(count))
def generate(self, count):
iteration = 0
for x in self.provider:
if iteration == count:
break
iteration += 1
yield x
def OrderBy(self, foo):
return Range(sorted(self.provider, key=foo))
def GroupBy(self, foo):
d = {}
for elem in self.provider():
if foo(elem) not in d:
d[foo(elem)] = []
d[foo(elem)].append(elem)
def generator():
for key, elems in d.items():
yield key, elems
return Range(generator)
def ToList(self):
return list(self.provider)
print((Range(generateFibonacci())
.Where(lambda x: x % 3 == 0))
.Take(5)
.ToList())
with open("somepoem.txt", "r") as input:
def generator():
for line in input:
words = [word for word in line.strip().split(' ') if word]
for word in words:
yield word
print(Range(generator)
.GroupBy(lambda x: x)
.Select(lambda x: (len(x[1]), x[0]))
.OrderBy(lambda x: x[0])
.ToList()) |
acc5707766dcefcde3630e6ca7de8e421081baa9 | JneWalter25/-Generating-Randomness | /test5.py | 2,966 | 3.65625 | 4 | class GenerateRandomness:
def __init__(self):
self.number = ''
self.profile = {"000": [0, 0], "001": [0, 0], "010": [0, 0], "011": [0, 0],
"100": [0, 0], "101": [0, 0], "110": [0, 0], "111": [0, 0]}
self.money = 1000
def get_number(self):
print(f"The current data length is {len(self.number)}, {100 - len(self.number)} symbols left")
data = input('Print a random string containing 0 or 1:\n\n')
for x in data:
if x == '0' or x == '1':
self.number += x
if len(self.number) < 100:
self.get_number()
else:
self.generate_profile()
def generate_profile(self):
for y in range(len(self.number)):
try:
self.number[y + 3]
except IndexError:
break
else:
if self.number[y + 3] == "0":
self.profile[self.number[y:y + 3]][0] += 1
elif self.number[y + 3] == "1":
self.profile[self.number[y:y + 3]][1] += 1
print(f"\nFinal data string:\n{self.number}\n")
print("")
print("You have $1000. Every time the system successfully predicts your next press, you lose $1.")
print('Otherwise, you earn $1. Print "enough" to leave the game.' + "Let's go!")
print("")
def prediction(self):
self.get_number()
while True:
try:
test_string = input("Print a random string containing 0 or 1:\n\n")
if test_string == "enough":
return False
prediction_string = test_string[:3]
total = len(test_string) - 3
for number in range(total):
triad = test_string[number:number + 3]
prediction_string += '0' if self.profile[triad][0] >= self.profile[triad][1] else '1'
correct = 0
for x in range(total):
if prediction_string[x] == test_string[x]:
correct += 1
print(f"prediction:\n{prediction_string}\n")
print("Computer guessed right {} out of {} symbols ({:.2f} %)".format(correct,
total,
correct / total * 100))
self.game(correct,total)
except:
pass
def game(self,correct,total):
incorrect = total-correct
if correct > 0:
self.money +=incorrect-correct
else:
self.money +=incorrect-correct
print(f"Your capital is now ${self.money}")
print("Please give AI some data to learn...")
GenerateRandomness().prediction()
print("Game over!")
|
8f4f4fee4dbda17e5f75c4c741067bb99cb9cfbe | kmark1625/Project-Euler | /p30.py | 786 | 3.90625 | 4 | def main():
return sum_of_nth_sum(5)
def sum_of_nth_sum(n):
sum = 0
for i in range(1, 1000000):
if is_valid_nth_sum(i, n):
sum += i
return sum
def is_valid_nth_sum(num, n):
string_num = str(num)
if len(string_num) == 1:
return False
sum = 0
for d in string_num:
sum += int(d)**n
if sum == num:
return True
else:
return False
def test_is_valid_nth_sum():
assert is_valid_nth_sum(1634, 4) == True
assert is_valid_nth_sum(8208, 4) == True
assert is_valid_nth_sum(9474, 4) == True
assert is_valid_nth_sum(1, 4) == False
assert is_valid_nth_sum(9248, 4) == False
def test_sum_of_nth_sum():
assert sum_of_nth_sum(4) == 19316
def test():
test_is_valid_nth_sum()
test_sum_of_nth_sum()
if __name__ == '__main__':
print main() |
efd693c13e784427880f1388038716d7da8474c6 | algharrash/saudidevorg | /day007.py | 855 | 3.625 | 4 | #python string
my_name = 'Ali AlGharrash'
long_text = """Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse. The Python interpreter and the extensive standard library are available in source or binary form without charge for all major platforms, and can be freely distributed."""
print("printng sub-string from string varibale")
print(my_name[0:3])
print(long_text) |
79f1fa60dcc97e3ec1cab1f936aff537da20f3b2 | morbrian/carnd-alf | /binary_thresholds.py | 5,902 | 3.890625 | 4 |
import numpy as np
import cv2
def abs_sobel_threshold(image, orient='x', sobel_kernel=3, thresh=(0, 255)):
"""
Apply sobel threshhold to image.
Reference: Udacity Advanced Lane Finding - (21) Applying Sobel
:param image: input image
:param orient: orientation axis (x or y)
:param sobel_kernel: kernel size to use, should be odd number
:param thresh: pixel intensity threshhold
:return: binary threshholded image
"""
# 1) Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 2) Take the derivative in x or y given orient = 'x' or 'y'
a = 1 if orient == 'x' else 0
b = 1 if orient == 'y' else 0
sobel = cv2.Sobel(gray, cv2.CV_64F, a, b, ksize=sobel_kernel)
# 3) Take the absolute value of the derivative or gradient
abs_sobel = np.absolute(sobel)
# 4) Scale to 8-bit (0 - 255) then convert to type = np.uint8
scaled_sobel = np.uint8(255*abs_sobel/np.max(abs_sobel))
# 5) Create a mask of 1's where the scalsqed gradient magnitude
# is > thresh_min and < thresh_max
sbinary = np.zeros_like(scaled_sobel)
sbinary[(scaled_sobel >= thresh[0]) & (scaled_sobel <= thresh[1])] = 1
# 6) Return this mask as your binary_output image
return sbinary
def magnitude_threshold(image, sobel_kernel=3, thresh=(0, 255)):
"""
Apply magnitude threshhold to image.
Reference: Udacity Advanced Lane Finding - (22) Magnitude of the Gradient
:param image: input image
:param sobel_kernel: kernel size (should be odd)
:param thresh: intensity threshhold
:return: binary output image based on gradient magnitude
"""
# 1) Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 2) Take the gradient in x and y separately
abs_sobelx = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel))
abs_sobely = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel))
# 3) Calculate the magnitude
abs_sobelxy = np.sqrt(abs_sobelx * abs_sobelx + abs_sobely * abs_sobely)
# 4) Scale to 8-bit (0 - 255) and convert to type = np.uint8
# scaled_sobelxy = np.uint8(255*abs_sobelxy/np.max(abs_sobelxy))
scale_factor = np.max(abs_sobelxy)/255
scaled_sobelxy = (abs_sobelxy/scale_factor).astype(np.uint8)
# 5) Create a binary mask where mag thresholds are met
binary_output = np.zeros_like(scaled_sobelxy)
binary_output[(scaled_sobelxy >= thresh[0]) & (scaled_sobelxy <= thresh[1])] = 1
# 6) Return this mask as your binary_output image
return binary_output
def direction_threshold(image, sobel_kernel=3, thresh=(0, np.pi/2)):
"""
Apply direction of the gradient to image.
Reference: Udacity Advanced Lane Finding - (23) Direction of the Gradient
:param img: input image
:param sobel_kernel: kernel size (should be odd)
:param thresh: arctan2 range
:return: binary image after direction threshold applied
"""
# 1) Convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 2) Take the gradient in x and y separately
# 3) Take the absolute value of the x and y gradients
abs_sobelx = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=sobel_kernel))
abs_sobely = np.absolute(cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=sobel_kernel))
# 4) Use np.arctan2(abs_sobely, abs_sobelx) to calculate the direction of the gradient
grad_dir = np.arctan2(abs_sobely, abs_sobelx)
# 5) Create a binary mask where direction thresholds are met
binary_output = np.zeros_like(grad_dir)
binary_output[(grad_dir >= thresh[0]) & (grad_dir <= thresh[1])] = 1
# 6) Return this mask as your binary_output image
# binary_output = np.copy(img) # Remove this line
return binary_output
def color_binary(image, thresh=(170, 255)):
"""
use saturation color channel to identify likely lane lines
:param image: corrected image
:param thresh: color threshold
:return: binary image based on saturation
"""
# Convert to HLS color space and separate the S channel
# Note: img is the undistorted image
hls = cv2.cvtColor(image, cv2.COLOR_RGB2HLS)
s_channel = hls[:, :, 2]
s_binary = np.zeros_like(s_channel)
s_binary[(s_channel >= thresh[0]) & (s_channel <= thresh[1])] = 1
return s_binary
def combined_binary(image, gradx_kernel=3, grady_kernel=3, mag_kernel=3, dir_kernel=3,
gradx_thresh=(0, 255), grady_thresh=(0, 255), mag_thresh=(30, 100), dir_thresh=(0.7, 1.3),
color_thresh=(100, 210)):
"""
use combination of all binary lane line identification methods to give best guess of lanes
:param image: corrected image
:param gradx_kernel: gradient kernel in x direction sobel
:param grady_kernel: gradient kernel in y direction sobel
:param mag_kernel: magnitude kernel
:param dir_kernel: direction kernel
:param gradx_thresh: pixel threshold for gradient on x sobel
:param grady_thresh: pixel threshold for gradient on y sobel
:param mag_thresh: threshold for magnitude
:param dir_thresh: threshold for direction
:param color_thresh: saturation threshold
:return: combined result of all binary approaches
"""
# Apply each of the thresholding functions
gradx = abs_sobel_threshold(image, orient='x', sobel_kernel=gradx_kernel, thresh=gradx_thresh)
grady = abs_sobel_threshold(image, orient='y', sobel_kernel=grady_kernel, thresh=grady_thresh)
magnitude_bin = magnitude_threshold(image, sobel_kernel=mag_kernel, thresh=mag_thresh)
direction_bin = direction_threshold(image, sobel_kernel=dir_kernel, thresh=dir_thresh)
color_bin = color_binary(image, color_thresh)
combined = np.zeros_like(direction_bin)
combined[((gradx == 1) & (grady == 1) & (color_bin == 1)) | ((magnitude_bin == 1) & (direction_bin == 1))] = 1
return combined
|
f53e8f184ba51b32db58af68e7423b7b41bef3b7 | shuchangFrances/machinelearning | /normalization.py | 859 | 3.5 | 4 | """标准化normalization数据"""
from sklearn import preprocessing
import numpy as np
from sklearn.cross_validation import train_test_split
from sklearn.datasets.samples_generator import make_classification
from sklearn.svm import SVC
import matplotlib.pyplot as plt
'''a=np.array([[10,2.7,3.6],
[-100,5,-2],
[120,20,40]],dtype=np.float64)
print(a)
print(preprocessing.scale(a))#标准化数据'''
X,y=make_classification(n_samples=300,n_features=2,n_redundant=0,
n_informative=2,random_state=22,n_clusters_per_class=1,scale=100)
#300个data 2个属性 相关系的属性2个 随机的22个都一样
#plt.scatter(X[:,0],X[:,1],c=y)
#plt.show()
X=preprocessing.scale(X)
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=.3)
clf=SVC()
clf.fit(X_train,y_train)
print(clf.score(X_test,y_test))
|
7cf8b42e0181c646c797ea2dc5b9749aba02f7db | slottwo/rpg-dpc | /gui/__init__.py | 558 | 3.75 | 4 | from reader import dice_reader, sum_reader
from calculator import probability, probability_range
def one_sum_probability():
n, f, m = dice_reader()
s = sum_reader()
print(f"The probability of the sum {s} occurring in rolling of {n}d{f}{'+' if m > 0 else ''}{m if m != 0 else ''} "
f"is around {round(probability(n, f, s, m)*100, 2)}%")
def all_sums_probabilities():
n, f, m = dice_reader()
print("SUM : Probability")
for s, p in probability_range(n, f, modifier=m).items():
print(f"{s} : {round(p * 100, 3)}%")
|
26a3a546e2a8edfb85854cf0a5ac88babf666f54 | mnkhann/PythonBasic | /basic.py | 2,919 | 4.28125 | 4 | #3 types string
a = 'Hello python'
print(a)
b = "Hello python"
print(b)
c = """ Hello student's, "how are you"? """
print(c)
#Numbers in python
e = 345
print(e)
print(type(e))
f = 3.55
print(f)
print(type(f))
g = 555555555666666 #long datatype for python v2 not v3
print(g)
print(type(g))
h = 8 + 7j
print(h)
print(type(h))
print(h.real, "real part")
print(h.imag, "imaginary part")
x = 28
print(float(x))
y = 5.667
print(int(y))
#ints are narrower than floats
#floats are wider than ints
print(complex(y + 0j)) #j = sqrt(-1)
#float to complex but vice versa is not possible
#floats are narrower than complex numbers and complex numbers are wider than floats
ab = 4
ac = 5.7
cd = 12 + 8j
#Rule: Widen numbers so they'r the same types
#add
print(ab + ac) #int+float
#sub
print(ac - ab) #float-int
#mul
print(ac * cd) #float * complex
#Div
print(cd / ac) #complex/float
print(16/5) #return float
print(16 // 5) #return only integer part(quotient)
print(16 % 5) #return remainder
#print(2/0) #undefined
print(dir()) #short for "directory" - this contains collection of common objects which are always available
print(__builtins__)
#use of help
#print(help(pow))
print(pow(4, 2))
print(4 ** 2) #double asterisk works for power
#hex(number) -> string (hexadecimal representation of the number"
print(hex(10)) #hexadecimal in python begins with 0x
print(0xa) #it prints the decimal number (hex -> dec)
import math
print(dir(math))
print(help(math.radians))
print(math.radians(180))
print(type(True))
print(type(False))
t = 4
s = 6
print(t == s) #it will return boolean result
print(t != s) #it will return boolean result
#in python 0 is converted to false other numbers are ture
print(bool(20))
print(bool(0))
#for boolean not empty string will return true and empty will false
print(bool("Hello"))
print(bool(""))
print(bool(" ")) #this string contains space so this is not empty
#boolean to string, the string has quotes boolean does not
print(str(True))
print(str(False))
#boolean to integer
print(int(True))
print(int(False))
print(67 + True)
print(67 + False)
print(3 * False)
import datetime
#print(help(datetime))
ft = datetime.date(1952, 2, 21)
print(ft) #can access the year month day seperately
print(ft.day)
dt = datetime.timedelta(100)
print(ft + dt)
ct = datetime.timedelta(-365)
print(ft + ct)
#Day name, month name, day, year
print(ft.strftime("%A, %B %d, %Y"))
launch_date = datetime.date(2017, 1, 15) #y, m, d
launch_time = datetime.time(12, 15, 5) #h, m, s
launch_datetime = datetime.datetime(2017, 1, 15, 12, 15, 5)
print(launch_date)
print(launch_time)
print(launch_datetime)
now = datetime.datetime.today()
print(now)
print(now.microsecond)
moon_landing = "7/20/1969"
moon_landing_datetime = datetime.datetime.strptime(moon_landing, "%m/%d/%Y")
print(moon_landing_datetime)
print(type(moon_landing_datetime))
print(datetime.timedelta(8, 9, 5, 6, 7, 2))
|
1e42d50d994919f7c52d1693b7a626ab199f1f98 | qdonnellan/projecteuler | /python/problems/problems_01_25/problem_02.py | 1,116 | 3.921875 | 4 | class Problem02:
"""
find the sum of all even terms in the Fibonacci series where
the largest term is less than some limit
"""
limit = 3
fibonacci_series = []
even_terms = []
solution = None
def solve_problem(self):
self.construct_fibonacci_series_less_than_limit()
self.construct_series_of_even_terms()
self.solution = sum(self.even_terms)
def construct_fibonacci_series_less_than_limit(self):
seed_terms = [1, 2]
self.fibonacci_series.extend(seed_terms)
while not self.next_term_exceeds_limit():
self.fibonacci_series.append(self.next_term_in_series())
def construct_series_of_even_terms(self):
self.even_terms = [x for x in self.fibonacci_series if x % 2 == 0]
def next_term_exceeds_limit(self):
if self.next_term_in_series() > self.limit:
return True
else:
return False
def next_term_in_series(self):
last_term = self.fibonacci_series[-1]
next_to_last_term = self.fibonacci_series[-2]
return last_term + next_to_last_term
|
530a867ac6149e50cb42e0183660311abf58b58d | happyquokkka/TIL_Python | /common_education/06. While/while_ex3.py | 1,232 | 3.859375 | 4 | # while_ex3.py
# 사용자에게 숫자(정수)를 입력받아
# 홀수이면 '숫자는 홀 수 입니다.' 출력
# 짝수이면 출력 없이 다음 입력을 받는 프로그램을 작성.
# 종료는 입력에 x 문자가 들어오면 종료하되 break문 활용
# 짝수일 경우 출력 건너뜀은 continue 문 활용
num = input('숫자(정수)만 입력하세요. 종료를 원하면 x를 입력하세요 : ')
while int(num) % 2 != 0 :
print('%d는 홀 수 입니다.' % int(num))
break
if int(num) % 2 == 0 :
continue
elif num == "x" :
break
print('종료합니다')
# num = input('숫자(정수)만 입력하세요. 종료를 원하면 x를 입력하세요 : ')
# while num % 2 != 0 :
# print('%d는 홀 수 입니다.' % num)
# if num % 2 == 0 :
# continue
# print(num)
# elif num == "x" :
# break
# print('종료합니다')
# 선생님 풀이
#
# while True :
# s = input('숫자(정수)만 입력하세요. 종료를 원하면 x를 입력하세요 : ')
# if s == 'x' :
# print('종료합니다.')
# break
# if int(s) % 2 == 0 :
# continue
#
# print(s + '는 홀수입니다.')
|
3da982c7fe1f65e36061824bf594ce2b491a9da8 | Jrice170/Chaos-Simulation | /Chaos_pi.py | 3,907 | 4.1875 | 4 | ## Joseph Rice 10/23/2017
## Cs 177
"""This code it going to randamly generate dots on to a graphics window.
The code below will do a calulation for random dots.
This code will allso show the calculation for the percentage that hit the circle.
first import the random modual 'from random import *'
next import the graphics modual. 'from graphics import *
import math
1. input the number of dots generated
2. outputs generate the graphic picture of what is happening
"""
from random import *
from math import *
from graphics import *
## function for the whole background the the graphical picture
win = GraphWin("Pi Simulation",900,700)
win.setBackground("purple")
center = Point(0,0)
##Corrds
win.setCoords(10,-10,-10,10)
##for the rectange
rect = Rectangle(Point(-4,-4),Point(4,4))
rect.setOutline("black")
rect.setFill("white")
rect.setWidth(1)
rect.draw(win)
Display_text = Text(Point(2,-6),"Enter Total Number of dots. ")
Display_text.draw(win)
dis = Entry(Point(-2,-6),3)
dis.getText
dis.draw(win)
## this draws the simulated circle
cir = Circle(center,4)
cir.setOutline("red")
cir.setWidth(3)
cir.setFill("black")
cir.draw(win)
enter_box = Rectangle(Point(-1,1),Point(1,-1))
enter_box.move(-5,-5)
enter_box.move(0,-1)
Word_enter = Text(Point(-5,-6),"Enter")
Word_enter.draw(win)
enter_box.draw(win)
## tells user how to end program
Kill_while = Text(Point(1,-8),"To kill while Loop <ENTER> interger 0")
Kill_while.draw(win)
### draws each individual point
### this function draws all of the objects
## number_dots = eval(input("enter the number of dots: "))
## n = 1 ## range stops before the number you put in>>>
## Total_darts = n + number_dots
## hits = 0
### TAKE NOTE** I ADDED A WHILE LOOP TO MAKE MY PROGRAM MORE USER Friendly
## What THE WHILE LOOP DOES:: WILL Continue RUNING AS LONG AS THE USER DOES NOT ENTER A LETTER
##win.getMouse()
## while state does not have a string in it will continue running
## loop will run while* the input does not equal zero.
while True:
win.getMouse()
try:
number_dots = eval(dis.getText())
except SyntaxError:
Text(Point(4,-7),"The end!").draw(win)
break
##
## range stops before the number you put in>>>
Total_darts = 1 + number_dots
hits = 0
#state = input("Hit Enter to quit")
## I Without THE IF STATEMENT THE LOOP Would BE INFINITE.
if number_dots == 0:
break
#### This for loop WILL LOOP HOW MANY TIMES THE USER INPUTS FOR TOTAL_DARTS
for i in range(0,Total_darts):
####
x = random()*8 - 4
####
y = random()*8 - 4
in_circle = x**2 + y**2
if in_circle <=16:
p = Point(x,y)
blue = "red"
p.draw(win)
p.setFill(blue)
else:
p = Point(x,y)
red = "blue"
p.draw(win)
p.setFill(red)
if in_circle <= 16:
hits += 1
## calculations
pi_experment = 4 *(hits/Total_darts)
p_error = (pi_experment - pi)/pi
ave = hits/Total_darts
dis_play = Text(Point(5,6)," ")
dis_play_2 = Text(Point(5,5)," ")
play = Entry(Point(0,6),7)
play_2 = Entry(Point(0,5),7)
play.draw(win)
play_2.draw(win)
dis_play.setText("Percent That hit the circle:")
dis_play_2.setText("percent error for pi " + "~")
play.setText(str(round(ave*100,2)) + "%")
play_2.setText(str(round(abs(p_error),3)))
dis_play.draw(win)
dis_play_2.draw(win)
try:
win.close()
except TypeError:
Text(Point(4,-9),"THE STORM HAS PASSED !!!!!!").draw(win)
|
2d03be0cf0bca0f04fc2398404ad2c336473eb9b | antillgrp/Maryville-University-Online-Master-s-in-Software-Development | /SWDV-600-Intro-to-Programming/Week-6-Using-Classes,-Objects,-and-Collections/unique_list.py | 693 | 4 | 4 | class ListUniqueClassifier:
def __init__(self):
self.list = []
def isUnique(self):
# set --> Builds an unordered collection of unique elements.
return len(set(self.list)) == len(self.list)
if __name__ == '__main__':
listUniqueClassifier = ListUniqueClassifier()
print("This program tests if the sequence of positive numbers you input are unique\nEnter -1 to quit")
nextInt = int(input("First: "))
while nextInt >= 0:
listUniqueClassifier.list.append(nextInt)
nextInt = int(input("Next: "))
print("The sequence {} is {}".format(listUniqueClassifier.list, "unique!" if listUniqueClassifier.isUnique() else "NOT unique!"))
|
3ef296cd38f33d62c7f4a21c4b629129ceeeb1cf | sachindusahan/Tic_tac_toe | /result.py | 573 | 3.671875 | 4 | lines = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6]
]
def result(user, computer, checks):
for line in lines:
count1 = 0
count2 = 0
for i in range(3):
if checks[line[i]] == user:
count1 += 1
if checks[line[i]] == computer:
count2 += 1
if count1 == 3:
return "You won"
elif count2 == 3:
return "You loss"
elif " " not in checks:
return "Draw"
|
ef895f0144f0be711180aad36569cfbbcbf2b446 | madelinepet/data-structures-and-algorithms | /challenges/find_max_value/find_max_value.py | 6,814 | 4.1875 | 4 | class Node(object):
def __init__(self, value, data=None, left=None, right=None):
""" Instantiates the first Node
"""
self.value = value
self.data = data
self.left = left
self.right = right
def __str__(self):
""" Returns a string
"""
return f'{self.value}'
def __repr__(self):
""" Returns a more highly formatted string
"""
return f' <Node | Value: {self.value} | Data: {self.data} | Left: {self.left} | Right: {self.right} >'
class BinaryTree:
def __init__(self, iterable=None):
""" Instatiates the first BinaryTree
"""
self.root = None
if iterable:
for i in iterable:
self.insert(i)
def __str__(self):
""" String representation of the BinaryTree
"""
return f'{self.value}'
def __repr__(self):
""" Technical representation of the BinaryTree
"""
return f' <Node | Value: {self.root.value} | Root : {self.root}>'
def insert(self, val):
""" Given root node, go left or right, get to child, go left, right or
insert? Does not need to be self balancing.
"""
new_node = Node(val)
if self.root is None:
self.root = new_node
return
current = self.root
while True:
if val == current.value:
raise ValueError('Value is already in the tree')
if val > current.value:
if current.right is None:
current.right = new_node
return False
else:
current = current.right
if val < current.value:
if current.left is None:
current.left = new_node
return False
else:
current = current.left
def in_order(self, callable=lambda node: print(node)):
""" Go left, visit, go right.
"""
def _walk(node=None):
""" recursion! Function calls itself. The recursion needs to know
when to stop. The return here acts at the base case when the node
is None
"""
if node is None:
return
# go left
if node.left is not None:
_walk(node.left)
# visit, runs lambda and prints the node
callable(node)
# go right
if node.right is not None:
_walk(node.right)
# call walk for the first time and pass in the root
_walk(self.root)
def pre_order(self, callable=lambda node: print(node)):
""" Visit, go left, go right
"""
def _walk(node=None):
""" recursion! Function calls itself. The recursion needs to know
when to stop. The return here acts at the base case when the node
is None
"""
if node is None:
return
# visit, runs lambda and prints the node
callable(node)
# go left
if node.left is not None:
_walk(node.left)
# go right
if node.right is not None:
_walk(node.right)
# call walk for the first time and pass in the root
_walk(self.root)
def post_order(self, callable=lambda node: print(node)):
""" Go left, go right, visit
"""
def _walk(node=None):
""" recursion! Function calls itself. The recursion needs to know
when to stop. The return here acts at the base case when the
node is None
"""
if node is None:
return
# go left
if node.left is not None:
_walk(node.left)
# go right
if node.right is not None:
_walk(node.right)
# visit, runs lambda and prints the node
callable(node)
# call walk for the first time and pass in the root
_walk(self.root)
class Queue(object):
""" This creates a queue class with methods below
"""
def __init__(self, potential_iterable=None):
""" Initializes fn, defines datatype as always a node, = "type annotation"
"""
self.queue = list()
self.front = None
self.back = None
self._length: int = 0
def __str__(self):
""" Returns a string of the top and the length
"""
return f'{self.front} | {self.back}| {self._length}'
def __repr__(self):
""" Returns a formatted string of the top and the length of the queue
"""
return f'<Queue | Front: {self.front} | Back: {self.back}| Length : {self._length}>'
def __len__(self):
""" Returns the length of the queue
"""
return self._length
def enqueue(self, potential_iterable):
"""Takes in an iterable and creates new nodes in the queue's end
"""
try:
for i in potential_iterable:
if i not in self.queue:
self.queue.insert(0, i)
potential_iterable[0] = self.front
potential_iterable[-1] = self.back
self._length += 1
return True
else:
return False
except TypeError:
if not len(self.queue):
self._length += 1
self.front = potential_iterable
self.back = potential_iterable
self.queue.insert(0, potential_iterable)
else:
self._length += 1
self.back = potential_iterable
self.queue.insert(0, potential_iterable)
def dequeue(self):
if len(self.queue) > 0:
self._length -= 1
self.front = self.queue[-1]
return self.queue.pop()
return('No items in queue!')
def find_max_value(bt):
""" Function that takes in a tree and returns the max value
"""
breadth = Queue()
output = []
breadth.enqueue(bt.root)
maximum = bt.root.value
if not bt.root:
return('Your bt was empty!')
while breadth._length > 0:
if breadth.front and breadth.front.left:
breadth.enqueue(breadth.front.left)
if breadth.front and breadth.front.right:
breadth.enqueue(breadth.front.right)
try:
output.append(breadth.dequeue().value)
except Exception:
pass
for i in output:
if i > maximum:
maximum = i
return maximum
|
36804adc7ad61c4413ee0e55b2cdf7d5c0a5d57f | swapnilbabladkar/python_sourceCode | /PythonSourceCodes/Day3/FrequencyOfVowels.py | 258 | 4.09375 | 4 | # Take a string from user.
# Count the occurrences of each vowel in the string.
# A : 1
# E : 3 & so on
vsent = raw_input('Enter a string:')
vwls = ['a','e','i','o','u']
cnt=[]
for item in vwls:
print item, ' : ', vsent.lower().count(item)
|
6fe0e8d77f3667323eb5dc7170d0ac8373efb32b | Suspious/-forever-young- | /lancering.py | 144 | 3.5625 | 4 | import time
print("we gaan opstijgen over ")
x = range(31,0,-1)
for n in x:
time.sleep(1)
print(n)
print("en we gaan opstijgen!!!!!")
|
3a3c97b20a52d00b4d62dbba28e39cfb6234351b | olga3n/adventofcode | /2018/01-chronal-calibration-1.py | 838 | 3.640625 | 4 | #!/usr/bin/env python3
import sys
import re
import functools
import unittest
def calc(data):
lst = re.compile(r'[\s\n,]+').split(data)
result = functools.reduce(
lambda x, y:
x + (int(y[1:]) if y[0] == '+' else - int(y[1:])),
lst, 0)
return result
class TestMethods(unittest.TestCase):
def test_0(self):
data = "+1, -2, +3, +1"
self.assertEqual(calc(data), 3)
def test_1(self):
data = "+1, +1, +1"
self.assertEqual(calc(data), 3)
def test_2(self):
data = "+1, +1, -2"
self.assertEqual(calc(data), 0)
def test_3(self):
data = "-1, -2, -3"
self.assertEqual(calc(data), -6)
if __name__ == '__main__':
data = sys.stdin.readlines()
data = ''.join(data).rstrip()
v = calc(data)
print(v)
|
b7697dc4d444b4c12a2b9e5eac0acd6a88b95770 | sidneyalex/Desafios-do-Curso | /Desafio058.py | 897 | 4.09375 | 4 | #Melhore o jogo do Desafio028 onde o computador vai "pensar" em um numero entre 0 e 10. Só que agr o jogador vai tentar advinhar até acertar, mostrando no final quantos palpites foram necessarios para vencer.
from emoji import emojize
from random import randrange
tentativas = 1
ale = randrange(0,11)
print('{}\n|| Jogo de ADIVINHAÇÃO ||\n{}\n'.format('='*25, '='*25))
print('Sou seu computador... Acabei de pensar em um número entre 0 e 10.\nSera que você consegue adivinhar qual foi?')
num = int(input('Qual é o seu palpite? '))
while num != ale:
tentativas += 1
if ale > num:
print('Mais... Tente outro numero: ', end='')
else:
print('Menos... Tente outro numero: ', end='')
num = int(input())
print('\nApós {} tentativas:'.format(tentativas))
print(emojize(':tada: Parabéns você GANHOU com {} tentativas :tada:'.format(tentativas), use_aliases=True))
|
fce28e0802d5312604c87b7911157eef121586ef | Victorletzelter/pattern_detection | /Python_project/Hand_labeling.py | 13,846 | 3.546875 | 4 | #This file allows to perform hand-labeling of the ZF intervals, in order to adjust hyperparameters of the Event_labeling.py file.
#Provided that the variable zi was created or initialized, the user can execute the function learning(), to label by hand the ZF intervals.
#If not, the file exec(open("/Users/victorletzelter/Desktop/Projet_python/samplezi.txt").read()) can be executed first.
#The process to adopt for hand-labeling is precised in the learning() function.
#Loading of the data
data1=pd.read_csv("/Users/victorletzelter/Documents/GitHub/pattern_detection/Python project/Data_files/converted_data1.txt",delimiter=' ')
data2=pd.read_csv("/Users/victorletzelter/Documents/GitHub/pattern_detection/Python project/Data_files/converted_data2.txt",delimiter=' ')
def split(dat,x1,x2) : #This function splits the data frame
l=len(dat)
dat1=dat.tail(l-int(x1))
dat1=dat1.head(int(x2-x1))
return(dat1)
def onclick(event): #For a point to be considered, the user will have to double-click on it
if event.dblclick :
zi.append((event.xdata,event.ydata))
def learning(data1,data2) : #This function allows to label by hand data, by clicking on the temporal time series. The relevant values are then stored in a variable called 'zi'
#When labelling the data, the user has to proceed, if possible, in the order : for the Data1 : select a point just before the peak, at the
#extremum of the peak, and just after the peak.
#For the Data2 : select proceed in the same way.
#If a point is selected by mistake, the traitement function will filter it automatically. The corresponding 6-uplet just has to be selected again.
Dt=split(data1,X1,X2)
D2t=split(data2,X1,X2)
def smooth(D,D2,x1,x2) : #This function allows to smooth the signal using savgol_filter
S_1=savgol_filter(D['Potential(V)'],int(len(D)/10)+1, 2)
S_2=savgol_filter(D2['Potential(V)'],int(len(D2)/10)+1, 2)
D_s=pd.DataFrame.copy(D)
D2_s=pd.DataFrame.copy(D2)
for i in range (x1,x2) :
D_s['Potential(V)'][i]=S_1[i-x1]
D2_s['Potential(V)'][i]=S_2[i-x1]
for i in range (x1,x2) :
D['Potential(V)'][i]=D['Potential(V)'][i]-D_s['Potential(V)'][i]
D2['Potential(V)'][i]=D2['Potential(V)'][i]-D2_s['Potential(V)'][i]
return((D,D2))
Da=smooth(Dt,D2t,X1,X2)
D=Da[0]
D2=Da[1]
t=Correlation_s(D,D2,seuil_opt,X1,X2) #Spectral correlation btw the 2 signals
def fill2(t,c1='blue') : #This function fills the zones with high correlation, it facilitates the labelling in the right intervals
i=0
while i<len(t) :
if t[x1+i]==1 :
X=[]
while t[x1+i]==1 :
X.append(x1+i)
i+=1
plt.fill_between(X,-30 ,30, color=c1, alpha=0.1)
i+=1
fig, ax = plt.subplots(1,1)
fill2(t)
ax.plot(Dt['Potential(V)'])
ax.plot(D2t['Potential(V)'])
ax.grid()
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()
def traitement(zi) : #This function supposes that empty lists called GP2_min, DP2_min, GP_min, DP_min, GP2_max, DP2_max, GP_max and DP_max were created.
#It allows to fulfill these lists using the zi variable which was created by hand labelling in the learning() function.
#Otherwise, this functions filters points selected by mistake.
Dt=split(data1,X1,X2)
D2t=split(data2,X1,X2)
i=0
while i<len(zi)-5 :
if zi[i+2][0]>zi[i+1][0] and zi[i+1][0]>zi[i][0] and zi[i+4][0]>zi[i+3][0] and zi[i+5][0]>zi[i+4][0] : #We check if the pattern is good
if abs(zi[i][0]-zi[i+3][0])<100 : #Idem
a0=[abs(D2t['Potential(V)'][int(zi[i][0])]-zi[i][0]),abs(D2t['Potential(V)'][int(zi[i][0])+1]-zi[i][0])] #Check if permutation
b0=[abs(Dt['Potential(V)'][int(zi[i][0])]-zi[i][0]),abs(Dt['Potential(V)'][int(zi[i][0])+1]-zi[i][0])]
if min(b0)<min(a0) :
zi[i],zi[i+1],zi[i+2],zi[i+3],zi[i+4],zi[i+5]=zi[i+3],zi[i+4],zi[i+5],zi[i],zi[i+1],zi[i+2]
else :
None
a0=[abs(D2t['Potential(V)'][int(zi[i][0])]-zi[i][0]),abs(D2t['Potential(V)'][int(zi[i][0])+1]-zi[i][0])]
b0=[abs(Dt['Potential(V)'][int(zi[i][0])]-zi[i][0]),abs(Dt['Potential(V)'][int(zi[i][0])+1]-zi[i][0])]
a1=[abs(D2t['Potential(V)'][int(zi[i+1][0])]-zi[i+1][0]),abs(D2t['Potential(V)'][int(zi[i+1][0])+1]-zi[i+1][0])]
b1=[abs(Dt['Potential(V)'][int(zi[i+1][0])]-zi[i+1][0]),abs(Dt['Potential(V)'][int(zi[i+1][0])+1]-zi[i+1][0])]
a2=[abs(D2t['Potential(V)'][int(zi[i+2][0])]-zi[i+2][0]),abs(D2t['Potential(V)'][int(zi[i+2][0])+1]-zi[i+2][0])]
b2=[abs(Dt['Potential(V)'][int(zi[i+2][0])]-zi[i+2][0]),abs(Dt['Potential(V)'][int(zi[i+2][0])+1]-zi[i+2][0])]
a3=[abs(D2t['Potential(V)'][int(zi[i+3][0])]-zi[i+3][0]),abs(D2t['Potential(V)'][int(zi[i+3][0])+1]-zi[i+3][0])]
b3=[abs(Dt['Potential(V)'][int(zi[i+3][0])]-zi[i+3][0]),abs(Dt['Potential(V)'][int(zi[i+3][0])+1]-zi[i+3][0])]
a4=[abs(D2t['Potential(V)'][int(zi[i+4][0])]-zi[i+4][0]),abs(D2t['Potential(V)'][int(zi[i+4][0])+1]-zi[i+4][0])]
b4=[abs(Dt['Potential(V)'][int(zi[i+4][0])]-zi[i+4][0]),abs(Dt['Potential(V)'][int(zi[i+4][0])+1]-zi[i+4][0])]
a5=[abs(D2t['Potential(V)'][int(zi[i+5][0])]-zi[i+5][0]),abs(D2t['Potential(V)'][int(zi[i+5][0])+1]-zi[i+5][0])]
b5=[abs(Dt['Potential(V)'][int(zi[i+5][0])]-zi[i+5][0]),abs(Dt['Potential(V)'][int(zi[i+5][0])+1]-zi[i+5][0])]
n0=int(zi[i][0])+a0.index(min(a0))
n1=int(zi[i+1][0])+a1.index(min(a1))
n2=int(zi[i+2][0])+a2.index(min(a2))
n3=int(zi[i+3][0])+a3.index(min(a3))
n4=int(zi[i+4][0])+a4.index(min(a4))
n5=int(zi[i+5][0])+a5.index(min(a5))
if zi[i+1][1]<zi[i][1] :
GP2_min.append((n0,n1))
DP2_min.append((n1,n2))
GP_min.append((n3,n4))
DP_min.append((n4,n5))
elif zi[i+1][1]>zi[i][1] :
GP2_max.append((n0,n1))
DP2_max.append((n1,n2))
GP_max.append((n3,n4))
DP_max.append((n4,n5))
print(i)
i+=1
def fill(Int_min,Int_max,c1='blue',c2='red') : #This function enables to fulfill the alleged ZF intervals with colors
for i in range (0,len(Int_max)) :
(a,b)=Int_max[i][0],Int_max[i][1]
X=np.arange(a,b,1)
ax.fill_between(X,-30 ,30, color=c1, alpha=0.1)
for i in range (0,len(Int_min)) :
(a,b)=Int_min[i][0],Int_min[i][1]
X=np.arange(a,b,1)
ax.fill_between(X,-30 ,30, color=c2, alpha=0.1)
def plot_mouse() : #This function allows to add new points on zi that are not yet chosen
fig, ax = plt.subplots()
fill(DP_min,DP_max)
fill(DP2_min,DP2_max,'green','orange')
fill(GP_min,DP_max)
fill(GP2_min,GP2_max,'green','orange')
cid = fig.canvas.mpl_connect('button_press_event', onclick)
ax.grid()
ax.plot(D['Potential(V)'])
ax.plot(D2['Potential(V)'])
plt.title('Labelled ZF')
plt.show()
def Coh_opt(DP,DP2,Rate_keep=95,N=4,F=100,X1=450000,X2=500000) : #DP and DP2 are lists of couples, that correspond to ZF intervals for both probes.
#Rate_keep is a parameter that adjusts the iota coefficient in accordance with the quality of the ZF chosen for the detection
#N adjust the maximum frequency to be considered
#F is the size of the gaussian window to be considered
#This function returns the optimal value of the coherence : the iota coefficient.
Dt=split(data1,X1,X2)
D2t=split(data2,X1,X2)
Fs=2e6
f, t, Sxx = signal.spectrogram(Dt['Potential(V)'], Fs, window=('gaussian',F))
f=f[0:N]
Sxx=Sxx[0:N,:]
f2, t2, Sxx2 = signal.spectrogram(D2t['Potential(V)'], Fs,window=('gaussian',F))
f2=f2[0:3]
Sxx2=Sxx2[0:N,:]
T=len(t)
SXX=[Sxx[:,t] for t in range (0,T)]
SYY=[Sxx2[:,t] for t in range (0,T)]
Corr=[0]*T
for j in range (T) :
Corr[j]=np.dot(SXX[j],SYY[j])
pas=int((X2-X1)/(T))
indices=np.arange(X1,X2,pas)
Corr2=pd.DataFrame([0]*len(Dt['Potential(V)']),index=Dt.index)
for j in range (len(indices)-1) :
Corr2[0][indices[j]]=Corr[j]*10**(9)
for l in range (X1,X2) :
if Corr2[0][l]==0 :
Corr2[0][l]=np.nan
Corr2=Corr2.interpolate(method='linear')
Corr2=Corr2[0]
Liste_coh=[]
Liste_coh2=[]
for e in DP :
e=e[0]
Liste_coh.append(Corr2[e])
for e in DP2 :
e=e[0]
Liste_coh2.append(Corr2[e])
Seuil1=np.percentile(Liste_coh,100-Rate_keep)
Seuil2=np.percentile(Liste_coh2,100-Rate_keep)
Seuil_opt=min(Seuil1,Seuil2)
return(Seuil_opt)
### a,b and c and T values
def valeur_opt(DP,DP2,MAX,Rate_keep=80) : #MAX=1 if DP and DP2 contains damping intervals that begin with a maximum value, and -1 else
#Rate_keep : adjusting parameter that refers to the rate of 'real ZF' to be kept
#This function provides the optimal values for the a, b and c coefficient for the ZF detection algorithm
Dt=split(data1,X1,X2)
D2t=split(data2,X1,X2)
C=[]
A_e=[]
B_e=[]
C_e=[]
T=[]
for e in DP :
if MAX==1 :
res=score_max(e[0],Dt)
else :
res=score_min(e[0],Dt)
score=res[0]
s=res[1]
T.append(10+10*s)
C.append(score)
for e in DP2 :
if MAX==1 :
res=score_max(e[0],D2t)
else :
res=score_min(e[0],D2t)
score=res[0]
T.append(10+10*s)
C.append(score)
for elt in C :
A_e.append(elt[0])
B_e.append(elt[1])
C_e.append(elt[2])
am=np.median(A_e) #1.59 #1.51
bm=np.median(B_e) #0.0100
cm=np.median(C_e) #1.51 #1.45
a_eropt=np.percentile(A_e, Rate_keep)
b_eropt=np.percentile(B_e, Rate_keep)
c_eropt=np.percentile(C_e, Rate_keep)
plt.hist(T)
tm=np.median(T) #100
return((a_eropt,b_eropt,c_eropt))
#a_eropt_min,b_eropt_min,c_eropt_min=valeur_opt(DP_min,DP2_min,-1)
#a_eropt_max,b_eropt_max,c_eropt_max=valeur_opt(DP_max,DP2_max,1)
### Distance with the moving average ?
###For the mins
def Distances_opt(DP,DP2,Rate_keep=90,MAX=-1,S=100) : #This function provides the optimal distance with the average when a ZF appears
S=100
MAX=-1
Rate_keep=90
DP=DP_min
DP2=DP2_min
Dt=split(data1,X1,X2)
D2t=split(data2,X1,X2)
Distances1=[]
Distances2=[]
D_m=Dt.rolling(S).mean()['Potential(V)']
D2_m=D2t.rolling(S).mean()['Potential(V)']
D_sd=Dt.rolling(S).std()['Potential(V)']
D2_sd=D2t.rolling(S).std()['Potential(V)']
D_rms=np.sqrt(Dt.pow(2).rolling(S).apply(lambda x: np.sqrt(x.mean())))['Potential(V)']
D2_rms=np.sqrt(D2t.pow(2).rolling(S).apply(lambda x: np.sqrt(x.mean())))['Potential(V)']
for elt in DP :
Distances1.append((Dt['Potential(V)'][elt[0]]-D_m[elt[0]])/D_sd[elt[0]])
for elt in DP2 :
Distances2.append((D2t['Potential(V)'][elt[0]]-D2_m[elt[0]])/D2_sd[elt[0]])
if MAX==-1 :
Distance_opt=max(abs(np.percentile(Distances1, Rate_keep)),abs(np.percentile(Distances2, Rate_keep)))
elif MAX==1 :
Distance_opt=max(abs(np.percentile(Distances1, 100-Rate_keep)),abs(np.percentile(Distances2, 100-Rate_keep)))
return(Distance_opt)
def plotidist() : #This function plots the distogram of distances with the average (in number of sd)
plt.hist(Distances1)
plt.hist(Distances2)
plt.grid()
plt.hist(Distances1,bins=20,color='blue',ec='blue',alpha=0.4,label='Probe B')
plt.hist(Distances2,bins=20,color='darkorange',ec='darkorange',alpha=0.4,label='Probe D')
plt.xlabel('Distance from the MA (in number of sd)')
plt.ylabel('Distance from the MA (in number of sd)')
plt.legend()
plt.title('Histogram of the distance from the MA (in number of sd)')
plt.show()
###For the max
def plot_dist() :
Distances1=[]
Distances2=[]
S=100
for elt in DP_max :
Distances1.append((D['Potential(V)'][elt[0]]-D_m[elt[0]])/D_sd[elt[0]])
for elt in DP2_max :
Distances2.append((D2['Potential(V)'][elt[0]]-D2_m[elt[0]])/D2_sd[elt[0]])
plt.grid()
plt.hist(Distances1,20,color='blue',alpha=0.4)
plt.hist(Distances2,20,color='orange',alpha=0.4)
plt.title('Distance from the MA (in number of sd)')
plt.show()
#np.mean(Distances1)
#-2.1596255864703964
#np.mean(Distances2)
#-2.1167086057968336
###Filter on the length
def indicatrice(Int) :
ind=[0]*(X2-X1)
ind=pd.DataFrame(ind)
ind=ind.set_index(np.arange(X1,X2,1))
for i in range (len(Int)) :
for l in range (Int[i][0],Int[i][1]) :
ind[0][l]=1
return(ind[0])
def liste_quotient(Int,Int2) :
Int=DP_min
Int2=DP2_min
ind_=indicatrice(Int)
ind2_=indicatrice(Int2)
produit=ind_*ind2_
Lp=[]
for (a,b) in Int :
for (c,d) in Int2 :
if (a<c and b>c) or (a<c and d<b) or (c<a and d>a) or (c<a and b<d) : #The two intervals recover
liste=[produit[e] for e in range (min(a,c),max(b,d))]
n=len(liste)
liste=np.asarray(liste)
p=len(np.where(liste==1)[0])/n
Lp.append(p)
return(Lp)
def read(file) :
with open(file) as f:
lines = f.readlines()
def save(var,name) :
namefile="sample{}.txt".format(name)
file = open(namefile, "w")
file.write("%s = %s\n" %(name, var))
file.close()
|
f505c35af870e9a796b92833a05d3a8784c896a2 | rathnakarsp/GSoC | /data_preparation/classes.py | 2,861 | 3.859375 | 4 | import os
import numpy as np
'''
Class person has two variables: the one that is composed of activities and the second are the label to each entry of the activity variable
We have five environments: bathroom, bedroom, kitchen, living room and office which are composed of the following activities:
bathroom
- rinsing mouth with water
- brushing teeth
- wearing contact lenses
bedroom
- talking on the phone
- drinking water
- opening pill container
kitchen
- cooking (chopping)
- cooking (stirring)
- drinking water
- opening pill container
livingroom
- talking on the phone
- drinking water
- talking on couch
- relaxing on couch
office
- talking on the phone
- writing on whiteboard
- drinking water
- working on computer'''
class Person:
def __init__(self):
self.activity = []
self.label = []
#This function is for converting the activity file into a numpy array of n rows, corresponding to frames of the activity
def string2list(self,stringact):
tmp=stringact.split("\n")[:-1] #the -1 is to remove the line with the END word
dim = [len(tmp),tmp[0].count(",")]
lista = []
for i in range(len(tmp)):
nnmm=np.fromstring(tmp[i],sep=",")
lista.append(nnmm)
#lista=np.array(lista)
return lista
#The search function is used to find the position of an argument in a listo of lists. Consequently it is used to find the name of activity for a set of frames read from file
def search(self,lst, item):
for i in range(len(lst)):
part = lst[i]
for j in range(len(part)):
if part[j] == item: return (i, j)
return None
#updating activity and labels
def read_activity_from_folder(self,folder):
tmp = open(os.path.join(folder,"activityLabel.txt"),'r').read()
tmp = tmp.split("\n")[:-1]
activityList=[tmp[i].split(",") for i in range(len(tmp))]
#np.loadtxt(folder,delimiter=",",unpack=True)
entries = os.listdir(folder)
for entry in entries:
if entry.endswith(".txt") and "activity" not in entry:
with open(os.path.join(folder,entry),'r') as df:
stringact = df.read()
tmp=self.string2list(stringact)
self.activity.append(tmp)
name = os.path.splitext(entry)[0]
index=self.search(activityList,name)
if index!=None:
self.label.append(activityList[index[0]][1])
else:
self.label.append("none")
#Adding activity if person performs a new activity
def add_activity(self,act,lab):
self.activity.append(act)
self.label.append(lab)
|
9b6e8b0fec2d86f258cb444cfe969eda4ad9ad95 | lanhhv84/multithreading_crawler | /threads.py | 1,465 | 4.0625 | 4 | from __future__ import print_function
import threading
import time
class Threads:
"""
How to use:
Create Threads object
th = Threads(num_threads, data_pool)
Create a function f that take two argument
The first one is data in pool
The second one is a tuple of additional arguments
Ex:
def func(data, extra):
# extra = (a1, a2)
a1, a2 = extra
print(data + a1 + a2)
Run
th.run(func, (10, 20))
"""
def __init__(self, num_threads, data_pool):
self.num_threads = num_threads
self.data_pool = data_pool
self.lock = threading.Lock()
self.threads = []
def run(self, func, extra_args):
# Task receive a tuple
for i in range(self.num_threads):
thread = threading.Thread(target=self.task, args=(func, extra_args))
self.threads.append(thread)
thread.start()
def join(self):
for t in self.threads:
t.join()
def task(self, func, extra_args):
while len(self.data_pool) > 0:
data = None
with self.lock:
if len(self.data_pool) == 0:
return
else:
data = self.data_pool[0]
self.data_pool = self.data_pool[1: ]
func(data, extra_args)
|
d1cb48d421ad5e5e751610e4e415128e525eb26f | HenintsoaHARINORO/Youtube-Video-Downloader2 | /Download.py | 801 | 3.578125 | 4 | import tkinter as tk
from pytube import YouTube
window = tk.Tk()
window.geometry('500x300')
window.resizable(0,0)
window.title("Youtube Video Downloader")
tk.Label(window, text ="Youtube Video Downloader", font ="arial 20 bold").pack()
link = tk.StringVar()
tk.Label(window, text ="Paste Link Here:", font ="arial 15 bold").place(x=160, y=60)
link_error = tk.Entry(window, width =70, textvariable = link).place(x =32, y=90)
def Downloader():
url =YouTube(str(link.get()))
video =url.streams.first()
video.download('./Downloads')
tk.Label(window, text ="Successfully Downloaded", font ="arial 15").place(x =180, y =200)
#Download Button
tk.Button(window, text ="DOWNLOAD", font ="Verdana 15 bold", bg ="orange", padx =2, command =Downloader).place(x=180, y=150)
window.mainloop()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.