blob_id
stringlengths 40
40
| repo_name
stringlengths 5
119
| path
stringlengths 2
424
| length_bytes
int64 36
888k
| score
float64 3.5
5.22
| int_score
int64 4
5
| text
stringlengths 27
888k
|
---|---|---|---|---|---|---|
d064b683c1581f0d4f3f1f41bd5f6caa2ba4a215 | amari-at4/Password_Hacker | /Topics/Kwargs/Tallest people/main.py | 295 | 3.65625 | 4 | def tallest_people(**kwargs):
tallest = {}
for name, height in sorted(kwargs.items()):
tallest.setdefault(height, []).append(name)
tallest_height = sorted(tallest, reverse=True)[0]
for people in tallest.get(tallest_height):
print(f"{people} : {tallest_height} ")
|
234ddfccd1c03b8d7fd3a4d3eaf7fd88bc290386 | vishalsood114/pythonprograms | /sigma.py | 326 | 3.71875 | 4 | """ function that computes the sum of any function passed as
a parameter
"""
def sigma(f,a,b):
return sum(f(x) for x in range(a,b))
def square(x):
return x*x
def cube(x):
return x*x*x
print sigma(square, 1,10)
print sigma(cube,1,10)
print sigma(lambda x:x**0.5, 0,10)
print sigma(lambda x:1.0/x,1,100)
|
91aa873537912aa320e4d02bebb5a6125146e5a4 | develooper1994/DeepLearningCaseStudies | /SırajRaval/MathOfIntelligence/Chapter1/LinearRegression.py | 3,511 | 3.84375 | 4 | from numpy import *
from numpy.core._multiarray_umath import ndarray
import matplotlib.pyplot as plt
'''
This example about single line modelling. y = mx + b (Linear regression)
There is also polinominal models like y = (k=1->inf)sum(mk*x**k) + b =m1*x + m2*x**2 + m3*x**3 + ... + b (Polinom fit)
'''
# y = mx + b
# m is slope, b is y-intercept
def line_regression_result(b, m, x):
return m * x + b
def toterror(y, x, b, m):
# SSE(sum of square error)
return (y - line_regression_result(b, m, x)) ** 2
def toterror_derivative_b(N, y, x, b_current, m_current): return -(2 / N) * (y - line_regression_result(b_current, m_current, x))
def toterror_derivative_m(N, y, x, b_current, m_current): return -(2 / N) * x * (y - line_regression_result(b_current, m_current, x))
def gradient(N, y, x, b_current, m_current):
return toterror_derivative_b(N, y, x, b_current, m_current), \
toterror_derivative_m(N, y, x, b_current, m_current)
def error_line_points(b: float, m: float, points):
total_error: float = 0.0
n: int = len(points)
for i in range(n):
x, y = points[i, (0, 1)]
total_error += toterror(y, x, b, m)
return total_error / float(n)
def step_gradient(b_current, m_current, points, learning_rate):
b_gradient: float = 0.0
m_gradient: float = 0.0
N: int = len(points)
for i in range(N):
x, y = points[i, (0, 1)]
grad = gradient(N, y, x, b_current, m_current)
b_gradient += grad[0]
m_gradient += grad[1]
new_b = b_current - (learning_rate * b_gradient)
new_m = m_current - (learning_rate * m_gradient)
return new_b, new_m
def gradient_descent_runner(points, starting_b, starting_m, learning_rate, num_iterations):
b: float = starting_b
m: float = starting_m
for i in range(num_iterations):
b, m = step_gradient(b, m, array(points), learning_rate)
return b, m
def run():
filename = "data.csv"
points: ndarray = genfromtxt(filename, delimiter=",")
learning_rate: float = 0.0001
b_initial: float = 0.0 # initial y-intercept guess
m_initial: float = 0.0 # initial slope guess
num_iter: int = 1000
print(f"Gradient descent started at b = {b_initial}, m = {m_initial}, "
f"error = {error_line_points(b_initial, m_initial, points)}")
print("Running 'data.csv'...")
b, m = gradient_descent_runner(points, b_initial, m_initial, learning_rate, num_iter)
p = plotter(b, m, points)
p.title(filename)
p.show()
print(f"After ; b = {b}, m = {m}, "
f"error = {error_line_points(b, m, points)}")
# another data set but it is random points. Basic line regression isn't good for the random datasets
points = random.rand(100,2)
print(f"\nGradient descent started at b = {b_initial}, m = {m_initial}, "
f"error = {error_line_points(b_initial, m_initial, points)}")
print("Running 'data.csv'...")
b, m = gradient_descent_runner(points, b_initial, m_initial, learning_rate, num_iter)
p = plotter(b, m, points)
p.title('random data')
p.show()
print(f"After ; b = {b}, m = {m}, "
f"error = {error_line_points(b, m, points)}")
def plotter(b, m, points):
x, y = points[:, 0], points[:, 1]
yhat = line_regression_result(b, m, x)
plt.plot(x, yhat, c='green')
plt.scatter(x, y, c='red', marker='.', linestyle=':')
plt.gca().invert_yaxis()
plt.xlabel('x')
plt.ylabel('y')
return plt
if __name__ == '__main__':
run()
|
609cca7ecdae8b1851b9290a3ea3d9e8f6038ff2 | sxt/pipython | /sayhello.py | 168 | 3.765625 | 4 | #!/usr/bin/python
import sys
print "Hello " + sys.argv[1]
option = sys.argv[1]
if option == "1":
print "Turning on pin 1"
else:
print "Not turning on a pin"
|
c378b70ddd789fc251b7a66718689b9c7023b339 | Ichiro805/crypto-mining-sites | /telegram/ZEC Click Bot/sleep.py | 242 | 3.625 | 4 | import time
from datetime import datetime, timedelta
def sleep(ms):
timenow = datetime.now()
print("Sleeping for: ", ms, " ms. Sleep is from ", str(timenow), "to", str(timenow + timedelta(hours = ms / 1000 / 3600)))
time.sleep(ms / 1000)
|
c0a6ec73851426331ea2aec71c52e6d8fc113455 | Yiisux/Clase | /PycharmProjects/untitled1/ArteagaDuranJesusExamen/Ejercicio2.py | 366 | 3.796875 | 4 | #-'- coding: utf-8 -'-
list = []
print "Diga la primera palabra"
list.append(raw_input())
print "Diga la segunda palabra"
list.append(raw_input())
print "Diga la tercera palabra"
list.append(raw_input())
print "Diga la cuarta palabra"
list.append(raw_input())
print "Diga la quinta palabra"
list.append(raw_input())
list.sort(reverse=False)
print list |
5c2240e374a1dafa9e9c2558a3336515bb993365 | monish7108/PythonProg2 | /fibonacciNumChecking.py | 1,384 | 4.28125 | 4 | """This programs check every number from command line
and tells whether number is in fibbonacci series or not.
Math: Instead of producing loop and checking the number there is a mathematical formula.
If (5*x*x)+4 or (5*x*x)-4 or both are perfect squares,
then the number is in fibonacci.
======================================================================="""
def isPerfectSquare(x):
"""if the number is not having decimal part then dividing it from int type
of same num gives 0"""
return (x**0.5) % int(x**0.5) == 0
def fibonacciSeries(userinput):
"""This function tells whether number is in fibbonacci series or not."""
try:
isinstance(int(userinput), int)
userinput = int(userinput)
except ValueError as e:
print(e)
else:
if isPerfectSquare(
(5 *
userinput *
userinput) -
4)or isPerfectSquare(
(5 *
userinput *
userinput) +
4):
return True
else:
return False
if __name__ == "__main__":
print(__doc__)
userinput = input("Enter the number you want to check: ")
if fibonacciSeries(userinput):
print("The numeber is present in fibonacci series.")
else:
print("The number is not present in fibonacci series.")
|
424f40816cbcc82c156a9c43647b4c7b5d956f5a | CaiqueAmancio/ExercPython | /exerc_22.py | 796 | 4.125 | 4 | """
Leia a idade e o tempo de serviço de um trabalhador e escreva se ele pode ou não se aposentar.
As condições para aposentadoria são:
- Ter pelo menos 65 anos;
- Ou ter trabalhado pelo menos 30 anos;
- Ou ter pelo menos 60 anos e trabalhado pelo menos 25 anos
"""
print('Digite sua idade e seu tempo de serviço e direi se pode ou não se aposentar.\n')
idade = int(input('Digite sua idade: \n'))
tempo_servico = int(input('Digite seu tempo de serviço (em anos): \n'))
if idade >= 65 or tempo_servico >= 30:
print('Tem direito a aposentadoria por idade ou tempo de serviço')
elif idade >= 60 and tempo_servico >= 25:
print('Tem direito a aposentadoria por idade e tempo de serviço!')
else:
print('Não tem direito a aposentadoria por idade nem por tempo de serviço!')
|
fcbb4d738d62c7e376322ae42d255088d4c712aa | radavis47/automate_python | /Programs/collatzSequence.py | 594 | 4.3125 | 4 | def collatz(number):
if number % 2 == 0:
print(number//2)
return number // 2
elif number % 2 == 1:
print(3*+number+1)
return 3 * number + 1
r=''
print('Enter the number')
while r != int:
try:
r=input()
while r != 1:
r=collatz(int(r))
break
except ValueError:
print ('Please enter an integer')
# https://stackoverflow.com/questions/33508034/making-a-collatz-program-automate-the-boring-stuff
# https://www.reddit.com/r/learnpython/comments/4ps9zn/the_collatz_sequence_automate_the_boring_stuff/
|
d5e3bca573d32316aef967b1712a15996475c2ab | vengrinovich/python | /number_guess.py | 478 | 3.984375 | 4 | import random
a = random.randint(1,9)
guesses = 0
while True:
user_number = raw_input("Please guess a number from 1 to 9:")
if user_number == 'exit':
break
elif int(user_number) == a:
guesses += 1
print "You guessed it right using %d guesses" % guesses
break
elif int(user_number) > a:
guesses += 1
print "Your number is higher then computer's, try again"
elif int(user_number) < a:
guesses += 1
print "Your number is lower then computer's, try again"
|
14c48fc45021cdc354c1ebd3ba1f4b874d24ec49 | hungcold/BaiKiemTraXSTK | /Bai2.py | 358 | 3.5 | 4 | A=[1,1,2,3,5,8,13,21,34,55,88]
B=[1,3,5,4,7,88,66,59,40,54]
C = set(A) & set(B)
print("Các phần tử trùng nhau trong list A,B là",C)
for i in A:
for j in B:
if(j==i):
A.remove(j)
B.remove(j)
print("Xóa các phần tử trong list A bị trùng nhau",A)
print("Xóa các phần tử trong list B bị trùng nhau",B) |
fae2a2ad56cd8cadb6295067f623fcb90334ed0b | Albert-Richards/Python | /QA_community/programs/debug.py | 898 | 4.15625 | 4 | import pdb
"""## exercise 1
num = float(input("Burger price:"))
price = {"Burger": num}
user_funds = 10.31
item_price = price["Burger"]
if item_price < user_funds:
print("You have enough money!")
if item_price == user_funds:
print("You have the precise amount of money")
if item_price > user_funds:
print("Sorry you don't have enough money")
##exercise 2
def product(n):
total = 1
for n in n:
total *= n
return total
print(product([4,4,5]))"""
##exercise 3
#pdb.set_trace()
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
for n in range(2, x):
if x % n == 0:
return False
return True
print(is_prime(78))
##exercise
"""pdb.set_trace()
item_list = ["Burger", "Hotdog", "Bun", "Ketchup", "Cheese"]
n = 0
while n < 5:
for i in item_list:
print(item_list[i])
print(item_list[5])""" |
6c147e14300b51aca7c8251bc132f4a7312e5b92 | lidianxiang/leetcode_in_python | /树/501-二叉搜索树中的众数.py | 856 | 3.53125 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
import collections
class Solution:
def findMode(self, root: TreeNode) -> List[int]:
if not root:
return []
self.count = collections.Counter()
# 中序遍历得到有序序列
self.inOrder(root)
# 找到频数最多的那个数
freq = max(self.count.values())
res = []
# 要考虑存在多个最大值的情况
for item ,c in self.count.items():
if c == freq:
res.append(item)
return res
# 中序遍历
def inOrder(self, root):
if not root:
return
self.inOrder(root.left)
self.count[root.val] += 1
self.inOrder(root.right)
|
e62d424cca83e3cef9c581893948b3d6ec0aedce | GauthamAjayKannan/guvi | /binary.py | 114 | 3.71875 | 4 | #62
s=input()
b,n=0,0
for i in s:
if i=="0" or i=="1":
b=1
else:
n=1
break
print("no" if n==1 else "yes")
|
439cbd5337f4e64b5b0628d6b765351ffbfa1f8d | ericlarslee/RockPaperScissorsLizardSpock | /game.py | 2,025 | 4.0625 | 4 | import math
from human import Human
from computer import Computer
def game():
print('Hello!\n--------------------\nWelcome to RPSLS!\n--------------------\n'
'Here are the game Rules:\nRock crushes Scissors\nScissors cuts Paper\n'
'Paper covers Rock\nRock crushes Lizard\nLizard poisons Spock\nSpock smashes Scissors\n'
'Scissors decapitates Lizard\nLizard eats Paper\nPaper disproves Spock\n'
'Spock vaporizes Rock\n')
player1 = Human()
print(f'Welcome {player1.id}')
opponent = ''
while opponent != 'computer' or opponent != 'human':
opponent = input('\nDo you want to play against a computer, or a human?')
if opponent == 'computer':
player2 = Computer()
print(f'Welcome {player2.id}\n')
break
elif opponent == 'human':
player2 = Human()
print(f'Welcome {player2.id}\n')
break
else:
print('try again')
games = input('How many games would you like this series to be the best of?')
games = int(games)
games /= 2
games = math.floor(games)
games += 1
player1_points = 0
player2_points = 0
while player1_points < games and player2_points < games:
print(f'{player1.id} it is your turn\n')
player1_turn = player1.gesture_choice()
print(f'{player2.id} it is your turn\n')
player2_turn = player2.gesture_choice()
for beat in player2_turn.beats:
if player1_turn.name == beat:
print(f'{player2.id} wins this round')
player2_points += 1
for lose in player2_turn.loses:
if player1_turn.name == lose:
print(f'{player1.id} wins this round')
player1_points += 1
if player1_turn.name == player2_turn.ties:
print('This one is a draw!')
if player1_points == games:
print(f'{player1.id} wins!')
if player2_points == games:
print(f'{player2.id} wins!')
|
ba31d159601f9af8e092ad35aac0c97dae80b306 | eskog/password-compare | /PwComp.py | 939 | 3.6875 | 4 | #!/bin/usr/python
#Loads in 2 password files formated as user:password and opens a output file.
file1 = ""
file2 = ""
matches = open("matches.txt" ,"w")
#Opens the first file, Retrieved the Username and password, then search the other file for a identical password.
with open(file1 ,"r") as pw1:
for line in pw1:
line = line.rstrip('\n')
temp = line.rsplit(':',1)
user = temp[0]
password = temp[1]
#Starts to read the second passwords and compares them with the first ones.
with open(file2 ,"r") as pw2:
for line in pw2:
line = line.rstrip('\n')
temp = line.rsplit(':',1)
user2 = temp[0]
password2 = temp[1]
#Check if password matches, if they do, write it to an outfile.
if password == password2:
matches.write('{}' + user + ' {} ' + user2 + '\n').format('User: ', 'and User: ') ##writing the results to file.
file1.close()
file2.close()
matches.close()
|
401ca8a067c49c874ece1e2b2d67f73d2816d285 | veena863/python-practice-01 | /practice03.py | 1,904 | 4.625 | 5 | #!/usr/bin/env python
# coding: utf-8
# In[5]:
#How to change,add,deleting elements in a list
fruits=['Apple','mango','banana','gauava']
print(fruits)
#1changing elements in list
fruits[1]='pea'
print(fruits)
# In[2]:
#2 Adding/append the element in the list
fruits=['Apple','manga','banana','gauava']
print(fruits)
fruits.append('pineapple')
print(fruits)
# In[3]:
"""above we can observe that the added element is placed at the last of the list
if we want to place at any particular position then we need to define with a index position as below"""
fruits=['Apple','manga','banana','gauava']
print(fruits)
fruits.insert(2,'pineapple')
print(fruits)
# In[4]:
#Dymanic creation of empty list
friends=[]
print(friends)
friends.append('satya')
friends.append('teja')
friends.append('Anu')
friends.append('navee')
friends.insert(1,'harry')
print(friends)
# In[10]:
#3 deleting elements from list
#there are two differnt ments to delete the element from list
#a
icecreames=['chocalate','butterscotch','vanilla','tuttyfruity']
print(icecreames)
del icecreames[2]
print(icecreames)
#b
icecreames=['chocalate','butterscotch','vanilla','tuttyfruity']
icecreames.pop()
# the above syntax will delete the last element in the list
print(icecreames)
#inorder to delete the particular element in the list below has to be followed
icecreames.pop(1)
print(icecreames)
"""delete will delete the items permanently
whereas pop() will not delete its permeanently from memory
in popup items will be stored separately in another variable declared"""
# In[14]:
#4 how to sort a list?
veg=['carrot','beans','cabbage','bitterguard']
veg.sort()
print(veg)
veg.reverse()
print(veg)
veg=['carrot','beans','cabbage','bitterguard']
veg.reverse()
print(veg)
# In[15]:
#5 how to count the no. of elements in a list?
veg=['carrot','beans','cabbage','bitterguard']
print(len(veg))
# In[ ]:
|
fdaee51960f758bf2388ce2dc4fae3de5815f9aa | heyulin1989/language | /python/books/writing-solid-python-code-91-suggestions/30.py | 964 | 3.609375 | 4 | #coding:utf8
nested_list = [['Hello', "world"], ['Goodbye', 'World']]
# [expr for iter_item in iterable if cond_expr]
nested_list = [[s.upper() for s in xs if len(s) > 5] for xs in nested_list ]
print nested_list
# 支持多重迭代
nested_list = [(a,b) for a in ['a','1'] for b in [3,'b'] if a != b]
print (nested_list)
# 表达式可以是函数
def f(v):
if v%2 == 0:
v = v**2
else:
v = v+1
return v
nested_list = [f(v) for v in [2,3,4,5,6,7,-1] if v>0]
print nested_list
#也可以是普通的计算
nested_list = [v**2 if v%2==0 else v+1 for v in [2,3,4,5,6,7,-1,-2] if v>0]
print nested_list
# 可以把iterable当作一个文件句柄
fh = open("23.py","r")
result = [i for i in fh if 'print' in i]
print result
# 元组,集合,字典都可以
# 字典 ===>> {expr1, expr2 for iter_item in iterable if cond_expr}
# 集合 ===>> {expr for iter_item in iterable if cond_expr}
# 元组 ===>> (expr for iter_item in iterable if cond_expr)
|
bc4933b335a9bbd4dff7df249c6fe3c32bce1208 | jedzej/tietopythontraining-basic | /students/sendecki_andrzej/lesson_01_basics/tens_digit.py | 211 | 4.0625 | 4 | # lesson_01_basics
# Tens digit
#
# Statement
# Given an integer. Print its tens digit.
import math
print("Enter the number")
n = int(input())
res = abs(n) // 10 % 10
print("The tens digit is: " + str(res))
|
a402af35c7fc722a5eba8ee9d9640d57e3c99627 | bullethammer07/Python_Tkinter_tutorial_repository | /progress_bar.py | 1,061 | 4.0625 | 4 | #------------------------------------
# Implementing a Progress Bar
#------------------------------------
# importing tkinter module
from tkinter import *
from tkinter.ttk import *
# creating tkinter window
root = Tk()
# Progress bar widget
progress = Progressbar(root,
orient=HORIZONTAL,
length=250,
mode='determinate')
# Function responsible for the updation
# of the progress bar value
def bar():
import time
progress['value'] = 20
root.update_idletasks()
time.sleep(1)
progress['value'] = 40
root.update_idletasks()
time.sleep(1)
progress['value'] = 50
root.update_idletasks()
time.sleep(1)
progress['value'] = 60
root.update_idletasks()
time.sleep(1)
progress['value'] = 80
root.update_idletasks()
time.sleep(1)
progress['value'] = 100
progress.pack(pady=10)
# This button will initialize
# the progress bar
Button(root, text='Start', command=bar).pack(pady=10)
# infinite loop
mainloop() |
2b2eeafbb099d2d8c469b467584f46c8f3c066e7 | balasubramanyas/PythonMultiThreadApplication | /source/com/sbala/thread/concurrent/ThreadPoolExecutorExampleMain.py | 601 | 3.734375 | 4 | '''
Created on Jan 8, 2019
@author: balasubramanyas
'''
from concurrent.futures.thread import ThreadPoolExecutor
def printData(x):
return x + 2
if __name__ == '__main__':
values = [1,2,3,4]
executor = ThreadPoolExecutor(2)
# Submit method
print("Executor.submit() : ")
submitresultData = {executor.submit(printData, i) : i for i in values}
for res in submitresultData:
print(res.result())
# Map method
print("Executor.map() : ")
mapresultData = executor.map(printData, values)
for res in mapresultData:
print(res)
pass
|
ed3d8d1270296da678983c27284d43a9a74df6e1 | usernamegenerator/MOOC | /MIT OpenCourseWare/MITx6.00.2x Introduction to Computational Thinking and Data Science/Unit2/exe3.py | 785 | 3.84375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Feb 2 15:57:37 2019
@author: yuhan
"""
#Exercise 3-1
#0.0/5.0 points (graded)
#Write a deterministic program, deterministicNumber, that returns an even number between 9 and 21.
import random
def deterministicNumber():
'''
Deterministically generates and returns an even number between 9 and 21
'''
#return random.choice(range(10, 22,2))
return 10
print (deterministicNumber())
#Write a uniformly distributed stochastic program, stochasticNumber, that returns an even number between 9 and 21.
def stochasticNumber():
'''
Stochastically generates and returns a uniformly distributed even number between 9 and 21
'''
# Your code here
return random.choice(range(10,22,2))
print (stochasticNumber()) |
06a50ef6249ec7dc987fc81b4b5c7f6a8dcf336f | Maria16pca111/Design-and-Analysis-of-Algorithms | /SquareRootNo.py | 2,557 | 3.875 | 4 | # find the square root of a given no
# using the Iterative Method
import math
def iseven(m):
flag = False
if(m % 2 == 0):
flag = True
return flag;
def betterguess(m,a):
betterguessarr = []
differencearr = []
flag = False
for i in a:
difference = m - round (i * i)
if not(difference < 0):
betterguessarr.append(i)
differencearr.append(difference)
differencearr.sort()
betterguessarr.sort()
if len(betterguessarr) > 0:
flag = True
result1 = betterguessarr[len(betterguessarr)-1]
if len(differencearr) > 0:
flag = True
result = differencearr[len(differencearr)-1]
split = "&"
if flag == True:
return result1,split,result
else:
return 0
def Squareroot(m):
#initial guess.
flag = True
a=[]
result=[]
print("Given no is ",m)
flag = iseven(m)
if(flag == False):
start = 3
Jump = 2
else:
start = 2
Jump = 2
for j in range(start,m,Jump):
n = m % j
if(n == 0):
a.append(j)
else:
continue
if not (len(a) == 1):
guess = betterguess(m,a)
if not (guess == 0):
m = guess[0]
m1 = guess[2]
for i in a:
#a_float = n
#formatted_float = "{:.2f}".format(a_float)
m = round(m,2)
n = round(i * i,2)
while(n != m):
#n = "{:.2f}".format(n)
n = round(n,2)
if(n > m):
n -= 1
elif (n < m):
n += 0.1
else:
if(n == m):
print("SquareRoot by Using Iterative Method Result is",n)
else:
continue
print("SquareRoot by Using Iterative Method Result is",n)
return "Success"
print (Squareroot(64))
def iseven(m):
flag = False
if(m % 2 == 0):
flag = True
return flag;
def betterguess(m,a):
betterguessarr = []
differencearr = []
for i in a:
difference = m - round (a * a)
betterguessarr.append(i)
differencearr.append(difference)
differencearr.sort()
betterguessarr.sort()
result1 = betterguessarr[len(betterguessarr-1)]
result = differencearr[len(differencearr-1)]
return result1,result
|
bdb5818bafafe4b96dd5145a5f212d43a65bbc62 | Laurahpro/EXERCICIOS-EM-PYTHON | /ex000.py | 323 | 3.828125 | 4 | nome = input('Qual o seu nome?')
print('É um grande prazer te conhecer,', nome)
idade = input('Quantos anos você tem?')
print('Bacana que você tem', idade,'anos', nome,'!')
filho = input('Você tem filhos?')
print('Que bacana!')
nomeFilho = input('Qual o nome do seu filho?')
print('Então ele se chama', nomeFilho, '!') |
65773d0b9e03e1e1f94eac0501a2ff404c7bd542 | 4doctorstrange/DS-and-Algorithms-in-Python | /solved/codechef/Gasoline 2 Lunchtime.py | 622 | 3.5625 | 4 | for _ in range(int(input())):
n=int(input())
fuel=list(map(int,input().split()))
cost=list(map(int,input().split()))
sorted_indicesC=[i[0] for i in sorted(enumerate(cost),key=lambda x:x[1])] #this line will sort indices of array on the basis of values and those indices are stored in array
ans=0
distleft=n
for i in sorted_indicesC:
temp=min( fuel[i], distleft) # fuel[i] will basically give fuels of cars in ascending order of cost.
distleft-=temp
ans+= temp*cost[i] #extracting cost of that car
if distleft==0:
break
print(ans)
|
bfac67572c16b6d0de6e5906b008e564348740c9 | farzanehta/project-no.1 | /Mosh/list_remove_the_duplicates.py | 338 | 3.8125 | 4 | #1(Myself)
numbers = [1, 6, 3, 3, 6, 7, 3, 4, 4, 10]
for i in numbers:
if numbers.count(i) > 1:
numbers.remove(i)
print(numbers)
numbers.sort()
numbers.reverse()
print(numbers)
#2(Mosh)
numbers = [1, 6, 3, 3, 6, 7, 3, 4, 4, 10]
uniques = []
for i in numbers:
if i not in uniques:
uniques.append(i)
print(uniques)
|
cb9ff9c61369f3cda5324f8bf33be211914c05c4 | fatemehmakki13/CIS2001-Winter2017 | /MoreClasses/MoreClasses/MoreClasses.py | 1,277 | 3.9375 | 4 | class BankAccount:
def __init__(self,name,number):
self._name = name
self._number = number
self._balance = 0
def GetName(self):
return self._name
def GetNumber(self):
return self._number
def GetBalance(self):
return self._balance
def Withdraw(self, amount ):
if amount <= self._balance:
self._balance -= amount
else:
raise ValueError('Amount to withdraw exceeds balance')
def Deposit(self, amount ):
if amount >= 10000:
print( 'Fatemeh has to do paperwork for us' )
self._balance += amount
def __add__(self, other):
result = BankAccount(self.GetName() + "1", self.GetNumber() + 1 )
result._balance = self.GetBalance() + other.GetBalance()
return result
def __str__(self):
return "Name: " + self._name + " Number: " + str(self._number) + " Balance: " + str(self._balance)
checking = BankAccount("Eric's Checking", 123456789)
savings = BankAccount("Eric's Savings", 234567890)
checking.Deposit(1000)
savings.Deposit(2000)
new_account = checking + savings
# short hand for this
new_account = checking.__add__(savings)
print(checking)
print(new_account)
print(savings)
#checking = checking - savings
|
e012e6b35e8c430bed63b3dea3901fa7b747c056 | sederj/zork | /Python/Player.py | 2,238 | 3.546875 | 4 | import random
from Weapon import Empty
from Weapon import HersheyKiss
from Weapon import SourStraw
from Weapon import ChocolateBar
from Weapon import NerdBomb
'''
Created on Nov 2, 2017
@author: Joseph Seder, Daniel Gritters
'''
class Player(object):
'''
This class holds the game's player object
'''
def __init__(self):
'''
set the player's initial health, attack, and weapons
player's attack and health have been boosted for testing
purposes
'''
self.health = random.randrange(10000, 10025)
self.attack = random.randrange(40, 50)
self.weapons = []
self.generateWeapons()
def getWeapons(self):
''' get the player's list of weapons '''
return self.weapons
def getHealth(self):
''' get the player's health '''
return self.health
def printWeapons(self):
''' print the player's current weapon inventory '''
for ind,weapon in enumerate(self.weapons):
if(weapon.getName() == "Empty"):
index = str(ind + 1)
print(index + ": Empty")
else:
print(str(ind + 1) + ": " + weapon.getName() + " " + str(weapon.getUses()))
def decWeapon(self,weaponNum):
''' decrement a weapon from the player's inventory '''
weapon = self.weapons[weaponNum]
weapon.decrement()
if(weapon.getUses() == 0):
self.weapons[weaponNum] = Empty()
def attackMon(self,weaponNum,monster):
''' subtract the attack of the monster from the player's health '''
self.health = self.health - monster.attacked(self.attack,self.weapons[weaponNum])
def generateWeapons(self):
''' generate a random list of weapons '''
self.weapons.append(HersheyKiss())
for i in range(9):
weaponNum = random.randint(2,4)
if (weaponNum == 2):
self.weapons.append(SourStraw())
elif (weaponNum == 3):
self.weapons.append(ChocolateBar())
elif (weaponNum == 4):
self.weapons.append(NerdBomb())
|
1bdc2c167487e6b560d7da652e32d658498c05d1 | aaka2409/HacktoberFest2020 | /Python/Factorial.py | 377 | 4.34375 | 4 |
# To take input from the user
n = int(input("Enter a number: "))
factorial = 1
# checking wheather the number is negative, positive or zero
if n < 0:
print("factorial does not exist for negative numbers")
elif n == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",n,"is",factorial)
|
34fdeacd670fda71aa3b4cf6f90b93dc3fc2129f | narayanants/complete-python-bootcamp | /4 Methods and Functions/lambda.py | 763 | 3.84375 | 4 | def square(num):
return num ** 2
my_nums = [1, 2, 3, 4, 5]
for item in map(square, my_nums):
print(item)
list(map(square(my_nums)))
# MAP FUNCTION
def splicer(s):
if len(s) % 2 == 0:
return 'EVEN'
else:
return s[0]
names = ['Andy', 'Eve', 'Sally']
print(list(map(splicer, names)))
# FILTER FUNCTION
def check_even(num):
return num % 2 == 0
mynums = [1, 2, 3, 4, 5, 6, 7]
print(list(filter(check_even, my_nums)))
# LAMBDA EXPRESSION
mynums = [1, 2, 3, 4, 5, 6, 7]
print(map(lambda num: num ** 2, my_nums))
# CHECK EVEN
mynums = [1, 2, 3, 4, 5, 6, 7]
print(list(filter(lambda num: num % 2 == 0, mynums)))
# FILTER NAMES
names = ['Narayanan', 'Gopal', 'Krish']
print(list(map(lambda name: name[0], names)))
|
d68a75bd1e6454913ce19913bb1ebd8cb0b213f1 | Yutong-Wu/Applets | /兔子问题/test11.py | 327 | 3.53125 | 4 | '''
古典问题:有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月
后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
'''
n,a,b=1,0,1
while n<=15:
print('第{}月,有兔子{}只'.format(n,b*2))
a , b = b,a+b
n +=1 |
e811a24b12060fa99d5bd41e6c2b9b3bb8435a3d | saikumarsandra/My-python-practice | /Day-14/super.py | 563 | 4.09375 | 4 | class company():
def __init__(self,company):
self.company=company
def display(self) :
print(f"company name {self.company}")
class emp(company):
def __init__(self, company,emp_name):
super().__init__(company)
self.emp_name=emp_name
def display(self):
print("company name",self.company)
print("company name",self.emp_name)
super().display()#we can use the self method when the method names are same in both parent and child class
ob=emp("cognizant","saikumar")
ob.display() |
9ac4f39aae592f6b20bf6379611d5d6d57615371 | c-u-p/data-science-project | /Data Science Mini Projects/Data Science Mini Proj 2/2.12.py | 431 | 3.65625 | 4 | import matplotlib.pyplot as plt
# defining labels
activities = ['eat', 'sleep', 'work', 'play']
# portion covered by each label
slices = [3, 7, 8, 6]
# color for each label
colors = ['r', 'y', 'g', 'b']
# plotting the pie chart
plt.pie(slices, labels = activities, colors=colors,
startangle=90, shadow = True, explode = (0, 0, 0.1, 0),
radius = 1.2, autopct = '%1.1f%%')
# plotting legend
plt.legend()
# showing the plot
plt.show() |
4515a25705d18a9ef861e909e185d91b1421e6a3 | AndersonAngulo/T07.Angulo_Damian | /angulo/bucle_iteracion/ejer4.py | 330 | 3.96875 | 4 | # factorial de un numero x
import os
#input
x=int(os.sys.argv[1])
#validacion de datos
x_invalido=(x<0)
while(x_invalido):
x=int(input("ingrese valor correcto de x:"))
x_invalido = (x < 0)
#processing
i=1
producto=1
#bucle_while
while(i<=x):
producto *= i
i += 1
#fin_while
print("el factorial de ",x ,"es:",producto)
|
dc0472efb2b093e37439fef9378453da6436bab2 | Gayatri-soni/python-training | /assignment9/q1.py | 411 | 4.03125 | 4 | #q1 Create a circle class and initialize it with radius. Make two methods getArea and getCircumference inside this class.
import math
class circle:
def __init__(self,radius):
self.radius=radius
def getArea(self):
area=math.pi*(self.radius**2)
print(area)
def getCircumference(self):
crcm=2*(math.pi*self.radius)
print(crcm)
c1= circle(7)
c1.getArea()
c2=circle(7)
c2.getCircumference() |
97365121faf64986046f2332192de7463fbf17fc | LalithK90/LearningPython | /privious_learning_code/String/String lstrip() Method.py | 641 | 4.28125 | 4 | str = " this is string example....wow!!! "
print(str.lstrip())
str = "88888888this is string example....wow!!!8888888"
print(str.lstrip('8'))
# Description
#
# The method lstrip() returns a copy of the string in which all chars have been stripped from the beginning of the
# string (default whitespace characters). Syntax
#
# Following is the syntax for lstrip() method −
#
# str.lstrip([chars])
#
# Parameters
#
# chars − You can supply what chars have to be trimmed.
#
# Return Value
#
# This method returns a copy of the string in which all chars have been stripped from the beginning of the string (
# default whitespace characters). |
6215703fcc4305c2f41bf6de9671b295de3f498e | fliper6/PERFIL_PLC | /2º Semestre/SPLN/Testes/spln20190118.py | 6,203 | 3.5625 | 4 | import re
from typing import Collection
import random
## Questão 1 - a)
def max_diff(ex_ints):
dif = []
for n in ex_ints:
for n2 in ex_ints:
dif.append(abs(n - n2))
max = 0
for n in dif:
if n > max:
max = n
print(max)
#max_diff([1,1,3,5,2])
## Questão 1 - b)
def count_char_occur(ex_str):
res = {}
for keys in ex_str:
res[keys] = res.get(keys, 0) + 1
for a in res:
if(a != " "): ## ignorar espaços
print (a + " : " + str(res[a]) + "\n")
#count_char_occur("TESTE DE SPLN")
## Questão 2
def fix_lines(ex_str):
new = re.sub("[-]+[^\n]\n[^\n]", '',ex_str) ## entre a mesma palavra
new2 = re.sub("[^\n]\n[^\n]", ' ',new) ## entre palavras diferentes
print(new2)
#fix_lines("Ele mesmo costumava dizer que \n era simplesmente um egoísta: mas \n nunca, como agora na velhice, as \n generosidades do seu coração ti- \n nham sido tão profundas e largas. \n\n Parte do seu rendimento ia-se- \n -lhe por entre os dedos, espar- \n samente, numa caridade enterne- \n cida.")
## Questão 3 - a)
def upper_case(letter):
print(letter)
return str(letter.group(0).upper())
def fix_sent_start(ex_str):
new = re.sub("[.?!]+[\w\W]*?([a-z])",upper_case,ex_str) ## entre a mesma palavra
print(new[0].upper() + new[1:])
## [1:] - tudo menos primeiro char
## [-1:] - apenas último char
## [:-1] - tudo menos último char
## [:1] - apenas primeiro char
tmin = "sou uma frase. peepo pog wow. les go. \n\nparagrafo? who?"
fix_sent_start(tmin)
## Questão 3 - b)
def fix_start_stats(ex_str):
counts = dict()
words_nice = re.findall(r'\W?([\w]*)\W?', ex_str)
for w in words_nice:
if w != "":
if w in counts:
counts[w] += 1
else:
counts[w] = 1
for k in sorted(counts):
print("%s: %s" % (k, counts[k]))
tg = "Eu sou Filipa Santos. Vivo com o Rui Santos."
#fix_start_stats(tg)
## A partir da análise de um grande texto (tg) com vários nomes próprios, siglas, etc, poderiamos ver quais palavras ocorriam mais vezes com letra maiúscula e, a partir desta informação,
## poríamos essas mesmas palavras que aparecem em tmin com maiúscula também.
## Questão 4
def lookup_noticias(nome, dic, notis):
words = []
for n in notis:
word1 = re.findall(r'\W?([\w]*)\W?', n)
words = words + word1
nomes = nome.split(" ")
ocurrencias = 0
palavras_surround = []
indice = 0
for w in words:
for n in nomes: ##vai apanhar tanto "José" como "Mourinho" separadamente
if n in w:
ocurrencias +=1
for x in range(1, 6): ##para cada ocurrência, vai buscar as palavras 5 posições antes e 5 depois, se existirem
if words[indice-x]: ##verifica se existe
palavras_surround.append(words[indice-x])
if words[indice-x]: ##verifica se existe
palavras_surround.append(words[indice+x])
indice+=1
## a)
pal_10 = random.sample(palavras_surround, 10)
print(pal_10) ##vai buscar 10 palavras aleatórias
somatório = 0
for p in pal_10:
if p in dic: ## nem todas as palavras estão no dicionário
somatório += dic[p]
else: ## se a palavra não existir, assumimos como neutra
somatório += 0
## b)
popularidade = somatório / ocurrencias
print(popularidade)
n = ["Carlo Ancelotti está de volta ao banco do Real Madrid mas, garante o Telegraph, o treinador a regressar poderia ter sido… José Mourinho. Garante o jornal inglês que Florentino Pérez, presidente dos espanhóis e que mantém uma excelente relação com Mourinho, sondou o português há alguns dias a fim de aferir a possibilidade de substituir Zinedine Zidane no comando dos merengues. Tudo isto terá acontecido antes de o italiano dar o ‘sim’ à proposta do Real Madrid. Mourinho, porém, declinou o convite e sublinhou estar «extremamente entusiasmado» com o novo projeto que abraçou na Roma. O português esteve no Santiago Bernabéu entre 2010 e 2013, tendo conseguido quebrar a hegemonia do Barcelona, então de Pep Guardiola: venceu uma La Liga, uma Taça do Rei e uma Supertaça espanhola.",
"O legado de Aurélio Pereira, o ‘senhor formação’, foi hoje enaltecido por diversas figuras do futebol português, como o antigo futebolista Paulo Futre, o treinador José Mourinho e o presidente do Sporting, Frederico Varandas."]
d = { "Sporting": 0.5, "treinador": 0.1, "regressar": -0.1, "jornal": -0.2, "inglês": 0 }
#lookup_noticias("José Mourinho",d,n)
## Questão 5
def find_corresp(texto1,texto2):
dic = {}
t1_p = re.findall(r'\W?([\w]*)\W?', texto1)
t2_p = re.findall(r'\W?([\w]*)\W?', texto2)
for x in range(0, len(t1_p) - 1):
if t1_p[x] != t2_p[x]:
dic[t1_p[x]] = t2_p[x]
print(dic)
t1 = "As inundações provocaram graves damnos na pharmácia. A Philipa foi vítima desses damnos."
t2 = "As inundações provocaram graves danos na farmácia. A Filipa foi vítima desses danos."
#find_corresp(t1,t2)
## Questão 6
## como os returns que o estão no ex do teste dão erro, pus uma função que dá return à mesma
accoes = [
(r'És um (\w+)', [ ## expressão regular
lambda x: f1(x), ## ação
lambda x: f2(x), ## ação
'Quem diz é quem é!' ## constante
]),
(r'(\w+) em inglês', [
lambda x: tradutor(x) ]
)
]
def f1(x):
print(x + " és tu!")
def f2(x):
print("Tu é que és " + x)
dic_pt_en = { "carro" : "car", "livro" : "book", "sapato" : "shoe"}
## a)
def tradutor(x):
print(dic_pt_en[x.lower()])
## b)
def bot_responde(accoes, ex_str):
for (acc, f) in accoes:
if re.match(acc, ex_str): ## ação correta
newString = re.findall(acc, ex_str)[0]
action = random.choice(f) ## escolhe um randomly
if callable(action): ## ação
action(newString)
else: ## constante
print(action)
#bot_responde(accoes, "Carro em inglês")
#bot_responde(accoes, "És um burro") |
80c89ccffdbe866c0d3d2493fc97377e88763c58 | nareshkbojja/machinelearning | /gas.py | 2,577 | 3.8125 | 4 |
# coding: utf-8
# # **Predicting Gas Consumption Value using Linear Regression**
# ## Import Libraries
# #### _Import the usual libraries_
# In[131]:
import pandas as pd , numpy as np, pickle
import matplotlib.pyplot as plt,seaborn as sns
#get_ipython().run_line_magic('matplotlib', 'inline')
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn import metrics
#from pylab import rcParams
import seaborn as sb
#rcParams['figure.figsize'] = 7, 7
sb.set_style('darkgrid')
# ## Dataset Information
# #### _Gas_
#
#
# ## Get the Data
#
# ** Use pandas to read petrol_consumption.csv as a dataframe called gas.**
# In[128]:
gas = pd.read_csv("petrol_consumption.csv")
print(gas.shape)
gas.head()
#print(gas.describe())
# ## Data Cleansing
# #### if there, _removing the special chars & converting the corresponding object attributes to float_
# In[120]:
gas.columns = [ 'gas_tax','avg_income','Paved_highways','pop_dl','consumption']
#gas.info()
# ## Exploratory Data Analysis
#
# In[121]:
g = sns.lmplot(x="gas_tax", y="consumption", data=gas)
g = sns.lmplot(x="avg_income", y="consumption", data=gas)
g = sns.lmplot(x="Paved_highways", y="consumption", data=gas)
g = sns.lmplot(x="pop_dl", y="consumption", data=gas)
# # Train Test Split
#
# ** Split your data into a training set and a testing set.**
# In[122]:
droplst = ['Paved_highways','avg_income','consumption']
X = gas.drop(droplst,axis=1)
y = gas['consumption']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# # Train a Model
#
# Now its time to train a Linear Regression.
#
# **Call the LinearRegression() model from sklearn and fit the model to the training data.**
# In[132]:
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
scor = metrics.r2_score(y_test, y_pred)
print("SCORE=",scor)
predictiondf = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
print(predictiondf)
print('Mean Absolute Error:', metrics.mean_absolute_error(y_test, y_pred))
print('Mean Squared Error:', metrics.mean_squared_error(y_test, y_pred))
print('Root Mean Squared Error:', np.sqrt(metrics.mean_squared_error(y_test, y_pred)))
g = sns.lmplot(x="Actual", y="Predicted", data=predictiondf)
# plt.scatter(y_test,y_pred,c='m')
# plt.xlabel('Y Test')
# plt.ylabel('Predicted Y')
filename = 'gaslr.pkl'
pickle.dump(model, open(filename, 'wb'))
print("PICKLE FILE GENERATED SUCCESSFULLY\n\n\n\n")
print("PROGRAM ENDS SUCCESSFULLY")
|
4f98bdffa6d4f8c831719480be67731a63ddf25a | nsarlin/ml_simple | /Utils.py | 1,274 | 3.6875 | 4 | import numpy as np
import numbers
def sigmoid(z):
"""
The sigmoid function is used to uniformally distribute values from
[-inf;+inf] to [0;1].
z can be a matrix, a vector or a scalar
"""
return 1.0/(1.0+np.exp(-z))
def sigmoid_grad(z):
"""
Gradient of the sigmoid function
"""
return np.multiply(sigmoid(z), 1-sigmoid(z))
def add_bias(X):
"""
Adds either a column of ones if X is a matrix, or a single one
if a is a vector.
"""
# matrix
try:
return np.insert(X, 0, 1, axis=1)
# vector
except IndexError:
return np.insert(X, 0, 1)
def label_to_bitvector(lbl, nb_classes):
"""
Converts a lbl to a bitvector where the lblth element is 1 and the others 0
"""
if isinstance(lbl, numbers.Real):
return np.array([1 if i == lbl else 0 for i in range(nb_classes)])
else:
raise TypeError
def labels_to_bitmatrix(lbls, nb_classes):
"""
Converts a vector of labels to a matrix made of bitvectors.
"""
if isinstance(lbls, np.ndarray) and \
(len(lbls.shape) == 1 or lbls.shape[1] == 1):
return np.array([label_to_bitvector(int(lbl)-1, nb_classes) for
lbl in lbls])
else:
raise TypeError
|
9bb29979de08f4480fb2cb7da9504d71d856015f | kelsadita/Algorithms | /sorting/merge/inversion.py | 1,219 | 3.953125 | 4 | # A version of inversions pair finding algorithm designed on the basis of merge sort algorithm
# Courtesy : Tim Roughgarden (coursera: Algorithm design and analysis 1)
import math
def merge_sort(a, p, r):
if p < r:
q = int(math.floor((p + r) / 2))
merge_sort(a, p, q)
merge_sort(a, q + 1, r)
if q != len(a) - 1:
merge(a, p, q, r)
def merge(a, p, q, r):
global inv_count
# creating left and right sub-arrays
left = a[p:q+1]
right = a[q+1:r+1]
# to maintain sentinel (you need to feel it!)
# the logic can be understood through the program flow
left.append(100000000)
right.append(100000000)
# Dunno but removing this gives array index out of bound
if r == len(a):
r = r - 1
# comparing and merging routine
i = 0
j = 0
for k in range(p, r + 1):
if left[i] <= right[j]:
a[k] = left[i]
i += 1
else:
# counting the inversions
if i < len(left) - 1:
inv_count += (len(left) - i - 1)
a[k] = right[j]
j += 1
f = open('IntegerArray.txt', 'r')
arr = f.read().splitlines()
arr = [int(a) for a in arr]
inv_count = 0
# other test case
#arr = [2, 4, 1, 3, 5]
#arr = [5, 3, 4, 8, 2,1, 4, 8, 9,10, 45,34, 21, 55, 67, 89, 31]
merge_sort(arr, 0, len(arr))
print inv_count |
97f08997d92401642d935082f8243365dd544790 | stimko68/daily-programmer | /challenge_anwers/168_easy_2.py | 947 | 4.28125 | 4 | """
String Index
Given an input string and a series of integers, create indexes for each
valid word in the string and then return a string based on the given
integers.
Example:
Input string: "The lazy cat slept in the sunlight."
Input ints: 1 3 4
Output: "The cat slept"
"""
import re
input_string = "...You...!!!@!3124131212 Hello have this is a --- " \
"string Solved !!...? to test @\n\n\n#!#@#@%$**#$@ " \
"Congratz this!!!!!!!!!!!!!!!!one ---Problem\n\n"
indexes = [12, -1, 1, -100, 4, 1000, 9, -1000, 16, 13, 17, 15]
def parse_string(int_list, in_string):
answer = ''
cleaned_input = []
strings = re.findall(r'[a-zA-Z0-9]+', in_string)
for i in int_list:
if 0 < i <= len(strings):
cleaned_input.append(strings[i-1])
for j in cleaned_input:
answer += j + " "
return answer
if __name__ == "__main__":
print parse_string(indexes, input_string) |
537814de9e9fa13b06fbf81c0987e24c5eeb75eb | rbuerki/reference-code-python-programming | /algorithms/1_algorithmic_toolbox/week1_programming_challenges/2_maximum_pairwise_product/submission.py | 711 | 4 | 4 | # python3
def max_pairwise_product_fast(numbers):
"""My implementation."""
numbers = [int(x) for x in numbers]
n = len(numbers)
index_1 = 0
for index in range(n):
if numbers[index] > numbers[index_1]:
index_1 = index
if index_1 == 0:
index_2 = 1
else:
index_2 = 0
for index in range(n):
if index != index_1:
if numbers[index] > numbers[index_2]:
index_2 = index
max_product = numbers[index_1] * numbers[index_2]
return max_product
if __name__ == "__main__":
input_n = int(input())
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_product_fast(input_numbers))
|
2312bf2cdfbb259e671b0cc563c6a14a40f8c482 | syurskyi/Algorithms_and_Data_Structure | /_algorithms_challenges/w3resource/W3resource-exercises-master/16. return diff between 17.py | 185 | 3.90625 | 4 | def difference():
n = int(input("Enter a number to calc diff from 17, double if its over: "))
if n > 17:
print((n - 17) * 2)
else:
print(17 - n)
difference() |
135c200d744ce6b8c1ef93e781ad13061930572b | lissity/AoC | /2018/Day2/main.py | 824 | 3.75 | 4 |
# First star
file = open("Day2/input.txt", 'r')
two_letters = 0
three_letters = 0
for line in file:
found_two = False
found_three = False
for char in line:
char_count = line.count(char)
if (char_count == 2 and found_two == False):
two_letters += 1
found_two = True
if (char_count == 3 and found_three == False):
three_letters += 1
found_three = True
file.close()
print('Checksum: ' + str(two_letters) + " * " + str(three_letters) + " = " + \
str(two_letters*three_letters))
# Second star
with open('Day2/input.txt') as f:
lines = f.read().splitlines()
for x in lines:
no_diff = 0
for y in lines:
if len([i for i in range(len(x)) if x[i] != y[i]]) == 1:
print('whoa')
print(x + " " + y)
|
09c0f9fde75fe93ed4d8fa8311df983462ef2e90 | rubinshteyn89/Class_Spring | /Python/Lab_7/question3.py | 1,983 | 4.09375 | 4 | __author__ = 'ilya_rubinshteyn'
import os
import random
import sys
def Rando():
Y = (int(random.random()*100))
return Y
def guess():
y = Rando()
print("The computer generated a random number between 0 to 100.")
print("For testing purposes,",y," is the random number")
tries = 0
turned_on = True
while turned_on:
print("")
x = input("Please enter your guess: ")
tries = tries + 1
digit_check = x.isdigit()
if digit_check:
x = int(x)
if x != y:
print("Wrong!")
print("")
if x > y:
print(x," is greater than the random number, try again.")
print("")
else:
print(x," is smaller than the random number, try again.")
print("")
elif x == y:
print("You are correct!")
print("\nIt took you ",tries," tries to guess ",y)
break
else:
print("\nPlease enter a valid digit.")
def new_game():
while True:
print("\nIf you would like to start a new game, type \'y' or \'Y'. Type \'n' or \'N' to quit.")
answer = input(">>> ")
ans_len = len(answer)
if answer == 'y' or answer == 'Y':
print("\nStarting new game...\n")
guess()
elif answer == 'n' or answer == 'N':
print("Quitting application...")
quit()
elif answer.isalpha() == False or ans_len != 1:
print("Invalid answer. Please Try again.")
else:
print("Invalid answer. Please Try again.")
if __name__ == '__main__':
if sys.platform == 'darwin' or sys.platform == 'linux2':
os.system('clear')
print('')
try:
while True:
guess()
new_game()
except(KeyboardInterrupt):
print("\nQuit via keyboard interrupt.\n")
|
e5eb7b12d6758a35aab329d101d1d30f7f007b41 | Ale1503/Launchpad-Learning- | /Trivia.py | 2,092 | 4.0625 | 4 | def check_keep_playing(game):
keep_playing = input("Do you want to try the other game? -> (Yes/No)")
if keep_playing == "No":
print("Well, it was a pleasure!")
if keep_playing == "Yes":
if game == 1:
game = 2
run_game(game)
elif game == 2:
game = 1
run_game(game)
def run_game(game):
points = 0
#First game
if game == 1:
print ("These are all social studies questions! Let's beging! ")
g1_first = input ("What is the name of current president of Costa Rica? ->(Carlos Alvarado/Marito Mortadela/Jose Figueres) "
if g1_first == "Carlos Alvarado:
print("Correct!")
points = points+1
else:
print("Incorrect, it is Carlos Alvarado")
g1_second = input("When did Guanacaste become a new Costa Rican province? ->(1820/1921/1824) ")
if g1_second == "1824":
print("Correct!")
points = points + 1
else:
print("Incorrect, it was in 1824")
g1_third = input ("What was the name of the president who led the Costa Rican army against William Walker? -> (Jose Figueres/Braulio Carillo/Jose Mora Porras) ")
if g1_third == "Jose Mora Porras":
print("Correct!")
points = points +1
else:
print("Incorrect, it was Jose Mora Porras")
g1_fourth = input("Where do you tell poeple to go in Costa Rica when you are mad? ->(Jacó Beach/Fuente de la Hispanidad/El Gollo ")
if g1_fourth == "Fuente de la Hispanidad"
print("correct!")
points = points +1
else:
print("Incorrect, it was Fuente de la Hispanidad")
print ("You got",points,"/ 4", "points")
check_keep_playing(game)
#Second game
elif game == 2:
print ("Here we are, let´s beging")
else:
print ("That is not an option, but ")
#greeting and facts about the player
print("Hello! This is a really fun game that you are going to enjoy ")
name = input("Would you tell me your name? ")
print ("What a nice name ", name, "nice to meet you!")
age = int (input("How old are you? "))
#Start of the game
print("Ok, now I am going to let you choose the game you want to play")
game = int(input("Choose 1 or 2 -> "))
run_game(game)
check_keep_playing(game) |
dd5a9eb2e5331c25087010843c12c5eeb6491727 | agerista/HR_Python | /algorithms/implementation/day_of_the_programmer.py | 1,532 | 4.21875 | 4 | def solve(year):
"""Marie invented a Time Machine and wants to test it by time-traveling to
visit Russia on the Day of the Programmer (the 256th day of the year) during
a year in the inclusive range from 1700 to 2700.
From 1700 to 1917, Russia's official calendar was the Julian calendar; since
1919 they used the Gregorian calendar system. The transition from the Julian
to Gregorian calendar system occurred in 1918, when the next day after January
31 was February 14th. This means that in 1918, February 14th was the 32nd day
of the year in Russia.
In both calendar systems, February is the only month with a variable amount
of days; it has 29 days during a leap year, and 28 days during all other years.
In the Julian calendar, leap years are divisible by 4; in the Gregorian calendar,
leap years are either of the following:
Divisible by 400.
Divisible by 4 and not divisible by 100.
solve(2017)
>>> 13.09.2017
solve(2016)
>>> 12.09.2016
"""
if year <= 1917:
if year % 4 == 0:
return "12.09." + str(year)
else:
return "13.09." + str(year)
elif year == 1918:
return "26.09.1918"
elif year > 1918:
if year % 400 == 0:
return "12.09." + str(year)
if year % 4 == 0 and year % 100 != 0:
return "12.09." + str(year)
else:
return "13.09." + str(year)
year = int(raw_input().strip())
result = solve(year)
print(result)
|
734a23985c9663d9208004b11c9d216e5a3af595 | Guochiuan/NLP | /HW-3/hw3_skeleton_word.py | 8,413 | 3.875 | 4 | import math, random
from typing import List, Tuple
import collections
################################################################################
# Part 0: Utility Functions
################################################################################
def start_pad(n):
''' Returns a padding string of length n to append to the front of text
as a pre-processing step to building n-grams '''
return ['~'] * n
Pair = Tuple[str, str]
Ngrams = List[Pair]
def ngrams(n, text:str) -> Ngrams:
text=text.strip().split()
#print(text)
''' Returns the ngrams of the text as tuples where the first element is
the n-word sequence (i.e. "I love machine") context and the second is the word '''
padding = start_pad(n)
padded_text = padding+text
result = []
#print(text)
for i in range(len(text)):
# flag = False
# for j in range(i,i+n):
# if len(padded_text[j]) != 1:
# break
# else:
# flag = True
# if flag:
# result.append((''.join(tuple(padded_text[i:i+n])),text[i]))
# else:
result.append((' '.join(tuple(padded_text[i:i+n])),text[i]))
#print(result)
return result
def create_ngram_model(model_class, path, n=2, k=0):
''' Creates and returns a new n-gram model trained on the path file '''
model = model_class(n, k)
with open(path, encoding='utf-8') as f:
model.update(f.read())
return model
################################################################################
# Part 1: Basic N-Gram Model
################################################################################
class NgramModel(object):
''' A basic n-gram model using add-k smoothing '''
def __init__(self, n, k):
self.n = n
self.k = k
self.vocab = set()
self.count = collections.defaultdict(int)
self.ngram = collections.defaultdict(int)
def get_vocab(self):
''' Returns the set of words in the vocab '''
return self.vocab
def update(self, text:str):
''' Updates the model n-grams based on text '''
res = ngrams(self.n,text)
#print(res)
# update occurance of a context
#print(res)
for context,t in res:
self.count[context] += 1
# update ngram dictionary
for pair in res:
self.ngram[pair] +=1
# update vocab
text = text.strip().split()
for word in text:
self.vocab.add(word)
def prob(self, context:str, word:str):
''' Returns the probability of word appearing after context '''
if context not in self.count and self.k == 0:
return 1.0/len(self.get_vocab())
#print(self.ngram[(context,char)])
#print(self.count[context])
# print((context,word))
# print(context)
# print(self.ngram)
# print(self.count)
#print("in prob calculation")
#print((context,word, self.k))
if (context,word) not in self.ngram:
value1 = 0.0
else:
value1 = self.ngram[(context,word)]
if context not in self.count:
value2 = 0.0
else:
value2 = self.count[context]
return (value1 + self.k) / (value2 + self.k*len(self.get_vocab()) )
def random_word(self, context):
''' Returns a random word based on the given context and the
n-grams learned by this model '''
# random.seed(1)
rand_num = random.random()
sorted_vocab = sorted(self.get_vocab())
prob = 0
# for i=0
#print(context, sorted_vocab)
if rand_num< self.prob(context,sorted_vocab[0]):
return sorted_vocab[0]
for i in range(1,len(sorted_vocab)):
prob += self.prob(context,sorted_vocab[i-1])
prob_curr_char = prob + self.prob(context,sorted_vocab[i])
if prob <= rand_num < prob_curr_char:
return sorted_vocab[i]
else:
continue
return ''
def random_text(self, length):
''' Returns text of the specified word length based on the
n-grams learned by this model '''
starting_context = ['~'] * self.n
starting_context = " ".join(starting_context)
generated_text = ""
current_context = starting_context
#print(length, self.n)
for i in range(length):
random_char = self.random_word(starting_context)
#print("generating word no", i, random_char)
current_context += " " + random_char
generated_text = generated_text + " " + random_char
#print(current_context)
new_list = current_context
temp_list = new_list.split(" ")
#current_context = current_context.strip().split()
starting_context = temp_list[i+1:i+1+self.n]
#print(starting_context)
if '' in starting_context:
starting_context = "".join(starting_context)
else:
starting_context = " ".join(starting_context)
#starting_context = current_context[i+1:i+1+self.n]
return generated_text[1:]
def perplexity(self, text):
''' Returns the perplexity of text based on the n-grams learned by
this model '''
result = 0
res = ngrams(self.n,text)
#print(res)
text=text.strip().split()
#print(text)
count_ngrams_dict = collections.Counter(res)
for context,t in res:
#print(context,t)
c_prob = self.prob(context,t)
if c_prob == 0.0:
result = float('inf')
return result
result += math.log(self.prob(context,t))
#print(result,math.exp(result))
result = math.exp(-result/len(text))
#result = 1.0/math.pow(2,result)
return result
################################################################################
# Part 2: N-Gram Model with Interpolation
################################################################################
class NgramModelWithInterpolation(NgramModel):
''' An n-gram model with interpolation '''
def __init__(self, n, k):
self.n = n
self.k = k
self.count = collections.defaultdict(int)
self.ngram = collections.defaultdict(int)
self.vocab_set = set()
#self.lmbda = [1/(n+1)]*(n+1)
self.lmbda = [0.1,0.3,0.6]
def get_vocab(self):
return self.vocab_set
def update(self, text:str):
res = []
# update occurance of a context
for i in range(self.n+1):
#print(ngrams(i,text))
res.extend(ngrams(i,text))
for context,t in res:
self.count[context] += 1
# update ngram dictionary
for pair in res:
self.ngram[pair] +=1
# update vocab
text = text.strip().split()
for char in text:
self.vocab_set.add(char)
def prob(self, context:str, word:str):
if context not in self.count and self.k == 0:
return 1.0/len(self.get_vocab())
prob = 0
context = context.split(" ")
for i in range(self.n+1):
#print('contextsad',context)
if len(context) == 1:
new_context = ''.join(context)
else:
new_context = " ".join(context[self.n-i:self.n])
#print(new_context,'da',len(new_context))
if (new_context,word) not in self.ngram:
value1 = 0.0
else:
value1 = self.ngram[(new_context,word)]
if new_context not in self.count:
value2 = 0.0
else:
value2 = self.count[new_context]
#print('context',new_context)
#print("vocab",self.get_vocab())
temp = self.lmbda[i]*((value1 + self.k)/(value2+self.k*len(self.get_vocab())))
prob += temp
return prob
################################################################################
# Part 3: Your N-Gram Model Experimentation
################################################################################
if __name__ == '__main__':
pass |
d7223d045c4a663ba691719810ba9438100022ab | lokivmsl98/python | /pos or neeg.py | 97 | 3.796875 | 4 | l=int(input())
if(l>0):
print("Positive")
elif(l<0):
print("Negative")
else:
print("Zero")
|
ac36414acd860ecc6dbc7cc5838cace82f430c6f | VijayaR151852/Hackerrank | /Algorith_BubbleSort.py | 309 | 3.5 | 4 | def bs(a): # a = name of list
b=len(a)-1 # minus 1 because we always compare 2 adjacent values
for x in range(b):
for y in range(b-x):
if a[y]>a[y+1]:
a[y],a[y+1]=a[y+1],a[y]
return a
a=[32,5,3,6,7,54,87]
bs(a)
|
b39b9b9f8ba688a8639e60b2b5e0d06ccafead28 | sergzorg/pythonhillel | /DZ_1/5.py | 189 | 4 | 4 | #!/usr/bin/python3
##by Sergey Zhukanov
dict_one = { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
dict_two = { 'a': 6, 'b': 7, 'z': 20, 'x': 40 }
print(set(dict_one.keys()).intersection(set(dict_two.keys())))
|
51494b2b7182ad866218499953546eb6f4ec9af7 | SBazelais/ATM-application | /Transactions.py | 1,081 | 3.765625 | 4 |
def withdraw(amount):
"""function to add elements to withdraw text file"""
tran_list = [amount]
f = open('withdraw_tran.txt', 'a')
space = '\n'
for item in tran_list:
f.write(item + space)
f.close()
def deposit(amount):
"""function to add elements to deposit text file"""
tran_list = [amount]
f = open('deposit_tran.txt', 'a')
space = '\n'
for item in tran_list:
f.write(item)
f.close()
def withdraw_net():
"""function sums up elements in withdraw text file"""
f = open('withdraw_tran.txt', 'r')
file = f.readlines()
new_list = []
for data in file:
data = data.strip('\n')
print(data)
data_2 = float(data)
new_list.append(data_2)
return sum(new_list)
def deposit_net():
"""function sums up elements in withdraw text file"""
f = open('deposit_tran.txt', 'r')
file = f.readlines()
new_list = []
for data in file:
data = data.strip('\n')
data_2 = float(data)
new_list.append(data_2)
return sum(new_list)
|
f23e9eceaf0e942e1f11178367e1e9d4e44c571e | Mantvydas-data/pands-problem-sheet | /secondstring.py | 348 | 3.953125 | 4 | #A program that asks user to input a string and outputs every second letter in reverse order.
#Author: Mantvydas Jokubaitis
sentence = input("Please input a sentence: ")
example = "The quick brown fox jumps over the lazy dog."
print("Example sentence: ", example, "Every second letter in reverse order: ", example[::-2])
print("Your sentence: ", sentence[::-2]) |
1807440261891f52c2481b57be4c18bf0f80d364 | Hackman9912/PythonCourse | /Curriculum/My Git Stuff/05PythonProgramming/Additional Stuff/Medium Stuff/FileInteraction/filepracticeread.py | 383 | 3.875 | 4 | # This program reads and displays the contents of the philosophers.txt file
def main():
# Open the file named philosophers.txt
f = open('philosophers.txt', 'r')
# Read the files contents
f_contents = f.read()
# Close the file
f.close()
# Print the data that was read into memory
print(f_contents)
# Call the main function
main() |
89070b8ff30187306732fa9e24fa24f32d6cc44f | DayGitH/Python-Challenges | /DailyProgrammer/DP20130111C.py | 1,718 | 3.6875 | 4 | """
[01/11/13] Challenge #116 [Hard] Maximum Random Walk
https://www.reddit.com/r/dailyprogrammer/comments/16dbyh/011113_challenge_116_hard_maximum_random_walk/
# [](#HardIcon) *(Hard)*: Maximum Random Walk
Consider the classic random walk: at each step, you have a 1/2 chance of taking a step to the left and a 1/2 chance of
taking a step to the right. Your expected position after a period of time is zero; that is the average over many such
random walks is that you end up where you started. A more interesting question is what is the expected rightmost
position you will attain during the walk.
*Author: thePersonCSC*
# Formal Inputs & Outputs
## Input Description
The input consists of an integer n, which is the number of steps to take (1 <= n <= 1000). The final two are double
precision floating-point values L and R which are the probabilities of taking a step left or right respectively at each
step (0 <= L <= 1, 0 <= R <= 1, 0 <= L + R <= 1). Note: the probability of not taking a step would be 1-L-R.
## Output Description
A single double precision floating-point value which is the expected rightmost position you will obtain during the walk
(to, at least, four decimal places).
# Sample Inputs & Outputs
## Sample Input
walk(1,.5,.5)
walk(4,.5,.5)
walk(10,.5,.4)
## Sample Output
walk(1,.5,.5) returns 0.5000
walk(4,.5,.5) returns 1.1875
walk(10,.5,.4) returns 1.4965
# Challenge Input
What is walk(1000,.5,.4)?
## Challenge Input Solution
(No solution provided by author)
# Note
* Have your code execute in less that 2 minutes with any input where n <= 1000
* I took this problem from the regional ACM ICPC of Greater New York.
"""
def main():
pass
if __name__ == "__main__":
main()
|
e9956b768784a801ced97be6ca9a72e68e4997d8 | PdxCodeGuild/Intro-to-Computer-Programming | /example-files/boolgame.py | 2,217 | 4.15625 | 4 | #!/usr/bin/env python
"""
PDX Code Guild Curriculum. Boolean Game.
"""
__author__ = "Christopher Jones"
__copyright__ = "Copyright 2016, PDX Code Guild"
__version__ = "0.1"
import random
bools = {
'not False': not False,
'not True': not True,
'True or False': True or False,
'True or True': True or True,
'False or True': False or True,
'False or False': False or False,
'True and False': True and False,
'True and True': True and True,
'False and True': False and True,
'False and False': False and False,
'not (True or False)': not (True or False),
'not (True or True)': not (True or True),
'not (False or True)': not (False or True),
'not (False or False)': not (False or False),
'not (True and False)': not (True and False),
'not (True and True)': not (True and True),
'not (False and True)': not (False and True),
'not (False and False)': not (False and False),
'1 != 0': 1 != 0,
'1 != 1': 1 != 1,
'0 != 1': 0 != 1,
'0 != 0': 0 != 0,
'1 == 0': 1 == 0,
'1 == 1': 1 == 1,
'0 == 1': 0 == 1,
'0 == 0': 0 == 0,
}
def random_question():
question = random.choice(list(bools.keys()))
answer = bools[question]
return question, answer
def game():
score = 0
print('Welcome to the boolean value game!')
print('Type (T)rue or (F)alse for each question.')
while len(bools) > 0:
left = len(bools)
print("You have answered {score} of 26 questions correctly.".format(score=str(score)))
print("There are {left} questions left.".format(left=str(left)))
question = random_question()
player_answer = input("What is the value of {q}?: ".format(q=question[0]))
if player_answer.lower() == "t":
player_answer = 'True'
elif player_answer.lower() == 'f':
player_answer = 'False'
if player_answer == str(question[1]):
print("********** That is correct! **********")
del bools[question[0]]
score += 1
else:
print("Sorry, that is not correct.")
game()
|
2c4ba9ad889876cf81ba3933a76d832542c77ae3 | ventisk1ze/leetcode | /smaller_then_current.py | 155 | 3.78125 | 4 | nums = [8,1,2,2,3]
res = []
for num in nums:
count = 0
for n in nums:
if num > n:
count += 1
res.append(count)
print(res) |
dc11e0b4564d1f26088b267a5425762fe189ede2 | Sebastian-WR/Python-Exercises | /ses3/Mandatory_Handin_Sebastian_Wulff_Rasmussen.py | 3,780 | 4.34375 | 4 | # 1: Model an organisation of employees, management and board of directors in 3 sets.
board = ['Benny','Hans', 'Tine', 'Mille', 'Torben', 'Troels', 'Søren']
management = ['Tine', 'Trunte', 'Rane']
employees = ['Niels', 'Anna', 'Tine', 'Ole', 'Trunte', 'Bent', 'Rane', 'Allan', 'Stine', 'Claus', 'James', 'Lars']
# who in the board of directors is not an employee?
# who in the board of directors is also an employee?
def notEmployee(list1, list2):
notIn = []
totsIn = []
for person in list1:
if person in list2:
totsIn.append(person)
else:
notIn.append(person)
print("Theese people are only board and not employees: " + str(notIn))
print("Theese people are also an employee: " + str(totsIn))
notEmployee(board, employees)
# how many of the management is also member of the board?
def alsoInTheBoard(list1, list2):
notIn = []
totsIn = []
for person in list1:
if person in list2:
totsIn.append(person)
else:
notIn.append(person)
return print(str(len(totsIn)) + ": " + totsIn[0])
alsoInTheBoard(management, board)
# All members of the managent also an employee
def alsoEmployee(list1, list2):
result = all(person in list1 for person in list2)
if result:
print("Yes! all the people from management is also an employee!")
else:
print("No... sadly they're to fancy to also be an employee all of them")
alsoEmployee(employees, management)
# All members of the management also in the board?
def alsoBoardMember(list1, list2):
result = all(person in list1 for person in list2)
if result:
print("Yes! all the people from management is also part of the board!")
else:
print("No... sadly they're not all good enough to be part of the board..")
alsoBoardMember(management, board)
# Who is an employee, member of the management, and a member of the board?
def alsoInTheBoard(list1, list2, list3):
notIn = []
totsIn = []
for person in list1:
if person in list2 and list3:
totsIn.append(person)
else:
notIn.append(person)
return print("Yes!: " + totsIn[0] + " is part of all the departments!")
alsoInTheBoard(employees, management, board)
# Who of the employee is neither a memeber or the board or management?
def notPartOfAll(list1, list2, list3):
notIn = []
totsIn = []
for person in list1:
if person in list2 and list3:
totsIn.append(person)
else:
notIn.append(person)
return print("Theese employees are not part of all departments" + str(notIn))
notPartOfAll(employees, management, board)
# 2: Using a list comprehension create a list of tuples from the folowing datastructure
oldList = {'a': 'Alpha', 'b' : 'Beta', 'g': 'Gamma'}
tupList = [item for item in oldList.items()]
print(tupList)
# 3: From theese 2 sets:
list1 = {'a', 'e', 'i', 'o', 'u', 'y'}
list2 = {'a', 'e', 'i', 'o', 'u', 'y', 'æ' ,'ø', 'å'}
Union = list1.union(list2)
print(Union)
symmetricDiff = list1.symmetric_difference(list2)
print(symmetricDiff)
diff = list1.difference(list2)
print(diff)
disJoint = list1.isdisjoint(list2)
print(disJoint)
# 4: Date Decoder
dateDecoder = {
"JAN": 1,
"FEB": 2,
"MAR": 3,
"APR": 4,
"MAJ": 5,
"JUN": 6,
"JUL": 7,
"AUG": 8,
"SEP": 9,
"OKT": 10,
"NOV": 11,
"DEC": 12
}
strD = "8-MAR-85"
def dateDec(str, dateDecoders):
splitTup = str.split("-")
if int(splitTup[2]) > 21:
splitTup[2] = 1900 + int(splitTup[2])
else:
splitTup[2] = 2000 + int(splitTup[2])
tupTup = (splitTup[2], dateDecoders[splitTup[1]], int(splitTup[0]))
return tupTup
print(dateDec(strD, dateDecoder)) |
22fecd51a6c0d2736dc02de440b360fcbcf11a9e | leoscalesi/Mini-Games | /mini juegos1.py | 12,491 | 3.734375 | 4 | import tkinter as tk
ventana=tk.Tk()
ventana.title(" MINI GAMES ")
ventana.geometry('1200x720')
ventana.resizable(False,False)
import math
def calculadora():
pisos=int(piso.get())
metros=2.5*pisos
vf=math.sqrt(2*9.8*metros)
t=round(vf/9.8,2)
km=vf/1000
kmh=round(km/0.0002777778,2)
resultado.config(text=" La velocidad con la que llego al piso fue de " + str(kmh) + " km/h " )
tiempo.config(text= " y tardo " + str(t)+ " segundos en llegar al suelo ")
def calculadorap():
metros=float(prof.get())
presion=1000*9.8*metros+101300
presionatm=round(presion/101300,2)
resultado1.config(text=" La presion es de "+ str(presionatm) + " atm ")
titulo=tk.Label(text= " CALCULADORA DE IRRELEVANCIAS ", fg="#ff0000")
titulo.place(x=80, y=5)
opcion=tk.Label(text=" Desde que piso cayo el cuerpo? ")
opcion.place(x=100, y=40)
piso=tk.Entry()
piso.place(x=100,y=60)
piso.config(background="black",fg="#ffff00")
calculo=tk.Button(text= " Calcular ", command=calculadora, fg="#0000ff")
calculo.place(x=100,y=100)
resultado=tk.Label(text=" El resultado es ")
resultado.place(x=100, y=136)
tiempo=tk.Label(text=" ")
tiempo.place(x=100, y=155)
opcion1=tk.Label(text=" A que profundidad en metros se sumergio? ")
opcion1.place(x=100, y=180)
prof=tk.Entry()
prof.place(x=100,y=200)
prof.config(background="black",fg="#ffff00")
calculop=tk.Button(text= " Calcular ", command=calculadorap, fg="#0000ff")
calculop.place(x=100,y=240)
resultado1=tk.Label(text=" El resultado es ")
resultado1.place(x=100, y=280)
'''_________________________________________________'''
def sortear():
import random
l=[]
a=random.randint(0,45)
b=random.randint(0,45)
c=random.randint(0,45)
d=random.randint(0,45)
e=random.randint(0,45)
f=random.randint(0,45)
l.append(a)
l.append(b)
l.append(c)
l.append(d)
l.append(e)
l.append(f)
while True:
if l[0]==l[1] or l[0]==l[2] or l[0]==l[3] or l[0]==l[4] or l[0]==l[5] or l[1]==l[2] or l[1]==l[3] or l[1]==l[4] or l[1]==l[5] or l[2]==l[3] or l[2]==l[4] or l[2]==l[5] or l[3]==l[4] or l[3]==l[5] or l[4]==l[5]:
l.pop()
l.pop()
l.pop()
l.pop()
l.pop()
l.pop()
a=random.randint(0,45)
b=random.randint(0,45)
c=random.randint(0,45)
d=random.randint(0,45)
e=random.randint(0,45)
f=random.randint(0,45)
l.append(a)
l.append(b)
l.append(c)
l.append(d)
l.append(e)
l.append(f)
else:
break
cont=0
primer=int(n1.get())
if primer==l[0] or primer==l[1] or primer==l[2] or primer==l[3] or primer==l[4] or primer==l[5]:
cont=cont+1
segundo=int(n12.get())
if segundo==l[0] or segundo==l[1] or segundo==l[2] or segundo==l[3] or segundo==l[4] or segundo==l[5]:
cont=cont+1
tercero=int(n13.get())
if tercero==l[0] or tercero==l[1] or tercero==l[2] or tercero==l[3] or tercero==l[4] or tercero==l[5]:
cont=cont+1
cuarto=int(n14.get())
if cuarto==l[0] or cuarto==l[1] or cuarto==l[2] or cuarto==l[3] or cuarto==l[4] or cuarto==l[5]:
cont=cont+1
quinto=int(n15.get())
if quinto==l[0] or quinto==l[1] or quinto==l[2] or quinto==l[3] or quinto==l[4] or quinto==l[5]:
cont=cont+1
sexto=int(n16.get())
if sexto==l[0] or sexto==l [1] or sexto==l[2] or sexto==l[3] or sexto==l[4] or sexto==l[5]:
cont=cont+1
acertados1.config(text= " HAS ACERTADO: " + str(cont) + " NUMEROS ")
s1.config(text= a, fg="#ff0000")
s2.config(text=b, fg="#ff0000")
s3.config(text= c, fg="#ff0000")
s4.config(text= d, fg="#ff0000")
s5.config(text= e, fg="#ff0000")
s6.config(text= f, fg="#ff0000")
sorteo.config(text= " NO VA MAS ",bg= "#ff0000")
import mysql.connector
conexion3=mysql.connector.connect(host="localhost",
user="root",
passwd="",
database="Sorteos")
cursor3=conexion3.cursor()
sql="insert into Sorteos( numero_jugado_1,numero_jugado_2,numero_jugado_3,numero_jugado_4,numero_jugado_5,numero_jugado_6,cant_aciertos,nro_sorteado_1,nro_sorteado_2,nro_sorteado_3,nro_sorteado_4,nro_sorteado_5,nro_sorteado_6) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
datos=(l[0],l[1],l[2],l[3],l[4],l[5],cont,primer,segundo,tercero,cuarto,quinto,sexto)
cursor3.execute(sql, datos)
conexion3.commit()
conexion3.close()
def reconfig():
s1.config(text= " ??? ",foreground= "green")
s2.config(text= " ??? ",foreground= "green")
s3.config(text= " ??? ",foreground= "green")
s4.config(text= " ??? ",foreground= "green")
s5.config(text= " ??? ",foreground= "green")
s6.config(text= " ??? ",foreground= "green")
acertados1.config(text=" ")
sorteo.config(text=" SORTEAR ",background= "green")
comojugar=tk.Label(text=" TIENES LO QUE SE NECESITA PARA SER MILLONARIO ??? ", fg="#ff0000")
comojugar.place(x=50,y=320)
comojugar1=tk.Label(text= " SELECCIONA 6 NUMEROS DEL 0 AL 45 Y AVERIGUALO!! ", fg="#ff0000")
comojugar1.place(x=50,y=340)
n1=tk.Entry(ventana,background="black",fg="#03f943", width=8)
n1.place(x=10,y=370)
#n1.config(font=50)
n12=tk.Entry(ventana,background="black",fg="#03f943", width=8)
n12.place(x=80,y=370)
n13=tk.Entry(ventana,background="black",fg="#03f943", width=8)
n13.place(x=150,y=370)
n14=tk.Entry(ventana,background="black",fg="#03f943", width=8)
n14.place(x=220,y=370)
n15=tk.Entry(ventana,background="black",fg="#03f943", width=8)
n15.place(x=290,y=370)
n16=tk.Entry(ventana,background="black",fg="#03f943", width=8)
n16.place(x=360,y=370)
acertados1=tk.Label(text= " ")
acertados1.place(x=10,y=400)
sorteo=tk.Button(ventana,text=" SORTEAR " ,background="green", width=20, height=5,command=sortear)
sorteo.place(x=124,y=450)
reiniciar=tk.Button(ventana,text=" REINICIAR ",command=reconfig, fg="#0000ff")
reiniciar.place(x=170,y=630)
s1=tk.Label(text=" ??? ",foreground= "green")
s1.place(x=55, y=580)
s1.config(font=60)
s2=tk.Label(text=" ??? ",foreground= "green")
s2.place(x=105, y=580)
s2.config(font=60)
s3=tk.Label(text=" ??? ",foreground= "green")
s3.place(x=155, y=580)
s3.config(font=60)
s4=tk.Label(text=" ??? ",foreground= "green")
s4.place(x=205, y=580)
s4.config(font=60)
s5=tk.Label(text=" ??? ",foreground= "green")
s5.place(x=255, y=580)
s5.config(font=60)
s6=tk.Label(text=" ??? ",foreground= "green")
s6.place(x=305, y=580)
s6.config(font=60)
'''divisor_hor=tk.Label(text="___________________________________________________________________________")
divisor_hor.place(x=20,y=300)'''
'''________________________________________________________________________'''
def verificarp():
cont=0
c1=int(respuesta1.get())
if c1 == pregunta_azar[1]:
label1.config(text= "CORRECTO", fg="#008000")
cont=cont+1
else:
label1.config(text= "INCORRECTO",fg="#ff0000")
c2=int(respuesta2.get())
if c2 == pregunta_azar2[1]:
label2.config(text= "CORRECTO",fg="#008000")
cont=cont+1
else:
label2.config(text= "INCORRECTO", fg="#ff0000")
c3=int(respuesta3.get())
if c3 == pregunta_azar3[1]:
label3.config(text= "CORRECTO",fg="#008000")
cont=cont+1
else:
label3.config(text= "INCORRECTO", fg="#ff0000")
c4=int(respuesta4.get())
if c4 == pregunta_azar4[1]:
label4.config(text= "CORRECTO",fg="#008000")
cont=cont+1
else:
label4.config(text= "INCORRECTO", fg="#ff0000")
c5=int(respuesta5.get())
if c5 == pregunta_azar5[1]:
label5.config(text= "CORRECTO",fg="#008000")
cont=cont+1
else:
label5.config(text= "INCORRECTO",fg="#ff0000")
label_punt.config(text= " ACERTASTE " + str(cont)+ " RESPUESTAS ",fg="#0000ff")
import random
import mysql.connector
conexion1=mysql.connector.connect(host="localhost",
user="root",
passwd="",
database="Quiz")
cursor1=conexion1.cursor()
cursor1.execute("select pregunta, correcta from preguntas ")
todas_preguntas=cursor1.fetchall()
pregunta_azar=(random.choice(todas_preguntas))
pregunta_usuario=pregunta_azar[0]
#respuesta=int(input(pregunta_usuario))
opcion=tk.Label(text=" CUANTO SABES DE CULTURA GENERAL? ", fg="#ff0000")
opcion.place(x=712, y=5)
pregunta1=tk.Label(text= " P1: " + pregunta_usuario)
pregunta1.place(x=720,y=40)
respuesta1=tk.Entry()
respuesta1.place(x=720,y=60)
label1=tk.Label(text=" ")
label1.place(x=850,y=60)
cursor2=conexion1.cursor()
cursor2.execute("select pregunta, correcta from preguntas ")
todas_preguntas2=cursor2.fetchall()
pregunta_azar2=(random.choice(todas_preguntas))
pregunta_usuario2=pregunta_azar2[0]
pregunta2=tk.Label(text= " P2: " + pregunta_usuario2)
pregunta2.place(x=720,y=90)
respuesta2=tk.Entry()
respuesta2.place(x=720,y=110)
label2=tk.Label(text=" ")
label2.place(x=850,y=110)
cursor3=conexion1.cursor()
cursor3.execute("select pregunta, correcta from preguntas ")
todas_preguntas3=cursor3.fetchall()
pregunta_azar3=(random.choice(todas_preguntas))
pregunta_usuario3=pregunta_azar3[0]
pregunta3=tk.Label(text= " P3: " + pregunta_usuario3)
pregunta3.place(x=720,y=140)
respuesta3=tk.Entry()
respuesta3.place(x=720,y=160)
label3=tk.Label(text=" ")
label3.place(x=850,y=160)
cursor4=conexion1.cursor()
cursor4.execute("select pregunta, correcta from preguntas ")
todas_preguntas4=cursor4.fetchall()
pregunta_azar4=(random.choice(todas_preguntas))
pregunta_usuario4=pregunta_azar4[0]
pregunta4=tk.Label(text= " P4: " + pregunta_usuario4)
pregunta4.place(x=720,y=190)
respuesta4=tk.Entry()
respuesta4.place(x=720,y=210)
label4=tk.Label(text=" ")
label4.place(x=850,y=210)
cursor5=conexion1.cursor()
cursor5.execute("select pregunta, correcta from preguntas ")
todas_preguntas5=cursor5.fetchall()
pregunta_azar5=(random.choice(todas_preguntas))
pregunta_usuario5=pregunta_azar5[0]
pregunta5=tk.Label(text= " P5: " + pregunta_usuario5)
pregunta5.place(x=720,y=240)
respuesta5=tk.Entry()
respuesta5.place(x=720,y=260)
label5=tk.Label(text=" ")
label5.place(x=850,y=260)
label_punt=tk.Label(text=" ", fg="#0000ff")
label_punt.place(x=850,y=305)
verificar=tk.Button(ventana,text=" VERIFICAR ",fg="#0000ff", command=verificarp)
verificar.place(x=720,y=300)
'''volver=tk.Button(ventana, text=" VOLVER A JUGAR " ,foreground="green", command=volver)
volver.place(x= 1010, y=300)'''
"""boton_puntaje=tk.Button(text=" VER PUNTAJE ",fg="#0000ff" ,command=ver_puntaje)
boton_puntaje.place(x=10,y=440)
cantidad=tk.Label(text=" TU PUNTAJE ES: ", fg="#0000ff")
cantidad.place(x=10,y=470)"""
conexion1.close()
'''___________________________________________________________'''
def base_datos():
usuario=pregunta.get()
usuario1=int(respuesta.get())
import mysql.connector
conexion2=mysql.connector.connect(host="localhost",
user="root",
passwd="",
database="Quiz")
cursor2=conexion2.cursor()
sql="insert into preguntas( pregunta,correcta) values (%s,%s)"
datos=( usuario , usuario1 )
cursor2.execute(sql, datos)
conexion2.commit()
conexion2.close()
pregunta.delete(0, tk.END)
respuesta.delete(0, tk.END)
comentario=tk.Label(text=" APORTA TU GRANITO DE ARENA CARGANDO PREGUNTAS AL JUEGO!!! ",fg="#ff0000")
comentario.place(x=712, y=370)
comentario1=tk.Label(text=" RECUERDA QUE LA RESPUESTA DEBE SER UN VALOR NUMERICO ENTERO ", fg="#ff0000")
comentario1.place(x=712, y= 390)
pedido=tk.Label(text=" Escriba aqui su pregunta ")
pedido.place(x=720, y=450)
pregunta=tk.Entry()
pregunta.place(x=720,y=490)
pedido1=tk.Label(text=" Escriba aqui su respuesta")
pedido1.place(x=720, y=530)
respuesta=tk.Entry()
respuesta.place(x=720,y=570)
botonresp=tk.Button(text= " Enviar a base de datos ",command=base_datos, fg="#0000ff")#command=resp_base) #falta command
botonresp.place(x=720,y=610)
ventana.mainloop() |
fbcf2d7048347b75c446bae76ebc30d5d2cdbf18 | Nick12321/python_tutorial | /guessing_game.py | 1,631 | 4.3125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 4 21:07:07 2020
@author: nick
"""
###make import statements in homework5_8.py
# Make Guess_Game class to store guess number, tries per game.
# method to generate random number, check guess (low or high)
# Game__init__ generate and store random number, and empty list for tries
# Guess_Game will store info
import random
class Guessing_Game:
#initialize class
def __init__(self, name):
self.player_record=[]
self.name = name
self.tries=0
#get random number
def return_random(self):
max_number=100
self.random_num=random.randint(1, max_number)+1
return self.random_num
#get name
def get_name(self):
return self.name
#set game win/loss and # of tries, create tuple and store in list
def set_game_stat(self, tries):
self.player_record.append(tries)
#get game win / loss and # of tries
def get_game_stat(self):
return self.player_record
'''
#compare guess to random number
def check_guess(self, guess):
self.guess=int(guess)
if self.guess < self.random_num:
return(0)
if self.guess > self.random_num:
return(1)
if self.guess==self.random_num:
return(2)
#set new game tries = 0
def new_game(self):
self.tries = 0
#set number of tries
def add_tries():
self.tries=self.tries+1
#get number of tries
def get_tries():
return (self.tries)
'''
|
8b48ca9b4b4630345ec4cf1ddc6b76af3be01f5a | manjunatha-kasireddy/python-programs | /numpyufuc/ufunc.py | 183 | 3.6875 | 4 | # x = [1, 2, 3, 4]
# y = [4, 5, 6, 7]
# z = []
# for i, j in zip(x, y):
# z.append(i + j)
# print(z)
import numpy as np
x = [1, 2, 3, 4]
y = [4, 5, 6, 7]
z = np.add(x, y)
print(z) |
997d6ca85a770be84e4b2fd3f2bde28c77606c2a | VasssilPopov/AllSpiders | /_LIBRARY/HelperTools.py | 10,528 | 3.625 | 4 | # # -*- coding: utf-8 -*-
import jsonlines
import glob
#-------------------------------------------------------------------------
'''
It maps month name to month sequential number.
It returns '??' when the name is not found
'''
def bgMonthstoNumber(monthName):
monthName=monthName.lower()
months= {u'януари':'01',u'февруари':'02', u'март':'03',
u'април':'04',u'май':'05', u'юни':'06',
u'юли':'07',u'август':'08', u'септември':'09',
u'октомври':'10',u'ноември':'11', u'декември':'12'}
if (monthName in months):
return months[monthName]
else:
return'??'
'''
It checks date values.
It returns summary date & date count into file
'Key: 2017.07.15, count:44
'''
def usMonthstoNumber(monthName):
monthName=monthName.lower()
months= {'jan':'01',
'feb':'02',
'mar':'03',
'apr':'04',
'may':'05',
'jun':'06',
'jul':'07',
'aug':'08',
'sep':'09',
'oct':'10',
'nov':'11',
'dec':'12'}
if (monthName in months):
return months[monthName]
else:
return'??'
def checkDate(jlFile):
d=dict()
with jsonlines.open(jlFile) as reader:
for obj in reader:
#newDate = obj['date'].split()[0]
newDate = obj['date'].split(',')[0]
if (newDate in d.keys()):
d[newDate] +=1
else:
d[newDate] =1
#print len(d.items())
for (k,v) in d.items():
#if (k,v) != None:
if (k != None) and (v != None):
res=jlFile[-15:][0:10].replace('-','.')
if (res!=k):
print '%s Key: %s, count: %s' % (jlFile, k,v)
#checkDate('Blitz\Reports\Blitz-2017-06-06.json')
# scan files in directory and call checkDate for each one
def scanFolder(folderPath):
s20='-'*20
files=glob.glob(folderPath)
print s20+folderPath+s20
for file in files:
print checkDate(file)
#scanFolder('Dnevnik\Reports\*.json')
#>>> VALIDATION -------------------------------------------------------------
import requests
import datetime
# check existens of url
def urlExists(url):
try:
request = requests.get(url)
if request.status_code == 200:
return True #print('Web site exists')
else:
return False #print('Web site does not exist')
except:
return False
# standard validation procedure
#Item Level Validation
# it returns one result = True/False depending of are all validation checks true / or some of them failed
def isDataValid(obj, rowNo):
resValue={'result':'True','messages': list()}
#url Not empty ---------------------------------
if obj['url']==u'':
resValue['result'] = False
resValue['messages'].append(u"'url' is empty")
# elif urlExists(obj['url'])==False:
# #url Exists ---------------------------------
# url=obj['url']
# resValue['result'] = False
# resValue['messages'].append(u"url:'"+url+"' doesn't exist")
#title Not empty ---------------------------------
if (obj['title'] is None) or (obj['title'].strip() ==u''):
resValue['result'] = False
resValue['messages'].append(u"'title' is empty")
#text Not empty ---------------------------------
# if obj['text'] == u'':
#if (obj is None) or (obj.get['text'] is None):
if obj['text'].strip() == u'':
# if (obj is None) or (obj.get['text'] is None):
resValue['result'] = False
resValue['messages'].append(u"'text' is empty")
elif obj['text'].strip() == u'':
resValue['result'] = False
resValue['messages'].append(u"'text' is empty")
elif len(obj['text'].strip()) < 8:
resValue['result'] = False
resValue['messages'].append(u"'text' is shorter than 8")
#date Not empty ---------------------------------
if obj['date'].strip() == u'':
resValue['result'] = False
resValue['messages'].append(u"'date' is empty")
#date format YYYY.mm.dd ---------------------------------
try:
datetime.datetime.strptime(obj['date'], '%Y.%m.%d')
#datetime.datetime.strptime(obj['date'], '%d.%m.%Y')
except ValueError:
resValue['result'] = False
resValue['messages'].append(u"date value:'"+obj['date']+"' Incorrect date format, should be YYYY.mm.dd")
# print 'url: %s'%(u''+obj['url']),'-'*20
if resValue['result']:
#print 'Data valid'
pass
else:
#print 'Data is not valid'
#print 'url:'+obj['url']
print '<%d> %s' % (rowNo,obj['url'])
for msg in resValue['messages']:
print u''+msg
#print u''
return resValue['result']
# test it
t={'url':'alabala','title':'','text':'','date':'12.03.1951'}
#print isDataValid(t)
count=0
# check data of single report file
def checkReport(jlFile):
d=dict()
count = 0
countAll = 0
s20='-'*20
#print
# print s20+jlFile+
#print '>> Validation of %s '% (jlFile)
with jsonlines.open(jlFile) as reader:
for obj in reader:
countAll +=1
# print countAll
if isDataValid(obj, countAll):
count +=1
#print '-'*70
if (count != countAll):
print '<<Valid records: %d of %d'%(count, countAll)
#print '-'*70
#print
#checkReport('Dnevnik/Reports/Dnevnik-2017-07-18.json')
#checkReport('Trud\Reports\Trud-2017-06-23.json')
#checkReport('ClubZ/Reports\ClubZ-2017-07-03.json')
# check data of multiple report files
def scanReports(folderPath):
# print '>> '+folderPath
files=glob.glob(folderPath)
# print len(files)
s20='-'*10 +'Start'+ '-'*10 + '\n'
print s20+folderPath
for file in files:
# print '>2>'
checkReport(file)
s20='-'*10 +'End'+ '-'*10 + '\n'
print s20
# print '>1>'
#scanReports('Dnevnik\Reports\Ready\*.json')
# it swaps the day and the year positions into date
# 31.12.1999 --> 1999.12.31
# 1999.12.31 --> 31.12.1999
def swapDayAndYear(theDate):
print theDate
parts=theDate.split('.')
tmp=parts[0]
parts[0]=parts[2]
parts[2]=tmp
return '.'.join(parts)
#print swapDayAndYear('12.03.1951')
# modify the file name adding 'out' at the beggining
# makeNewFileName('Trud\Reports\Trud-2017-06-23.json') --> 'Trud\Reports\outTrud-2017-06-23.json'
def makeNewFileName(oldFileName):
#'Trud\Reports\Trud-2017-06-23.json'
parts=oldFileName.split('\\')
length=len(parts)-1
#print parts
parts[length] = 'out'+parts[length]
return '\\'.join(parts)
#print makeNewFileName('Trud\Reports\Trud-2017-06-23.json')
# copy jlFile and swap the day and year in the result file
def swapDateParts(jlFile):
jlFileOutput=makeNewFileName(jlFile)
with jsonlines.open(jlFile) as reader:
with jsonlines.open(jlFileOutput, mode='w') as writer:
for obj in reader:
date=obj['date']
obj['date'] = swapDayAndYear(date)
writer.write(obj)
#swapDateParts('Trud\Reports\Trud-2017-06-23.json')
def getNewFileName(oldFileName):
parts=oldFileName.split('\\')
pos=len(parts)-2
parts[pos] = 'Data'
print parts
return '\\'.join(parts)
#copy the file and change delimiters
# 2017-06-25 --> 2017.06.25
def chageDelimiter(jlFile):
print jlFile
jlFileOutput=getNewFileName(jlFile)
with jsonlines.open(jlFile) as reader:
with jsonlines.open(jlFileOutput, mode='w') as writer:
for obj in reader:
temp=obj['date']
temp = temp.replace('-','.')
obj['date'] = temp
writer.write(obj)
# change delimiters in multiple files
def scanAndSwapDateParts(folderPath):
s20='-'*20
files=glob.glob(folderPath)
print s20+folderPath+s20
for file in files:
swapDateParts(file)
#chageDelimiter(file)
#scanAndSwapDateParts('PIK\Reports\*.json')
# change delimiters in multiple files
def scanChangeDateDelimiter(folderPath):
s20='-'*20
files=glob.glob(folderPath)
print s20+folderPath+s20
for file in files:
chageDelimiter(file)
#scanAndSwapDateParts('PIK\Reports\*.json')
#scanChangeDateDelimiter('PIK\Reports\*.json')
'''
def scaneFile(jlFile):
jlFileOutput=makeNewFileName(jlFile)
with jsonlines.open(jlFile) as reader:
with jsonlines.open(jlFileOutput, mode='w') as writer:
for obj in reader:
try:
writer.write(obj)
except:
continue
scaneFile('PIK\Reports\PIK-2017-06-05.json')
'''
# used def read_json(file):
'Recognize the Json file format ("Json_Lines", "Json", "Unknown")'
#It's a single file
def jsonFileType(file):
with open(file) as f: # Check what is the first char of the file { or [
first_char = f.read(1)
f.close()
if first_char == '{': # Json Lines
return "Json_Lines"
elif first_char == '[': # Json format
return "Json"
else:
return "Unknown"
#print jsonFileType('PIK\Reports\PIK-2017-06-05.json')
# check multiple files
def checkReports(folderPath):
files=glob.glob(folderPath)
s20='-'*20
print s20+folderPath+s20
for file in files:
print jsonFileType(file), file
##checkReports('PIK\Reports\*.json')
#-------------------------------------------------------------------------
# def bgMonthstoNumber(monthName):
# monthName=monthName.lower()
# months= {u'януари':'01',u'февруари':'02', u'март':'03',
# u'април':'04',u'май':'05', u'юни':'06',
# u'юли':'07',u'август':'08', u'септември':'09',
# u'октомври':'10',u'ноември':'11', u'декември':'12'}
# if (monthName in months):
# return months[monthName]
# else:
# return'??'
def eho2(msg):
print msg
#----------------------------------------------------------------
|
62305da2aa292c8326370c9540de5182cdc8fdfa | RWEngelbrecht/Learning_Python | /intermediate_stuff/static_and_class_methods.py | 743 | 3.875 | 4 | ## static and class methods
class Person(object):
# variable that belongs to class
population = 50
def __init__(self, name, age):
self.name = name
self.age = age
Person.population += 1
@classmethod # decorator
def getPopulation(cls): # method belonging to the class, not an instance
return cls.population
@staticmethod
def isPerson(obj):
return isinstance(obj, Person)
def isAdult(self):
return self.age >= 18
def display(self):
print(self.name, "is",self.age,"years old", sep=' ')
per1 = Person("Steve", 18)
per1.display()
print(Person.getPopulation())
print("Yep, that's a person...") if Person.isPerson(per1) else print("That's no human...") |
5c7ccc3ffd9242ca29036e21fa81aa262a5bc904 | whitehamster26/python-project-lvl1 | /brain_games/games/progression.py | 375 | 3.609375 | 4 | from random import randint
DESCRIPTION = 'What number is missing in the progression?'
def start():
start = randint(1, 20)
step = randint(1, 10)
items = [str(start + item*step) for item in range(9)]
missed_item = randint(0, len(items))
answer = items[missed_item]
items[missed_item] = '..'
question = ' '.join(items)
return question, answer
|
07027e00071ddddf5d5917cb88259cd7dbab3dba | wfeng1991/learnpy | /py/leetcode/79.py | 989 | 3.6875 | 4 | class Solution:
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
def exist0(board,x,y,word,idx):
if x==len(board) or y==len(board[0]) or x<0 or y<0:
return False
if idx==len(word)-1 and board[x][y]==word[idx]:
return True
if idx<len(word) and board[x][y]==word[idx]:
board[x][y] += "*"
res = exist0(board,x-1,y,word,idx+1) or exist0(board,x+1,y,word,idx+1) or exist0(board,x,y+1,word,idx+1) or exist0(board,x,y-1,word,idx+1)
board[x][y] = board[x][y][0]
return res
return False
for i in range(len(board)):
for j in range(len(board[0])):
if exist0(board,i,j,word,0):
return True
return False
print(Solution().exist([["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]],"ABCCED")) |
75b0dba5462c02e098431800b76fe83c3aeafbc5 | maxfilter/project-rosalind | /Bioinformatics_Stronghold/REVC/revc.py | 469 | 4.03125 | 4 | '''
Complementing a Strand of DNA
Given: A DNA string s of length at most 1000 base pairs
Returns: The reverse complement s^c of s
'''
import sys
conjugate = {
'A' : 'T',
'C' : 'G',
'G' : 'C',
'T' : 'A',
}
with open(sys.argv[1], 'r') as f:
s = f.read().strip()
sequence = s[::-1] #reverse the string and break it into a list
conjugate_string = ''
for base_pair in sequence:
conjugate_string += conjugate[base_pair]
print(conjugate_string)
|
24e7e7f55ede11703b4dfe1ae983aa92fa568e51 | jenkin-du/Python | /pyhon36_study/palindrome.py | 467 | 3.6875 | 4 | # 筛选回数
def is_palindrome(num):
if 10 > num > 0:
return True
numlist = []
low = num % 10
while num > 0:
numlist.append(low)
num //= 10 # 整除
low = num % 10
lens = len(numlist)
i = 0
j = lens - 1
while i < j:
if numlist[i] != numlist[j]:
return False
i += 1
j -= 1
return True
output = filter(is_palindrome, range(1, 10000))
print(list(output))
|
abc5e53f746f02d56b49512bc0fecca7a62577a0 | drewriker/USU-CS-1400 | /Assignment 3/task1.py | 860 | 3.90625 | 4 | # Andrew Riker
# CS1400 - LW2 XL
# Assignment #03
# enter investment amount
investmentAmt = eval(input("Enter the starting investment amount: $"))
# enter monthly payment amount
monthlyPay = eval(input("Enter monthly payment amount: $"))
# enter annual interest rate
annualInterestRate = eval(input("Enter the annual interest rate: eg, 4.5 "))
# enter number of years
numYears = eval(input("Enter the number of years: "))
# calculate number of months and monthly interest rate
monthlyInterestRate = annualInterestRate / 1200
months = numYears * 12
# calculate final value
finalValue = investmentAmt * ((1 + monthlyInterestRate) ** months) + monthlyPay * \
((1 + monthlyInterestRate) ** months - 1) / monthlyInterestRate * (1 + monthlyInterestRate)
# print the final value
print("Final Value is $" + str(round(finalValue, 2)))
|
caaf8bc9d9eed74a4a65b2c1cdd8349cfacc6007 | BryceStansfield/Prime-Factor-Programming | /interpreter.py | 2,026 | 3.609375 | 4 | class program:
memory = [];
integer = 1;
instructions = [];
factors = [];
memPointer = 0;
inPointer = 0;
class primeIterator:
def __init__(self):
self.primes = [2];
def __iter__(self):
return(self);
def __next__(self):
test = self.primes[-1]+2;
while(1):
divisible = False;
index = 1;
while(primes[index] <= test**0.5):
if(test % primes[index] == 0):
divisible = True;
index += 1;
if(divisible):
return(test);
test += 2;
def __init__(self, integer):
self.integer = integer;
self.memPointer = 0;
self.inPointer = 0;
for i in range(0, 1000):
self.memory.append(0);
def factoriser(self):
primes = primeIterator();
while(self.integer != 1):
divisible = False;
prime = iter(primes);
while(self.integer % prime == 0):
self.integer = self.integer/prime;
divisible = True;
self.factors.append(divisible);
def createInstructions(self):
if(len(self.factors) % 2 == 1):
self.factors.append(0);
for i in range(0, len(self.factors), 2):
if(self.factors[i] == 0 and self.factors[i+1] == 0):
self.instructions.append('r');
elif(self.factors[i] == 0 and self.factors[i+1] == 1):
self.instructions.append('+');
elif(self.factors[i] == 1 and self.factors[i+1] == 0):
self.instructions.append('j');
elif(self.factors[i] == 1 and self.factors[i+1] == 1):
self.instructions.append('e');
def runProgram(self):
while(self.instructions[self.inPointer] != 'e'):
if(self.instructions[self.inPointer] == 'r'):
self.memPointer = (self.memPointer + 1) % 1000;
elif(self.instructions[self.inPointer] == '+'):
self.memory[self.memPointer] = (self.memory[self.memPointer] + 1) % 256;
elif(self.instructions[self.inPointer] and self.memory[self.memPointer] == 0):
self.inPointer = (self.inPointer + 2520) % len(self.inPointer);
self.inPointer = (self.inPointer + 1) % len(self.inPointer);
return(self.memory);
def loadProgram(self, instructions):
self.instructions = instructions; |
59935e39718a69ccd2438c8ebfb6d77be566177d | JerinPaulS/Python-Programs | /MaximalSquare.py | 1,221 | 3.640625 | 4 | '''
221. Maximal Square
Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
Example 1:
Input: matrix = [["1","0","1","0","0"],["1","0","1","1","1"],["1","1","1","1","1"],["1","0","0","1","0"]]
Output: 4
Example 2:
Input: matrix = [["0","1"],["1","0"]]
Output: 1
Example 3:
Input: matrix = [["0"]]
Output: 0
Constraints:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 300
matrix[i][j] is '0' or '1'.
'''
class Solution(object):
def maximalSquare(self, matrix):
"""
:type matrix: List[List[str]]
:rtype: int
"""
rows, cols = len(matrix), len(matrix[0])
cache = {}
def helper(row, col):
if row >= rows or col >= cols:
return 0
if (row, col) in cache:
return cache[(row, col)]
else:
down = helper(row + 1, col)
right = helper(row, col + 1)
diag = helper(row + 1, col + 1)
cache[(row, col)] = 0
if matrix[row][col] == "1":
cache[(row, col)] = 1 + min(down, right, diag)
return cache[(row, col)]
helper(0, 0)
return (max(cache.values()) ** 2) |
6595f00bfdec1ba02377619d833900c33fae064e | quadrant26/python | /Tkinter/test_dialogs_modules3.py | 728 | 3.53125 | 4 | '''
标准对话框
messagebox
filedialog
colorchooser 颜色选择对话框
arguments:
title 标题
message 消息内容
options 参数
default:
icon 图标
parent
'''
from tkinter import *
root = Tk()
'''
askopenfilename()
asksavefilename()
指定文件的后缀
defaultextension = ".py"
文件筛选:tuple("类型", "后缀名")
filetypes[("PNG", ".png), ("JPG", ".jpg")]
'''
'''
colorchooser.askcolor()
'''
def callback():
color = colorchooser.askcolor()
print(color) # tuple -> float ((128.5, 128.5, 255.99609375), '#8080ff')
Button(root, text="选择颜色", command=callback).pack()
root.mainloop()
|
4ef6e74afa7facf7f15931735e3f4dc657de454e | greenteemo/Murray-s-lectures | /FIT5191/NP07/getpath.py | 353 | 3.609375 | 4 | net = {
'x':['u','v','w','y'],
'y':['x','w','z'],
'z':['y','w'],
'u':['w','x','v'],
'v':['u','w','x'],
'w':['u','v','x','y','z']
}
def dfs(path, dest):
if(path[-1] == dest):
print(path)
return
for node in net[path[-1]]:
if(node not in path):
dfs(path+node, dest)
path = input("start node:")
dest = input("end node:")
dfs(path, dest)
|
6f057b80b2c6f5cb8822a661d16180face891e3d | jasmineseah-17/euler | /10_Summation_of_primes.py | 286 | 3.625 | 4 | #Problem 10
def is_prime(n):
if n == 1:
return False
for i in range(2,int(n**(0.5))+1):
if n%i==0:
return False
count = 0
total = 0
n = 1
while n < 2000000:
n += 1
if is_prime(n) != False:
count += 1
total += n
print(total)
|
452c906f3d2753e9ceecd8b37ba7506e83d8edf0 | justgolikeme/My_MachineLearning | /the_use_Numpy/the_learn_from_NumpyChineseWebsite/Broadcasting/Demo.py | 2,753 | 4.0625 | 4 | # -*- coding:utf-8 -*-
__author__ = 'Mr.Lin'
__date__ = '2019/11/15 16:20'
import numpy as np
"""
广播Broadcasting
广播是一种强有力的机制,它让Numpy可以让不同大小的矩阵在一起进行数学计算。我们常常会有一个小的矩阵和一个大的矩阵,然后我们会需要用小的矩阵对大的矩阵做一些计算。
"""
# 举个例子,如果我们想要把一个向量加到矩阵的每一行,我们可以这样做:
# We will add the vector v to each row of the matrix x,
# storing the result in the matrix y
x = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 0, 1])
y = np.empty_like(x) # Create an empty matrix with the same shape as x
# Add the vector v to each row of the matrix x with an explicit loop
for i in range(4):
y[i, :] = x[i, :] + v
# Now y is the following
# [[ 2 2 4]
# [ 5 5 7]
# [ 8 8 10]
# [11 11 13]]
# print(y)
# >>>
# [[ 2 2 4]
# [ 5 5 7]
# [ 8 8 10]
# [11 11 13]]
# 这样是行得通的,但是当x矩阵非常大,利用循环来计算就会变得很慢很慢。我们可以换一种思路:
vv = np.tile(v, (4, 1)) # Stack 4 copies of v on top of each other
# print(vv) # Prints "[[1 0 1]
# [1 0 1]
# [1 0 1]
# [1 0 1]]"
y = x + vv # Add x and vv elementwise
print("")
print("")
print("")
# print(y) # Prints "[[ 2 2 4
# [ 5 5 7]
# [ 8 8 10]
# [11 11 13]]"
# Numpy广播机制可以让我们不用创建vv,就能直接运算,看看下面例子:
xx = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v_1 = np.array([1, 0, 1])
y_1 = x + v_1 # Add v to each row of x using broadcasting
print(y_1) # Prints "[[ 2 2 4]
# [ 5 5 7]
# [ 8 8 10]
# [11 11 13]]"
# 对两个数组使用广播机制要遵守下列规则:
#
# 如果数组的秩不同,使用1来将秩较小的数组进行扩展,直到两个数组的尺寸的长度都一样。
# 如果两个数组在某个维度上的长度是一样的,或者其中一个数组在该维度上长度为1,那么我们就说这两个数组在该维度上是相容的。
# 如果两个数组在所有维度上都是相容的,他们就能使用广播。
# 如果两个输入数组的尺寸不同,那么注意其中较大的那个尺寸。因为广播之后,两个数组的尺寸将和那个较大的尺寸一样。
# 在任何一个维度上,如果一个数组的长度为1,另一个数组长度大于1,那么在该维度上,就好像是对第一个数组进行了复制。
|
9e451bdc3609320912e3fe1e49ac5abd8ad7e8d0 | smgraywood/Code_In_Place | /Khansole Academy.py | 1,591 | 4.28125 | 4 | Now that you’ve seen how programming can help us in a number of different areas, it’s time for you to implement Khansole Academy—a program that helps other people learn! In this problem, you’ll write a program in the file khansole_academy.py that randomly generates a simple addition problem for the user, reads in the answer from the user, and then checks to see if they got it right or wrong. Note that “console” is another name for “terminal” :-).
More specifically, your program should be able to generate simple addition problems that involve adding two 2-digit integers (i.e., the numbers 10 through 99). The user should be asked for an answer to the generated problem. Your program should determine if the answer was correct or not, and give the user an appropriate message to let them know.
A sample run of the program is shown below (user input is in bold italics).
$ python khansole_academy.py
What is 51 + 79?
Your answer: 120
Incorrect. The expected answer is 130
Here's another sample run, where the user gets the question correct:
$ python khansole_academy.py
What is 55 + 11?
Your answer: 66
Correct!
----------
import random
def main():
count=0
while True:
a = random.randint(0,100)
b = random.randint(0,100)
c = print("What is " + (str(a)+' + '+str(b)+ "?"))
d= input("Your answer: ")
if int(d) == a+b:
print("Correct!")
count += 1
else:
print("Incorrect. The expected answer is: " + str(a+b))
break
if __name__ == '__main__':
main()
|
6025948af67a72c2c1ace6291701efd402f049c9 | Improbus/DrexelCourseWork | /CS265/Lab4/s2.py | 528 | 3.640625 | 4 | #!/usr/bin/python
f = open( "students.csv", "r" ) # open file for reading (default)
# get rid of leading/trailing whitespace (spaces, tabs, newlines)
l = f.readline()
while l :
l = l.strip( ' \t\n' )
noname = l.strip('abcdefghijklmnopqrstuvwxyz, ')
numberlist = noname.split(",")
fsum = 0
for i in numberlist :
fsum += float(i)
numberofterms = float(len(numberlist))
average = (fsum / numberofterms)
print l
print noname
print numberlist
print fsum
print "The Average is "
print average
l = f.readline()
|
80bbd5c218109d55621c3b06824d31fbe15a528e | adiaz14/exercism_exercises_python | /armstrong-numbers/armstrong_numbers.py | 271 | 3.75 | 4 | def is_armstrong_number(number):
sum = 0
temp = number
exp = len(str(number))
digit = 0
while temp > 0:
digit = temp % 10
sum += digit ** exp
temp //= 10
if number == sum:
return True
else:
return False
|
b8f5f4feaddec18742129b234d4d42be73598367 | HBinhCT/Q-project | /hackerrank/Algorithms/Accessory Collection/solution.py | 1,150 | 3.609375 | 4 | #!/bin/python3
import os
#
# Complete the acessoryCollection function below.
#
def acessoryCollection(L, A, N, D):
#
# Write your code here.
#
if D > A or D > N or N > L:
return 'SAD'
if D == 1:
return str(L * A)
n_rest_max = (N - 1) // (D - 1)
max_result = -1
for n_rest in range(n_rest_max, 0, -1):
n_highest = N + (n_rest - 1) - n_rest * (D - 1)
rest, n_lowest = divmod(L - n_highest, n_rest)
if rest > A - 1 or (rest == A - 1 and n_lowest > 0):
break
res = n_highest * A + n_rest * (2 * A - rest - 1) * rest // 2 + n_lowest * (A - rest - 1)
if max_result >= res:
break
max_result = res
if max_result == -1:
return 'SAD'
return str(max_result)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
T = int(input())
for T_itr in range(T):
LAND = input().split()
L = int(LAND[0])
A = int(LAND[1])
N = int(LAND[2])
D = int(LAND[3])
result = acessoryCollection(L, A, N, D)
fptr.write(result + '\n')
fptr.close()
|
9418d2daeeb583c304be3129670c0fb932999f55 | tierchen/exercism-python-solutions | /allergies/allergies.py | 586 | 3.703125 | 4 | class Allergies(object):
allergies = ['eggs',
'peanuts',
'shellfish',
'strawberries',
'tomatoes',
'chocolate',
'pollen',
'cats']
allergies_mapping = {x: 2**i for i, x in enumerate(allergies)}
def __init__(self, score):
self.score = score
def is_allergic_to(self, item):
return bool(self.allergies_mapping[item] & self.score)
@property
def lst(self):
return [alr for alr in self.allergies if self.is_allergic_to(alr)] |
e82118efcf764d94426e616c8c635801eeda53b3 | emreg00/toolbox | /dict_utilities.py | 1,129 | 3.546875 | 4 |
def keep_only_with_overlapping_values(key_to_values, set_to_overlap, n_min_overlap):
"""
Keeping it non-one-liner for potential future feature additions based on values
"""
key_to_values_mod = {}
for key, values in key_to_values.iteritems():
values &= set_to_overlap
if len(values) >= n_min_overlap:
key_to_values_mod[key] = values
return key_to_values_mod
def keep_only_with_overlapping_keys(key_to_values, dict_to_overlap):
return dict((key, values) for key, values in key_to_values.iteritems() if key in dict_to_overlap)
def keep_only_with_unique_values(key_to_values, inner_delim="|"):
values_to_keys = {}
for key, values in key_to_values.iteritems():
values_key = inner_delim.join(sorted(list(values)))
values_to_keys.setdefault(values_key, []).append(key)
key_to_values_mod = {}
key_to_keys_equivalent = {}
for values, keys in values_to_keys.iteritems():
if len(keys) > 1:
keys.sort()
key_to_keys_equivalent[keys[0]] = set(keys[1:])
key_to_values_mod[keys[0]] = set(values.split(inner_delim))
return key_to_values_mod, key_to_keys_equivalent
|
9ab2cc6f379d282db130ea55eb76db9937a3b911 | Rashmidore/python-learning | /7conditional.py | 402 | 4 | 4 | def mean(value):
if type(value) == dict:
the_mean = sum(value.values()) / len(value)
else:
the_mean = sum(value) / len(value)
return the_mean
temp = {"mon":8,"tue":6,"wed":9}
date = (11,12,13,14)
print(mean(date))
print(mean(temp))
if isinstance(x, int) or isinstance(x, float) or x=='1':
print("Valid type!")
else:
print("Not valid!") |
ab0d07cd3eddf6b466fcdb7ae6ba2e90b6817082 | ruduran/advent_of_code | /2017/python/src/aoc/day03/part1.py | 1,597 | 3.6875 | 4 | #!/usr/bin/env python
from . import BaseProcessor
class Processor(BaseProcessor):
def calculate_steps(self):
if self.number == 1:
return 0
current_number = 1
side_size = 0
while current_number < self.number:
side_size += 2
current_number += 4 * side_size
x, y = self.calc_distance(side_size)
return x + y
def calc_distance(self, side_size):
prev_max_number = (side_size - 1) ** 2
number_pos_on_level = self.number - prev_max_number
side_num = int(number_pos_on_level / side_size)
if side_num == 4:
return (side_size, side_size)
number_pos_on_side = number_pos_on_level % side_size
if side_num % 2 == 0:
x_dist = int(side_size / 2)
y_dist = self.calc_dist_to_side_center(side_size,
number_pos_on_side)
else:
x_dist = self.calc_dist_to_side_center(side_size,
number_pos_on_side)
y_dist = int(side_size / 2)
return (x_dist, y_dist)
def calc_dist_to_side_center(self, side_size, num_on_side):
half_side = int(side_size / 2)
if num_on_side == half_side:
dist = 0
elif num_on_side < half_side:
dist = half_side - num_on_side
else:
dist = num_on_side - half_side
return dist
def main():
processor = Processor()
print(processor.calculate_steps())
if __name__ == '__main__':
main()
|
1adab35d4f24f363da8ef71f6ef7132391677f82 | LionKimbro/panthera | /listdict.py | 4,642 | 3.515625 | 4 | """listdict.py -- quickly search & filter a list of dictionaries
Experimental idea, research.txt 0K2
Import with:
-----------------------------------------------------------
from listdict import cue, val, val01, req, srt
from listdict import EQ, NEQ, GT, LT, GTE, LTE
from listdict import CONTAINS, NCONTAINS, WITHIN, NWITHIN
"""
EQ="EQ" # equal to
NEQ="NEQ" # not equal to
GT="GT" # greater than
LT="LT" # less than
GTE="GTE" # greater than or equal to
LTE="LTE" # less than or equal to
CONTAINS="CONTAINS" # sub-collection contains item
NCONTAINS="NCONTAINS" # sub-collection does NOT contain item
WITHIN="WITHIN" # value within collection
NWITHIN="NWITHIN" # value NOT within collection
fn_mappings = {EQ: lambda a,b: a==b,
NEQ: lambda a,b: a!=b,
GT: lambda a,b: a>b,
LT: lambda a,b: a<b,
GTE: lambda a,b: a>=b,
LTE: lambda a,b: a<=b,
CONTAINS: lambda a,b: b in a,
NCONTAINS: lambda a,b: b not in a,
WITHIN: lambda a,b: a in b,
NWITHIN: lambda a,b: a not in b}
LIST = "LIST"
g = {LIST: []}
def cue(L):
g[LIST] = L
def val():
return g[LIST]
def length():
return len(g[LIST])
def val1():
"""Require that there is one item, and return it."""
if len(g[LIST]) == 1:
return g[LIST][0]
else:
raise KeyError()
def val01(default=None):
"""Require that there is zero or one item, and return it."""
if len(g[LIST]) == 0:
return default
elif len(g[LIST]) == 1:
return g[LIST][0]
else:
raise KeyError
def req_fn(fn):
cue([D for D in g[LIST] if fn(D)])
def req_fn2(k, fn):
cue([D for D in g[LIST] if fn(D[k])])
def req_triple(k, relation, v):
fn = fn_mappings[relation]
cue([D for D in g[LIST] if fn(D[k], v)])
def req_matchall(D):
for k,v in D.items():
cue([D for D in g[LIST] if D[k] == v])
def req(*args, **kw):
"""Constrain down the list to meet some requirements.
This can be called in several different ways. In the example
below, we'll cull the list down to those dictionaries that have
D["x"] == 5.
1. req(fn) -- ex: req(lambda D: D["x"] == 5)
2. req(k, fn) -- ex: req("x", lambda x: x == 5)
3. req(k, relation, v) -- ex: req("x", EQ, 5)
4. req(**kw) -- ex: req(x=5)
Or consider D["y"] > 10:
1. req(fn) -- ex: req(lambda D: D["y"] > 10)
2. req(k, fn) -- ex: req("y", lambda y: y > 10)
3. req(k, relation, v) -- ex: req("y", GT, 10)
4. req(**kw) -- CANNOT BE EXPRESSED;
this form can only be used for equality checks
Or consider D["type"] == "foo" and D["name"] == "bar"
0. (Python List Comp:) -- ex: L = [D for D in L if D["type"] == "foo" and D["name"] == "bar"]
1. req(fn) -- ex: req(lambda D: D["type"] == "foo" and D["name"] == "bar")
2. req(k, fn) -- ex: req("type", lambda s: s=="foo")
req("name", lambda s: s=="bar")
(this form can only be used via serial calls)
3. req(k, relation, v) -- ex: req("type", EQ, "foo")
req("name", EQ, "bar")
(this form can only be used via serial calls)
4. req(**kw) -- ex: req(type="foo", name="bar")
"""
if kw:
req_matchall(kw)
elif len(args) == 1:
req_fn(*args)
elif len(args) == 2:
req_fn2(*args)
elif len(args) == 3:
req_triple(*args)
else:
raise TypeError
def srt(k, reverse=False):
"""Sort the list on a key."""
g[LIST].sort(key=lambda D: D[k], reverse=reverse)
def map(x):
"""Return the result of doing something to each list item.
map(fn) --> returns result of applying fn to each item
map(str) --> returns result of key lookup for each item
"""
if isinstance(x, str):
return [D[x] for D in g[LIST]]
else:
return [x(D) for D in g[LIST]]
def show(spec):
"""print dictionaries per a spec;
example spec:
"KEY1............. KEY2........................... KEY3......"
based on snippets.py, entry DLPR: Dictionary List Print
"""
print("NDX "+spec)
specL = [(word.rstrip("."), len(word)) for word in spec.split()]
for i, D in enumerate(g[LIST]):
pieces = [str(D.get(key, "NONE")).ljust(length)[:length] for (key,length) in specL]
print("{:>2}. ".format(i)+" ".join(pieces))
|
0ed1d616c7d2d9b196fcdda50520c829f3b4137a | QinGeneral/Algorithm | /sort/insert_sort.py | 1,551 | 3.921875 | 4 | # 插入排序
# 原地排序算法
# 稳定排序算法
# 时间复杂度:
# 最好 O(n)、最坏 O(n^2)、平均 O(n^2)
def better_insert_sort(array):
if len(array) <= 1:
return array
for i in range(1, len(array)):
temp = array[i]
j = i - 1
while j >= 0:
if temp < array[j]:
array[j + 1] = array[j]
else:
break
j -= 1
array[j + 1] = temp
return array
def insert_sort(array):
if len(array) <= 1:
return array
for i in range(1, len(array)):
for j in range(0, i):
if array[i] < array[j]:
temp = array[i]
for k in range(i - 1, j - 1, -1):
array[k + 1] = array[k]
array[j] = temp
break
return array
print(better_insert_sort([4, 5, 6, 1, 3, 2, 1, 3, 5, 23, 134, 45, 1, 4, 5]))
print(insert_sort([4, 5, 6, 1, 3, 2, 1, 3, 5, 23, 134, 45, 1, 4, 5]))
print(list(range(0, 1)), list(range(5, 1, -1)))
|
11ff275bba81d2ddcf7713f4849d3b392f60a824 | palfi-andras/NBAPredictor | /NBAPredictor/core/positions.py | 1,029 | 4.0625 | 4 | from enum import Enum
class Position(Enum):
"""
An enum to represent the types of positions that are possible for Players to play in the NBA
"""
PG = 1 # Point Guard
SG = 2 # Shooting Guard
SF = 3 # Small Forward
PF = 4 # Power Forward
C = 5 # Center
def convert_to_position(char: str) -> Position:
"""
Converts a char into the appropriate Position, if any exists.
Parameters
----------
char: str
A string that represents an NBA position
Returns
-------
Position
The Position represented by the string
Raises
------
RuntimeError
If the characters cannot be converted into a Positional entry
"""
if char == 'PG':
return Position.PG
elif char == 'SG':
return Position.SG
elif char == 'SF':
return Position.SF
elif char == 'PF':
return Position.PF
elif char == 'C':
return Position.C
else:
raise RuntimeError(f"Unrecognized position: {char}")
|
064ebb94b84b0d3cddfacef52d391590f16ebfd6 | a652895216/example_of_qianduan | /pachong2/pachong4 xml.py | 1,858 | 3.65625 | 4 | #xml 就是传数据 w3school
#xpath 是一门查找信息的工具 w3cschool 开发工具chrome插件 百度安装
'''
1.常用路径表达式:选取此节点的所有子节点
/:从根节点开始
//:选取元素,而不考虑元素的具体为止
. :当前节点
.. :父节点
@ :选取属性
2. 谓语(predicates)
谓语用来精确查找
/bookstore/book[1] :选取第一个属于bookstore下的叫book的元素
/bookstore/book[last()]: 选取最后一个
/bookstore/book[last()-1]:选取最后第二个
/bookstore/book[position()<3] 选取前两个
/bookstore/book[@lang]: 选取含lang的属性
/bookstore/book[@lang='cn']: 选取含lang=cn的属性的元素
/bookstore/book[@price<90]: 选取含price中小于90的属性的元素
/bookstore/book[@price<90]/title: 选取含price中title标签中小于90的属性的元素
3.通配符
- * :任何元素节点
- @* :匹配任何属性节点
- node():匹配任何类型的节点
4.选取多个路径
- //book/title | //book/author :选取book元素中title和author元素
- //title | //price :选取文档中所有的title和price元素
#lxml库
- python的html/xml 的解析器
官方文档: http://lxml.de/index.html
案例如下
'''
from lxml import etree
text = '''
<div>
<ul>
<li class="item-0"> <a href="0.html">first item</a> </li>
</ul>
</div>
'''
html = etree.HTML(text)
s = etree.tostring(html)
print(s)
html0 = etree.parse("pa.html")
print(type(html0))
rst0 = html0.xpath("//book")
print(rst0)
rst1 = html0.xpath('//book[@category="learn"]') #谓语用中括号
print(rst1)
rst1 = html0.xpath('//book[@category="learn"]/year') #谓语用中括号
rst1 = rst1[0]
print(rst1.tag) #打出标签year
print(rst1.text) #打出标签内容2018
print(rst1)
rst = etree.tostring(html,pretty_print=True)
print(rst)
|
858fc3582a0f8395546821ee85868fe34f0c7f9d | koalaboy808/Labor2Day_2.0 | /viewdatabase.py | 616 | 3.703125 | 4 | #!/usr/bin/python
import sqlite3
conn = sqlite3.connect('app.db')
print "Opened database successfully";
cursor = conn.execute("SELECT username, _password from Employers")
for row in cursor:
print "USERNAME = ", row[0]
print "PASSWORD = ", row[1], "\n"
cursor2 = conn.execute("SELECT request_title, emp_id from employer_request")
for row in cursor2:
print "REQUEST TITLE = ", row[0]
print "ASSOCIATED EMPLOYER = ", row[1], "\n"
cursor3 = conn.execute("SELECT laborer_first_name from laborer")
for row in cursor3:
print "NAME = ", row[0], "\n"
print "Operation done successfully";
conn.close() |
59b70ab9dc9a22d789f298055688447afdc8c7af | yskang/AlgorithmPractice | /leetCode/valid_parentheses.py | 536 | 3.546875 | 4 | # Title: Valid Parentheses
# Link: https://leetcode.com/problems/valid-parentheses/
class Problem:
def is_valid(self, s: str) -> bool:
last_len = len(s)
while s:
s = s.replace('()', '').replace('[]', '').replace('{}', '')
if len(s) == last_len:
break
last_len = len(s)
return not len(s)
def solution():
s = "()[[]{}]{"
problem = Problem()
return problem.is_valid(s)
def main():
print(solution())
if __name__ == '__main__':
main() |
02446cc7e567e30ce3fe9d71ac7263345bb88981 | cinvilla/Python_Class10272018 | /Materia Vista en Clase/command_class_forloops10272018.py | 1,315 | 4.375 | 4 | # Primer ejemplo con loops - for
for indice, elemento in enumerate (['maria', 'jose', 'pedro', 'juan']):
print('El indice {} para el valor {}' .format(indice, elemento))
# enumerate - para obtener el índice de posición junto a su valor correspondiente.
# Primer ejemplo con loops - for
print()
for indice, elemento in enumerate(['maria', 'jose', 'pedro', 'juan']):
print(f'El indice {indice} para el valor {elemento}')
# en reversa -1
print()
mi_lista = ['maria', 'jose', 'pedro', 'juan']
for indice, elemento in enumerate(mi_lista[::-1]):
print(f'El indice {indice} para el varlor {elemento}')
# lista.sort ordena la lista en sí, pero con sorted es distinto
print()
mi_lista = ['maria', 'jose', 'pedro', 'juan']
for indice, elemento in enumerate(sorted(mi_lista)):
print(f'El indice {indice} para el varlor {elemento}')
print()
mi_lista = ['maria', 'jose', 'pedro', 'juan']
for indice, elemento in enumerate(sorted(mi_lista, reverse=True)):
print(f'El indice {indice} para el varlor {elemento}')
# Para que el loop no inicie se agrega [] a la lista
mi_lista = ['maria', 'jose', 'pedro', 'juan']
for indice, elemento in enumerate(sorted(mi_lista)):
print(f'El indice {indice} para el varlor {elemento}')
else:
print('El loop no empezó')
## Print test using list sequences
|
52409b17f224a2cfc11156c218968188885abacb | oscarliu99/partia-flood-warning-system | /floodsystem/geo.py | 4,814 | 3.71875 | 4 | # Copyright (C) 2018 Garth N. Wells
#
# SPDX-License-Identifier: MIT
"""This module contains a collection of functions related to
geographical data.
"""
from .utils import sorted_by_key # noqa
from floodsystem.stationdata import build_station_list
from math import radians, cos, sin, asin, sqrt
def haversine(point1, point2, unit='km'):
""" Calculate the great-circle distance between two points on the Earth surface.
:input: two 2-tuples, containing the latitude and longitude of each point
in decimal degrees.
Keyword arguments:
unit -- a string containing the initials of a unit of measurement (i.e. miles = mi)
default 'km' (kilometers).
Example: haversine((45.7597, 4.8422), (48.8567, 2.3508))
:output: Returns the distance between the two points.
The default returned unit is kilometers. The default unit can be changed by
setting the unit parameter to a string containing the initials of the desired unit.
Other available units are miles (mi), nautic miles (nmi), meters (m),
feets (ft) and inches (in).
"""
# mean earth radius - https://en.wikipedia.org/wiki/Earth_radius#Mean_radius
AVG_EARTH_RADIUS_KM = 6371.0088
# Units values taken from http://www.unitconversion.org/unit_converter/length.html
conversions = {'km': 1,
'm': 1000,
'mi': 0.621371192,
'nmi': 0.539956803,
'ft': 3280.839895013,
'in': 39370.078740158}
# get earth radius in required units
avg_earth_radius = AVG_EARTH_RADIUS_KM * conversions[unit]
# unpack latitude/longitude
lat1, lng1 = point1
lat2, lng2 = point2
# convert all latitudes/longitudes from decimal degrees to radians
lat1, lng1, lat2, lng2 = map(radians, (lat1, lng1, lat2, lng2))
# calculate haversine
lat = lat2 - lat1
lng = lng2 - lng1
d = sin(lat * 0.5) ** 2 + cos(lat1) * cos(lat2) * sin(lng * 0.5) ** 2
return 2 * avg_earth_radius * asin(sqrt(d))
def stations_by_distance(stations, p):
#Calculates distance from p to all stations, then orders them in order from
#nearest station to furthest away
#create empty list
list_of_tuples = []
for q in stations:
#calculates distance of station from p
distance = haversine(q.coord, p)
#creates tuple with the name, town and distance (calculated above) of station
tuple_of_station = (q.name, q.town, distance)
#adds this tuple to the list
list_of_tuples.append(tuple_of_station)
return sorted_by_key(list_of_tuples, 2)
def rivers_with_station(stations):
#creates an empty list of rivers with stations
rivers = []
#adds river to list if it is not already in the list
for r in stations:
river = r.river #sets variable as the river name
#removes 'river' from the names
if river.startswith('River'):
rivers.append(river[:6]) #adds all of the string after 'River' '-space-' to the list
else:
rivers.append(river)
return set(rivers)
def stations_by_river(stations):
#produces a dictionary where the river names are the key, and the stations on that river are the value
river_with_stations = dict() #empty dictionary
for i in stations:
if i.river in river_with_stations: #if river is already a key in the dictionary
river_with_stations[i.river].append(i.name) #adds the name of the station to the list of values
else:
river_with_stations[i.river] = [i.name] #adds this river to the dictionary with the station name
return (river_with_stations)
def stations_within_radius(stations, centre, r):
list_stations=[] #produce an empty list
for i in stations:
distance = haversine(i.coord, centre) #find distances from stations to centre
station_name = (i.name)
if distance <= r:
list_stations.append(station_name) #put names of stations that are in the circle in the list
return list_stations
def rivers_by_station_number(stations,N):
stations_within_rivers = stations_by_river(stations) #dictiory which contains rivers as key and stations within each river as value
station_numbers = {key: len(value) for key, value in stations_within_rivers.items()} #a new dictionary which convert lists of stations to numbers of stations
value = sorted(station_numbers.items(), key=lambda x: x[1], reverse= True) #sort the new dictionary
result = value[:N] #top n rivers in the dictionary
while value[N-1][1]==value[N][1]:
result.append(value[N]) #in case there is rivers with equal number of stations, also add those rivers to the list
N+=1
return result |
2726bb722478687e2c18d793f6dfab2809ac7d88 | LeoneVeneroni/python | /exercicios/Aula15/aula15_exercicio1.py | 2,782 | 3.875 | 4 | class MeuTempo :
def __init__ (self , hrs = 0 , mins = 0 , segs = 0):
""" Criar um novo objeto MeuTempo inicializado para hrs, min, segs.
Os valores de mins e segs podem estar fora do intervalo de 0-59,
mas o objecto MeuTempo resultante será normalizado. """
# Calcular total de segundos para representar
self.totalsegs = hrs * 3600 + mins * 60 + segs
self.horas = self.totalsegs // 3600 # Divisão em h, m, s
restosegs = self.totalsegs % 3600
self.minutos = restosegs // 60
self.segundos = restosegs % 60
if self.horas >= 24:
self.horas = self.horas%24
def to_seconds (self):
"" "Retorna o número de segundos representados por esta instância " ""
return self.totalsegs
def __add__ (self, other):
""" Retorna a soma do tempo atual e outro, para utilizar com o símbolo + """
return MeuTempo (0, 0, self.to_seconds() + other.to_seconds())
def __sub__ (self, other):
""" Retorna a soma do tempo atual e outro, para utilizar com o símbolo - """
return MeuTempo (0, 0, self.to_seconds() - other.to_seconds())
def __str__ (self):
return f'{self.horas}:{self.minutos}:{self.segundos}'
def add_time (t1, t2):
h = t1.horas + t2.horas
m = t1.minutos + t2.minutos
s = t1.segundos + t2.segundos
while s >= 60:
s = s - 60
m = m + 1
while m >= 60:
m = m - 60
h = h + 1
sum_t = MeuTempo (h, m, s)
return sum_t
def incremento (t, segs):
t.segundos += segs
while t.segundos >= 60:
t.segundos -= 60
t.minutos += 1
while t.minutos >= 60:
t.minutos -= 60
t.horas += 1
def depois (self, time2):
"" "Retorna True se self for estritamente maior que time2" ""
if self.horas > time2.horas:
return True
if self.horas < time2.horas:
return False
if self.minutos > time2.minutos:
return True
if self.minutos < time2.minutos:
return False
if self.segundos > time2.segundos:
return True
return False
t1 = MeuTempo(12, 30, 26)
t2 = MeuTempo(10, 52, 36)
print(t1, t2)
print(t1 + t2)
print(t1 - t2)
print(t1.depois(t2)) # Mostra se é True ou False que t1 vem depois de t2
hora_atual = MeuTempo(11, 59, 30)
tempo_bolo = MeuTempo(18, 40, 190)
bolo_pronto = MeuTempo.add_time(hora_atual, tempo_bolo)
hora_atual.incremento(500) # incrementar em 500 segundos = 6 minutos e 20 segundos
print(hora_atual)
print(bolo_pronto)
|
ebecca8802c68d87f0c447eea2dee2261f0a098f | KorryKo/PythonPractice | /python-check/while «Количество четных элементов последовательности» _The number of even elements of a sequence_.py | 392 | 4.09375 | 4 | # «Количество четных элементов последовательности» "The number of even elements of a sequence"
# Определите количество четных элементов в последовательности, завершающейся числом 0.
n = -1
i = -1
while n != 0:
n = int(input())
if n % 2 == 0:
i += 1
print(i)
|
a0230d829227619ca7fed70823ec06d5c2a8ec4d | torenord/julekalender | /luke7.py | 417 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Luke 7
# Finn summen av alle positive heltall mellom 0 og 1000 som er har 7
# som en primtallsfaktor, der det reverserte tallet også har 7 som en
# primtallsfaktor.
# For eksempel teller 259 da en får 952 om en reverserer sifrene og
# begge disse tallene har 7 som en primtallsfaktor.
print sum(i for i in range(0, 1000+1) if i % 7 == int(str(i)[::-1]) % 7 == 0)
|
d9e1307745e50b054898fe89276818ece0cc7428 | 9zemel/python_course | /LessonSixth/diary.py | 134 | 3.625 | 4 | name = input("Enter you diary's name")
with open(name, 'a') as diary:
data = input('Enter your topic:\n')
diary.write(data)
|
fafa37c81f2d38c75741594fbee51511f7a2f647 | huayuhui123/prac05 | /word_occurrences.py | 263 | 3.75 | 4 | sentence={}
for word in input("Text:").split():
if word in sentence:
sentence[word]+=1
else:
sentence[word]=1
n=max(len(word) for word in sentence)
for key,value in sorted(sentence.items()):
print("{:<{}}{}".format((key+':'),n,value))
|
5808f003ea584c27c5ca885f7841293a6f30c141 | iamyoungjin/algorithms | /Basic/prime_number_basic.py | 333 | 3.734375 | 4 | #basic
#소수 판별 함수 (2이상의 자연수에 대해)
#시간 복잡도 : O(X)
def is_prime_number(x):
for i in range(2,x): #2부터 (x-1)까지 모든 수를 확인하며 x가 해당 수로 나누어 떨어지면 소수가 아님
if x%i == 0:
return False
return True
print(is_prime_number(7)) |
22adba30fa0648a2b41ec230fad4a998853236c7 | sukilau/data-structures-and-algorithms | /python/slliststack.py | 1,093 | 3.96875 | 4 | '''
Implementation of Stack using Singly Linked List
Basic operations:
get(i) O(n)
set(i,x) O(n)
add(i,x) O(n)
remove(i) O(n)
push(x) O(1)
pop() O(1)
peek() O(1)
getSize() O(1)
isEmpty() O(1)
'''
class Stack(object):
class Node(object):
def __init__(self, x):
self.value = x
self.next = None
def __init__(self):
self._initialize()
def _initialize(self):
self.size = 0
self.head = None
self.tail = None
def new_node(self, x):
return Stack.Node(x)
def push(self, x):
'''Add new node with value x at the start'''
u = self.new_node(x)
u.next = self.head
self.head = u
if self.size == 0:
self.tail = u
self.size += 1
return x
def pop(self):
'''Remove node at the start'''
if self.size == 0:
return None
u = self.head
self.head = u.next
if self.size == 1:
self.tail = None
self.size -= 1
return u.value
def peek(self):
'''Return node value at the start'''
return self.head.value
def getSize(self):
'''Return size'''
return self.size
def isEmpty(self):
'''Check if empty'''
return self.size == 0 |
22a462de8d06ea2a477ecba0aa1ac68c6b4387b0 | littleliona/leetcode | /medium/138.copy_list_with_random_pointer.py | 2,033 | 3.625 | 4 | # Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
#method_fast
dic = dict()
m = n = head
while m:
dic[m] = RandomListNode(m.label)
m = m.next
while n:
dic[n].next = dic.get(n.next)
dic[n].random = dic.get(n.random)
n = n.next
return dic.get(head)
#method O(n) O(1)
if not head:
return None
pre = m = head
while m:
node = RandomListNode(m.label)
m = m.next
pre.next = node
node.next = m
pre = m
m = head
while m:
if m.random:
m.next.random = m.random.next
m = m.next.next
newhead = head.next
pold = head
pnew = newhead
while pnew.next:
pold.next = pnew.next
pold = pold.next
pnew.next = pold.next
pnew = pnew.next
pold.next = None
pnew.next = None
return newhead
#method_mine
if not head:
return None
current = head
pre = new_haad = RandomListNode(current.label)
L = [new_haad]
while current:
if current.next:
pre.next = RandomListNode(current.next.label)
L.append(pre.next)
if current.random:
if current.random not in L:
pre.random = RandomListNode(current.random.label)
else:
pre.random = L[L.index(current.random)]
pre = pre.next
current = current.next
return new_haad
s = Solution()
a = s.partition('aab')
print(a)
|
12a33a3a7db19a8ed155f0a1a668d595054e07cb | JanSnobl/Madlibs | /madlibs.py | 2,086 | 4.125 | 4 | """ this program is telling story and you have to answer if the question is asked
Jan Snobl
"""
#The template for the story
STORY = "This morning I woke up and felt %s because %s was going to finally %s over the big %s %s. On the other side of the %s were many %ss protesting to keep %s in stores. The crowd began to %s to the rhythm of the %s, which made all of the %s very %s. %s tried to %s into the sewers and found %s rats. Needing help, %s quickly called %s. %s appeared and saved %s by flying to %s and dropping %s into a puddle of %s. %s then fell asleep and woke up in the year %s, in a world where %ss ruled the world."
# inform user about game is in progress
print("Mad Libs started")
# user must name his main character
name = str(input("What is your name ?"))
# user must write adjective
adjective1 = str(input("Write some adjective: "))
adjective1 = str(adjective1)
# user must write adjective
adjective2 = str(input("Write second adjective: "))
# user must write adjective
adjective3 = str(input("Write third adjective: "))
# user must write verb
verb1 = str(input("Write some verb: "))
# user must write verb
verb2 = str(input("Write second verb: "))
# user must write verb
verb3 = str(input("Write last verb: "))
# user must write noun
noun1 = str(input("Write first noun: "))
# user must write noun
noun2 = str(input("Write second noun: "))
# user must write noun
noun3 = str(input("Write last noun: "))
print("It is gonna get funny")
# user writes list of things
animal = str(input("write some animal: "))
food = str(input("write some food: "))
fruit = str(input("write some fruit: "))
number = str(input("write some number: "))
superhero = str(input("write superhero name: "))
country = str(input("write some country: "))
dessert = str(input("write some dessert: "))
year = str(input("write some year: "))
# printing story and inserting inputs
print(STORY) % (adjective1, name, adjective2, adjective3, verb1, verb2, verb3, noun1, noun2, noun3, animal, food, fruit, number, superhero, country, dessert, year)
# There is some mistake in last line of code FIX THAT |
4cd3e5d16ea83232b6c2f51ad70a9cf3662ea44d | uibcdf/OpenPocket | /openpocket/alpha_spheres/alpha_spheres.py | 7,902 | 3.90625 | 4 | import numpy as np
from scipy.spatial import Voronoi
from scipy.spatial.distance import euclidean
class AlphaSpheres():
"""Set of alpha-spheres
Object with a set of alpha-spheres and its main attributes such as radius and contacted points
Attributes
----------
points : ndarray (shape=[n_points,3], dtype=float)
Array of coordinates in space of all points used to generate the set of alpha-spheres.
n_points: int
Number of points in space to generate the set of alpha-spheres.
centers: ndarray (shape=[n_alpha_spheres,3], dtype=float)
Centers of alpha-spheres.
radii: ndarray (shape=[n_alpha_spheres], dtype=float)
Array with the radii of alpha-spheres.
points_of_alpha_sphere: ndarray (shape=[n_alpha_spheres, 4], dtype=int)
Indices of points in the surface of each alpha-sphere.
n_alpha_spheres: int
Number of alpha-spheres in the set.
"""
def __init__(self, points=None):
"""Creating a new instance of AlphaSpheres
With an array of three dimensional positions (`points`) the resultant set of alpha-spheres is returned
as a class AlphaSpheres.
Parameters
----------
points: ndarray (shape=[n_points,3], dtype=float)
Array with the three dimensional coordinates of the input points.
Examples
--------
See Also
--------
Notes
-----
"""
self.points=None
self.n_points=None
self.centers=None
self.points_of_alpha_sphere=None
self.radii=None
self.n_alpha_spheres=None
if points is not None:
# Checking if the argument points fulfills requirements
if isinstance(points, (list, tuple)):
points = np.array(points)
elif isinstance(points, np.ndarray):
pass
else:
raise ValueError("The argument points needs to be a numpy array with shape (n_points, 3)")
if (len(points.shape)!=2) and (points.shape[1]!=3):
raise ValueError("The argument points needs to be a numpy array with shape (n_points, 3)")
# Saving attributes points and n_points
self.points = points
self.n_points = points.shape[0]
# Voronoi class to build the alpha-spheres
voronoi = Voronoi(self.points)
# The alpha-spheres centers are the voronoi vertices
self.centers = voronoi.vertices
self.n_alpha_spheres = self.centers.shape[0]
# Let's compute the 4 atoms' sets in contact with each alpha-sphere
self.points_of_alpha_sphere = [[] for ii in range(self.n_alpha_spheres)]
n_regions = len(voronoi.regions)
region_point={voronoi.point_region[ii]:ii for ii in range(self.n_points)}
for region_index in range(n_regions):
region=voronoi.regions[region_index]
if len(region)>0:
point_index=region_point[region_index]
for vertex_index in region:
if vertex_index != -1:
self.points_of_alpha_sphere[vertex_index].append(point_index)
for ii in range(self.n_alpha_spheres):
self.points_of_alpha_sphere[ii] = sorted(self.points_of_alpha_sphere[ii])
# Let's finally compute the radius of each alpha-sphere
self.radii = []
for ii in range(self.n_alpha_spheres):
radius = euclidean(self.centers[ii], self.points[self.points_of_alpha_sphere[ii][0]])
self.radii.append(radius)
self.points_of_alpha_sphere = np.array(self.points_of_alpha_sphere)
self.radii = np.array(self.radii)
def remove_alpha_spheres(self, indices):
"""Removing alpha-spheres from the set
The method removes from the set those alpha-spheres specified by the input argument
`indices`.
Parameters
----------
indices : numpy.ndarray, list or tuple (dtype:ints)
List, tuple or numpy.ndarray with the integer numbers corresponding to the alpha-sphere
indices to be removed from the set.
Examples
--------
"""
mask = np.ones([self.n_alpha_spheres], dtype=bool)
mask[indices] = False
self.centers = self.centers[mask,:]
self.points_of_alpha_sphere = self.points_of_alpha_sphere[mask,:]
self.radii = self.radii[mask]
self.n_alpha_spheres = np.count_nonzero(mask)
def remove_small_alpha_spheres(self, minimum_radius):
indices_to_remove = np.where(self.radii < minimum_radius)
self.remove_alpha_spheres(indices_to_remove)
def remove_big_alpha_spheres(self, maximum_radius):
indices_to_remove = np.where(self.radii > maximum_radius)
self.remove_alpha_spheres(indices_to_remove)
def get_points_of_alpha_spheres(self, indices):
"""Get the points in contact with a subset of alpha-spheres
The list of point indices accounting for the points in contact with a subset of alpha-spheres is calculated.
Parameters
----------
indices : numpy.ndarray, list or tuple (dtype:ints)
List, tuple or numpy.ndarray with the alpha-sphere indices defining the subset.
Return
------
points_of_alpha_spheres : list
List of point indices in contact with one or more alpha-spheres of the subset.
Examples
--------
>>> import openpocket as opoc
>>> points = ([[-1., 2., 0.],
>>> [ 0., 2., 1.],
>>> [ 1., -2., 1.],
>>> [ 0., 1., 1.],
>>> [ 0., 0., 0.],
>>> [-1., -1., 0.]])
>>> aspheres = opoc.AlphaSpheres(points)
>>> aspheres.get_points_of_alpha_spheres([1,3])
[0,2,3,4,5]
"""
point_indices = set([])
for index in indices:
point_indices = point_indices.union(set(self.points_of_alpha_sphere[index]))
return list(point_indices)
def view(self, view=None, indices='all'):
"""3D spatial view of alpha-spheres and points
An NGLview view is returned with alpha-spheres (gray color) and points (red color).
Parameters
----------
indices : numpy.ndarray, list or tuple (dtype:ints)
List, tuple or numpy.ndarray with the alpha-sphere indices defining the subset.
Returns
-------
view : nglview
View object of NGLview.
Examples
--------
>>> import openpocket as opoc
>>> points = ([[-1., 2., 0.],
>>> [ 0., 2., 1.],
>>> [ 1., -2., 1.],
>>> [ 0., 1., 1.],
>>> [ 0., 0., 0.],
>>> [-1., -1., 0.]])
>>> aspheres = opoc.alpha_spheres.AlphaSpheresSet(points)
>>> view = aspheres.view([1,3])
>>> view
"""
if view is None:
import nglview as nv
view = nv.NGLWidget()
point_indices = []
if indices=='all':
indices=range(self.n_alpha_spheres)
point_indices=range(self.n_points)
else:
point_indices=self.get_points_of_alpha_spheres(indices)
for index in point_indices:
atom_coordinates = self.points[index,:]
view.shape.add_sphere(list(atom_coordinates), [0.8,0.0,0.0], 0.2)
for index in indices:
sphere_coordinates = self.centers[index,:]
sphere_radius = self.radii[index]
view.shape.add_sphere(list(sphere_coordinates), [0.8,0.8,0.8], sphere_radius)
return view
|
Subsets and Splits