blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
8a1a67998fff7179711b94c7334b7378fe723c4a | jaymaity/BusinessCanada | /Lib/Stringer.py | 497 | 3.640625 | 4 | """Modifies string functions"""
def is_number(s):
"""
Check if a string is a number or not
:return:
"""
try:
float(s)
return True
except ValueError:
pass
try:
import unicodedata
unicodedata.numeric(s)
return True
except (TypeError, ValueError):
pass
return False
def remove_quote(s):
"""
removes quotes and replace with blank
:param s:
:return:
"""
return s.replace("\"", " ")
|
69d605345e2b88851c85f217c548612befaeae1b | daniel-reich/ubiquitous-fiesta | /ZDDyfBFBWMotQSYin_13.py | 137 | 3.578125 | 4 |
def is_harshad(num):
sum_of_digits = sum(int(x) for x in str(num))
return num%sum_of_digits == 0 if sum_of_digits > 0 else False
|
229c613e05a1853e5673dea7b0c6bfc9a091b433 | mwolffe/my-isc-work | /advanced_python/arrays_numpy.py | 383 | 3.625 | 4 | import numpy as np
x = list(range(1,11))
a = np.zeros((3,2), dtype=np.float64) #creates a 64 bit 3x2 array of zeros
a1 = np.array(x, dtype=np.int32) #converts a list to an array of integers
a2 = np.array(x, dtype=np.float64)#converts a list to an array of floats
#print(x.dtype) - doesn't work as this is a list not an array
print(a1)
print(a1.dtype)
print(a2)
print(a2.dtype)
|
f9805ce26c751ec79b5932b2dbaf6176653f3803 | samr87/AI-Homework-2 | /hw2.py | 1,648 | 3.765625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 9 17:08:36 2020
@author: computer realm
"""
class Agent:
def __init__(self,n,x,y):
# this defines the class as self.
self.name = n
self.xPos = x
self.yPos = y
def move(self,d):
direc = d
if direc == "left": # && left is not a border
self.xPos = self.xPos - 1
elif direc == "right": # && right is not a border
self.xPos = self.xPos + 1
elif direc == "up": # && up is not a border
self.yPos = self.yPos + 1
elif direc == "down": # && down is not a border
self.yPos = self.yPos - 1
else:
print("There is an obstacle in that direction!")
def printLocation(self):
print("The bot's location is: " + self.xPos + " by " + self.yPos + " on the grid.")
def retXposition(self):
return self.xPos
def retYpos(self):
return self.yPos
def pickUp():
# if environment firty, then suck
# else environment clean, then move or something, idk.
#class Environment:
# determines whether a spot is clean or dirty?
|
b9cf55700b1458e947d3073d93134ba109a51d25 | ManikSharma001/SimpleCalculator | /calculator.py | 912 | 4.1875 | 4 | #Simple Calculator with Python
def addition(numOne, numTwo):
return (numOne + numTwo)
def subtraction(numOne, numTwo):
return(numOne - numTwo)
def multiplication(numOne, numTwo):
return(numOne * numTwo)
def division(numOne, numTwo):
return(numOne / numTwo)
response = ""
while response != "n".lower():
print("What is the First Number?")
fnum = float(input())
print("What Operation would you like to perform?")
operation = input()
print("What is the Second Number?")
snum = float(input())
if operation[0].lower() == "a":
addition(fnum, snum)
elif operation[0].lower() == "s":
subtraction(fnum, snum)
elif operation[0].lower() == "m":
multiplication(fnum, snum)
else:
division(fnum, snum)
print("Would You Like to Continue with this Answer (Press 'n' for no)?")
response = input()
|
985d229e98a391bd5f1c9ac05017989f1bf2c601 | wingedrasengan927/Python-tutorials | /Pythontut2 - looping.py | 1,723 | 4.15625 | 4 |
# printing odd numbers using for loop
for i in range(20):
if i % 2 != 0:
print(i)
# rounding off float type
your_float = input('Enter a floating point ')
your_float = float(your_float)
print("the value rounded off to two decimals is {:.2f}".format(your_float))
# Problem : Have user input their invest and expected interest each year
# After each year earning = investment + investment * interest
# print out the earning after 10 year period
investment, interest, No_of_Years = input('Enter the amount invested, the interest'+
' expected, time period ').split()
investment = float(investment)
interest = float(interest) * .01
No_of_Years = int(No_of_Years)
for i in range(No_of_Years):
earning = investment + investment*interest
print('the earning after {} years is {:.2f}'.format(No_of_Years, earning))
# imp* floating point calculations are only precise upto 16 digits
# Random Numbers
import random
for i in range(50):
rand_Num = random.randrange(1, 51)
print(rand_Num)
# continue jumps back again into the loop
# break jumps out of the loop
# print even numbers using while loop
i = 1
while i <= 20:
i += 1
if i % 2 != 0:
continue
print(i)
# Problem : Print out a pine tree taking number of rows as input
# how to print without a new line ; print("xyz",end="")
# how to print without space in between ; print("xyz", "abc", sep="")
rows = input('Enter the number of rows ')
rows = int(rows)
space = rows - 1
stars = 1
for i in range(rows):
for j in range(space):
print(" ", end=" ")
for k in range(stars):
print('*', end= " ")
print('\n')
space = space - 1
stars = stars + 2
|
4972037b410edc63adce205ca2514ae228fd1f9f | weady/python | /thread/python.multi.process.thread.py | 7,559 | 3.515625 | 4 | #/usr/bin/python
#coding=utf8
#
# 进程通信
import os,random,time
from multiprocessing import Pool, Queue, Process
import multiprocessing
import threading
‘’‘
Queue的功能是将每个核或线程的运算结果放在队里中,等到每个线程或核运行完毕后再从队列中取出结果
继续加载运算。原因很简单,多线程调用的函数不能有返回值,所以使用Queue存储多个线程运算的结果
pool = mp.Pool()
有了池子之后,就可以让池子对应某一个函数,我们向池子里丢数据,池子就会返回函数返回的值。
Pool和之前的Process的不同点是丢向Pool的函数有返回值,而Process的没有返回值
接下来用map()获取结果,在map()中需要放入函数和需要迭代运算的值
Pool默认大小是CPU的核数,我们也可以通过在Pool中传入processes参数即可自定义需要的核数量
pool = mp.Pool(processes=3)
res = pool.map(job, range(10))
print(res)
apply_async()中只能传递一个值,它只会放入一个核进行运算,但是传入值时要注意是可迭代的
所以在传入值后需要加逗号, 同时需要用get()方法获取返回值
# 用get获得结果
print(res.get())
# 迭代器,i=0时apply一次,i=1时apply一次等等
multi_res = [pool.apply_async(job, (i,)) for i in range(10)]
# 从迭代器中取出
print([res.get() for res in multi_res])
共享内存:
import multiprocessing as mp
value1 = mp.Value('i', 0)
value2 = mp.Value('d', 3.14)
其中d和i参数用来设置数据类型的,d表示一个双精浮点类型,i表示一个带符号的整型
array = mp.Array('i', [1, 2, 3, 4]) 一维数组
l = mp.Lock() # 定义一个进程锁
v = mp.Value('i', 0) # 定义共享内存
l.acquire() # 锁住
do something
l.release() # 释放
线程模块常用函数:
threading.active_count() #活跃线程数
threading.enumerate() #线程信息
threading.current_thread() #当前线程
add_thread = threading.Thread(target=thread_job,) # 定义线程
add_thread.start() #启动线程
add_thread.join() #主线程等待子线程全部运行完后才开始运行
q.get() #从队列中获取值
lock在不同线程使用同一共享内存时,能够确保线程之间互不影响,使用lock的方法是
在每个线程执行运算修改共享内存之前,执行lock.acquire()将共享内存上锁
确保当前线程执行时,内存不会被其他线程访问,执行运算完毕后,使用lock.release()将锁打开
保证其他的线程可以使用该共享内存
’‘’
#----------------------------------进程和进程池---------------------------------------------------------
def run_proc(name):
print "Child process %s (%s) Running....." % (name,os.getpid())
def creat_process():
print "Parent process %s " % os.getpid()
for i in range(5):
p = Process(target=run_proc,args=(str(i),))
print "Process will start"
p.start()
p.join()
print "Process end"
def run_pool_proc(name):
print "task %s (pid = %s) is runngin.... " %(name,os.getpid())
time.sleep(random.random() * 3)
print 'task %s end' % name
def create_pool_process():
print 'current process %s ' % os.getpid()
p = Pool(processes=3)
for i in range(5):
p.apply_async(run_pool_proc,args=(i,))
print 'waiting for all subprocesses done...'
p.close()
p.join()
print 'all subprocesses done'
#----------------------------------多进程---------------------------------------------------------
#进程池通信
def run_pool_pro(name):
print 'task %s (pid=%s) is running....' % (name,os.getpid())
time.sleep(random.random() * 3)
print 'task %s end.' % name
def create_pool_pro():
print 'current process %s' % os.getpid()
p = Pool(processes=3)
for i in range(5):
p.apply_async(run_pool_pro,args=(i,))
print 'waiting for all subprocesses done'
p.close()
p.join()
print 'all subprocesses done'
#---------------------------------------------------------
#进程间通信 queue 队列
#写进程
def proc_write(q,urls):
print 'process (%s) is writing....' % os.getpid()
for url in urls:
q.put(url)
print 'put %s to queue.....' % url
time.sleep(random.random())
#读进程
def proc_read(q):
print 'process (%s) is reading....' % os.getpid()
while True:
url = q.get(True)
print 'get %s from queue' % url
def proc_queue():
q = Queue()
proc_writer1 = Process(target=proc_write,args=(q,['url_1','url_2','url_3']))
proc_writer2 = Process(target=proc_write,args=(q,['url_4','url_5','url_6']))
proc_reader = Process(target=proc_read,args=(q,))
#启动写进程
proc_writer1.start()
proc_writer2.start()
#启动读进程
proc_reader.start()
#等待写进程结束
proc_writer1.join()
proc_writer2.join()
#读进程是死循环,无法等待其结束,只能强制终止
proc_reader.terminate()
#进程间通信 pipe
def proc_pipe_send(pipe,urls):
for url in urls:
print "Process (%s) send: %s " % (os.getpid(),url)
pipe.send(url)
time.sleep(random.random())
def proc_pipe_recv(pipe):
while True:
print 'Process (%s) rev: %s' % (os.getpid(),pipe.recv())
time.sleep(random.random())
def proc_pipe():
pipe = multiprocessing.Pipe()
p1 = multiprocessing.Process(target=proc_pipe_send,args=(pipe[0],['url_' + str(i) for i in range(10)]))
p2 = multiprocessing.Process(target=proc_pipe_recv,args=(pipe[1],))
p1.start()
p2.start()
p1.join()
p2.terminate()
#----------------------------------多线程---------------------------------------------------------
#
def thread_run_01(urls):
print 'current %s is running...' % threading.current_thread().name
for url in urls:
print '%s ----> %s' % (threading.current_thread().name,url)
time.sleep(random.random())
print '%s ended' % threading.current_thread().name
def create_thread_01():
print '%s is running...' % threading.current_thread().name
t1 = threading.Thread(target=thread_run_01,name='Thread_01',args=(['url_01','url_02'],))
t2 = threading.Thread(target=thread_run_01,name='Thread_02',args=(['url_03','url_04'],))
t1.start()
t2.start()
t1.join()
t2.join()
print '%s ended' % threading.current_thread().name
#从threading.Thread继承创建线程类
class myThread(threading.Thread):
def __init__(self,name,urls):
threading.Thread.__init__(self,name=name)
self.urls = urls
def run(self):
print 'current %s is running' % threading.current_thread().name
for url in self.urls:
print '%s ----> %s' % (threading.current_thread().name,url)
time.sleep(random.random())
print '%s ended' % threading.current_thread().name
def create_thread_02():
print '%s is running...' % threading.current_thread().name
t1 = myThread(name='Thread_01',urls=['url_01','url_02'])
t2 = myThread(name='Thread_02',urls=['url_03','url_04'])
t1.start()
t2.start()
t1.join()
t2.join()
print '%s ended' % threading.current_thread().name
if __name__ == '__main__':
#create_pool_pro()
#proc_queue()
#proc_pipe()
#create_thread_01()
create_thread_02()
if __name__ == '__main__':
create_pool_process()
|
949fa53ec88029692060d644a2ce0725e5a7f2ac | LFBianchi/pythonWs | /Learning Python/function_study.py | 558 | 3.5625 | 4 | def min1(*args):
res = args[0]
for arg in args[1:]:
if arg < res:
res = arg
return res
def min2(first, *rest):
for arg in rest:
if arg < first:
first = arg
return first
def min3(*args):
tmp = list(args)
tmp.sort()
return tmp[0]
def max1(*args):
res = args[0]
for arg in args[1:]:
if arg > res:
res = arg
return res
def max2(first, *rest):
for arg in rest:
if arg > first:
first = arg
return first
def max3(*args):
tmp = list(args)
tmp.sort()
return tmp[-1]
|
6e3fcb48692673093bbf85a6ce29ce198e30c63a | larry-dario-liu/Learn-python-the-hard-way | /ex11.py | 262 | 3.71875 | 4 | print "how old are you?",
age = raw_input("age your")
print "how tall are you?",
height = int(raw_input("your height"))
print "how much do you weigh?",
weight = raw_input("your weight")
print "So,you're %r old,%r tall and %r heavy."%(
age,height,weight) |
1e6e9d9d885d9d09050945de0c1360f33abda407 | kayliedehart/Evolution2 | /8/dealer/species.py | 3,113 | 3.9375 | 4 | import constants
from traitCard import *
class Species:
food = 0
body = 0
population = 1
traits = []
fatFood = 0
"""
creates a Species
food: how much food this species has eaten this turn
body: body size
population: population size
traits: Traits (String) on this species board (up to 3)
fatFood: how much food has been stored on a fat tissue card
can only be non-zero when a fat tissue card is in self.traits
Nat, Nat, Nat, ListOf(Trait), Nat -> Species
"""
def __init__(self, food, body, population, traits, fatFood):
self.food = food
self.body = body
self.population = population
self.traits = traits
self.fatFood = fatFood
"""
override equality
Any -> Boolean
"""
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
"""
override inequality
Any -> Boolean
"""
def __ne__(self, other):
return not self.__eq__(other)
"""
tell if this species has a trait card with a certain name
String -> Boolean
"""
def hasTrait(self, name):
return name in self.traits
"""
comparator for species/OptSpecies (aka False or Species)
decides if a species is larger than the given; precedence is decided in the following order:
population size, food eaten, body size
output is as follows:
if self is larger than given OR given is False, return is positive
if self is the same as as given, return is 0
if self is smaller than given, return is negative
OptSpecies -> Boolean
"""
def compare(self, other):
if other is False:
return 1
if self.population != other.population:
return self.population - other.population
elif self.food != other.food:
return self.food - other.food
else:
return self.body - other.body
"""
Given array of [defender, attacker, leftNeighbor, rightNeighbor], is the defender attackable?
TODO: restate spec here
Species, Species, OptSpecies (one of Boolean or Species), OptSpecies -> Boolean
"""
@staticmethod
def isAttackable(defend, attack, lNeighbor, rNeighbor):
if not lNeighbor:
lNeighbor = Species(0, 0, 0, [], 0)
if not rNeighbor:
rNeighbor = Species(0, 0, 0, [], 0)
if not attack.hasTrait("carnivore"):
return False
if defend.population != 0:
if lNeighbor.hasTrait("warning-call") or rNeighbor.hasTrait("warning-call"):
if not attack.hasTrait("ambush"):
return False
if defend.hasTrait("burrowing"):
if defend.food == defend.population:
return False
if defend.hasTrait("climbing"):
if not attack.hasTrait("climbing"):
return False
if defend.hasTrait("hard-shell"):
attackBody = attack.body
if attack.hasTrait("pack-hunting"):
attackBody += attack.population
if attackBody - defend.body < 4:
return False
if defend.hasTrait("herding"):
attackPopulation = attack.population
if defend.hasTrait("horns"):
attackPopulation -= 1
if attackPopulation - defend.population <= 0:
return False
if defend.hasTrait("symbiosis"):
if rNeighbor.body > defend.body:
return False
return True
|
b1ccef858b533ef1376a282ebaf6352cd2bda612 | KevinKnott/Coding-Review | /Month 03/Week 03/Day 04/b.py | 1,828 | 4.09375 | 4 | # Binary Tree Zigzag Level Order Traversal: https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
# Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).
from collections import deque
from types import Optional, List
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# This problem seems rather difficult but it turns out that you simply can do a level order search
# but instead of always appending the result on the right or left side we can swap by using a
# double ended queue
class Solution:
def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]:
if not root:
return []
curLevel = deque()
level = 1
result = []
curLevel.appendleft(root)
while curLevel:
temp = deque()
for _ in range(len(curLevel)):
node = curLevel.pop()
if node.left:
curLevel.appendleft(node.left)
if node.right:
curLevel.appendleft(node.right)
if level % 2 == 1:
temp.append(node.val)
else:
temp.appendleft(node.val)
# Once you have added the level in whatever order using temp
# record it to result
result.append(temp)
level += 1
return result
# The above works and runs in O(N) time and space
# Score Card
# Did I need hints? N
# Did you finish within 30 min? 8
# Was the solution optimal? Y
# Were there any bugs? N
# 5 5 5 5 = 5
|
b20880e1e0bfd211cdaa6c06f34b85020d75018d | San1357/Leetcode-August-2021 | /sqrt(x).py | 379 | 3.8125 | 4 | '''Problem: sqrt(x) '''
#code:
class Solution:
def mySqrt(self, x: int) -> int:
left = 1
right = 0
mid = 0
while(left<mid):
mid = left + math.floor((right-left)/2)
if (mid**2 > x):
right = mid
elif (mid**2) ==x:
return mid
else:
left = mid +1
return left -1
|
7e5061ae04daa7d7a2f5a3e49238f753c67fe7a6 | karan-modh/logic | /helper/formulaToTree.py | 1,541 | 3.53125 | 4 | from globalvars import OPERATORS
class BinaryTreeNode:
def __init__(self, c):
self.data = c
self.isOperator = True if c in OPERATORS else False
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
pass
def make_tree(self, formula):
x = formula[0]
if x in OPERATORS:
if x == '!':
node = BinaryTreeNode(x)
node.right = self.make_tree(formula[1])
else:
node = BinaryTreeNode(x)
p = self.make_tree(formula[1])
q = self.make_tree(formula[2])
node.left = p
node.right = q
else:
node = BinaryTreeNode(x)
return node
def generate_expr(self, root: BinaryTreeNode):
if not root:
return ""
else:
if root.data in OPERATORS:
result = ""
# result += "("
result += self.generate_expr(root.left)
result += root.data
result += self.generate_expr(root.right)
# result += ")"
return result
else:
return root.data
def divide_tree(self, root: BinaryTreeNode):
if not root:
return []
roots = []
if root.data == '&':
roots += self.divide_tree(root.left)
roots += self.divide_tree(root.right)
return roots
else:
return [root]
|
8ca7cfb49cb03a4904b541931b1c8e22c5c9d6a8 | jesgogu27/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/0-square_matrix_simple.py | 159 | 3.59375 | 4 | #!/usr/bin/python3
def square_matrix_simple(matrix=[]):
nl = []
for i in list(matrix):
nl.append(list(map(lambda i: i ** 2, i)))
return nl
|
58b4fa3419fa6ce4c8395b6865d9aa77525fca79 | GayatriMhetre21/python10aug21 | /14Aug21list.py | 1,186 | 4.21875 | 4 | #list
x=[2,3,4,5,6,7,8,9,1,0]#declare list type which carry 10 element
#extract all list
print("list x=",x[0:1])
print("list x=",x[0:5])
print("list x=",x)
print("list x=",x[7])
print("list x=",x[0:9])
print("list x=",x[1:9])
print("list x=",x[0:10])
print("list x=",x[10:0])
#extract index number 2 to 5
print("\nlist x=",x[2:5])
#print list element reverse
print("\nList x in reverse:",x[::-1])
#using append,insert add element in list
x.append(11)
print("\nAfter add 11 value in list = ",x)
x.insert(3,"hi")
print("\ninsert hi in list",x)
#Using pop,remoe,del remove element
x.pop(8)
print("\nlist After pop x[8]=",x)
x.remove(4)
print("\nlist After remove x[4]=",x)
del(x[9])
print("\nlist After delete x[9]",x)
x.clear()
print("\nlist After clear list ",x)
#tuple
g=[2,3,4,5,6,7,8,9,1,0]
#declare tuple type which carry 10 element
#extract all tuple
print("\ntuple g=",g)
#extract index number 2 to 5
print("\ntuple g=",g[2:5])
#print tuple element reverse
print("\ntuple g in reverse:",g[::-1])
#use index and count function
z=g.index(1)
print("\nIndex of 1=",z)
z=g.count('4')
print("\nCount of 4 is =",z) |
9c3f96a6497484abe3aef1c18771fa53df70322d | tinnan/python_challenge | /07_collections/062_piling_up.py | 1,376 | 4.09375 | 4 | """
There is a horizontal row of n cubes. The length of each cube is given.
You need to create a new vertical pile of cubes. The new pile should follow these directions: if cube(i) is
on top of cube(j) then sideLength(j) >= sideLength(i).
When stacking the cubes, you can only pick up either the leftmost or the rightmost cube each time.
Print "Yes" if it is possible to stack the cubes. Otherwise, print "No". Do not print the quotation marks.
"""
from collections import deque
for _ in range(int(input())):
C = int(input())
H = deque(list(map(int, input().split())))
result = -1
preceding_cube = 0
for i in range(C):
try:
left = H.popleft()
except IndexError:
left = 0
try:
right = H.pop()
except IndexError:
right = 0
if i > 0 and (left > preceding_cube or right > preceding_cube):
result = False # Both side must passes the check, else it will not be able to continue eventually
break
lesser = min(('appendleft', left), ('append', right), key=lambda x: x[1])
getattr(H, lesser[0])(lesser[1]) # Use the greater one and push the lesser one back in
if i == C - 1:
result = True # Has reached the last cube of horizontal row
preceding_cube = max(left, right)
print('Yes' if result else 'No')
|
6e36b4d7ff8c39b68224909ccaed81729dfdc589 | jpragasa/Learn_Python | /Basics/7_Program_Flow.py | 805 | 4.0625 | 4 | # name = input("Please Enter your name\n")
# age = int(input("How old are you {0}\n".format(name)))
# print(age)
#
# if age >= 18:
# print("You are old enough to vote")
# elif age <= 18:
# print("You are not old enough to vote. Please come back in {0} years...".format(18 - age))
# else:
# print("Invalid Entry")
print("Please guess a number between 1 and 10: \n")
guess = int(input())
if guess < 5:
print("Please guess higher\n")
guess = int(input())
if guess == 5:
print("Well done, you guessed it\n")
else:
print("Sorry, it is not correct\n")
elif guess > 5:
print("Please guess lower\n")
guess = int(input())
if guess == 5:
print("Well done, you guessed it\n")
else:
print("You got it the first time!\n") |
a089264c84268ecb06bc85f361c84cb7304c88db | mathfinder/python-script | /util/log.py | 1,430 | 3.5 | 4 | import logging
class Logger:
def __init__(self, log_file='log/log.txt', formatter='%(asctime)s\t%(message)s', user='rgh'):
self.user = user
self.log_file = log_file
self.formatter = formatter
self.logger = self.init_logger()
def init_logger(self):
# create logger with name
# if not specified, it will be root
logger = logging.getLogger(self.user)
logger.setLevel(logging.DEBUG)
# create a handler, write to log.txt
# logging.FileHandler(self, filename, mode='a', encoding=None, delay=0)
# A handler class which writes formatted logging records to disk files.
fh = logging.FileHandler(self.log_file)
fh.setLevel(logging.DEBUG)
# create another handler, for stdout in terminal
# A handler class which writes logging records to a stream
sh = logging.StreamHandler()
sh.setLevel(logging.DEBUG)
# set formatter
# formatter = logging.Formatter('%(asctime)s-%(name)s-%(levelname)s- %(message)s')
formatter = logging.Formatter(self.formatter)
fh.setFormatter(formatter)
sh.setFormatter(formatter)
# add handler to logger
logger.addHandler(fh)
logger.addHandler(sh)
return logger
def info(self,message=''):
self.logger.info(message)
def debug(self,message=''):
self.logger.debug(message)
|
71a85beece563565130098534efd2999726d8682 | muhammedimad/Project_Rails | /Assignments/1st Assignment/Assignment1/venv/ex6.py | 278 | 4.0625 | 4 | num=input("Please enter a five digit number\n")
if(len(num)>5):
print("error")
else:
print("you entered the number "+ num)
digits=[int(n) for n in num]
print("the digits of the number are:\n",digits)
ans=sum(digits)
print("the sum of the digits is:",ans) |
189ca03dde80cf88cc2c3ec87ce2e47208ec3c3f | hyuji946/project_euler | /01 解答例/p027.py | 1,399 | 3.578125 | 4 | # -*- coding: utf-8 -*-
"""
Project Euler Problem 27
オイラーは以下の二次式を考案している:
n**2 + n + 41.
この式は, n を0から39までの連続する整数としたときに40個の素数を生成する.
しかし, n = 40 のとき 40**2 + 40 + 41 = 40(40 + 1) + 41
となり41で割り切れる. また, n = 41 のときは 41**2 + 41 + 41
であり明らかに41で割り切れる.
計算機を用いて, 二次式 n**2 - 79n + 1601 という式が発見できた.
これは n = 0 から 79 の連続する整数で80個の素数を生成する.
係数の積は, -79 × 1601 で -126479である.
さて, |a| < 1000, |b| < 1000 として以下の二次式を考える
(ここで |a| は絶対値): 例えば |11| = 11 |-4| = 4である.
n**2 + an + b
n = 0 から始めて連続する整数で素数を生成したときに
最長の長さとなる上の二次式の, 係数 a, b の積を答えよ.
"""
from sympy import isprime
def f(a,b,n):
return n**2+a*n+b
def check(a,b):
n=0
while True:
if isprime(f(a,b,n)):
n+=1
else:
return n
#a=1;b=41
#print check(a,b)
#a=-79;b=1601
#print check(a,b)
ans=0
for a in range(-1000,1001):
for b in range(-1000,1001):
c=check(a,b)
if c>ans:
ans=c
ab=[a,b]
print ans,ab
print "ans=",ab,product(ab)
|
931c58b889992a80c9978f5585d616554598998b | cchudant/42ai_python_bootcamp | /day00/ex03/count.py | 904 | 4.3125 | 4 | import sys
def text_analyzer(text=None):
"""This function prints the number of upper characters, lower characters,
punctuation and spaces in a given text.
Input is taken from stdin when no argument is passed.
"""
if text is None:
print('What is the text to analyze?')
text = input('>> ')
if len(text) == 0:
print('The text is empty!')
return
upper = len(list(filter(lambda x: x.isupper(), text)))
lower = len(list(filter(lambda x: x.islower(), text)))
punctuation = len(list(filter(
lambda x: x in '[.,/#!$%^&*;:{}=\\-_`~()]"\'', text)))
spaces = len(list(filter(lambda x: x == ' ', text)))
print('The text contains %d characters:' % len(text))
print('- %d upper letters' % upper)
print('- %d lower letters' % lower)
print('- %d punctuation marks' % punctuation)
print('- %d spaces' % spaces)
|
26b8c68e772b388eb81e1a4e35c1c3b1c74aac53 | jshk1205/pythonPractice | /11365.py | 177 | 3.875 | 4 | while True:
text = str(input())
if text == 'END':
break
text = list(text)
for i in range(len(text)-1, -1, -1):
print(text[i], end='')
print() |
c5dd1297b245da4176429a0a9b62ee5a8934ad49 | KFranciszek/Python | /ZADANKA/2/2.py | 720 | 3.6875 | 4 | from HTMLParser import HTMLParser
# create a subclass and override the handler methods
#class object(object):
#"Pierwsza klasa"
class object1:
def __init__(self,x,y):
self.a = x
self.b = y
print("Stworzenie klasy Object!! :)")
class HtmlObject(object1):
def __init__(self, x, y):
self.a = x
self.b = y
print("Stworzenie klasy HtmlObject!! :)")
def html(self):
s = """<html>
\t<head>
\t\t<title>Test</title>
\t</head>
\t<body>
\t\t<h1> x = """ + str(self.a) + ", y = " + str(self.b) + """"
\t\t</h1>
\t</body>
</html>"""
plik = open('html2.txt', 'w')
plik.write("lol")
plik.close()
return s
# instantiate the parser and fed it some HTML
strona = HtmlObject(1,2)
print(strona.html())
input() |
60aedb6ae5864eab3e69cf83e5d6c2304bca74ca | kingsreturn/Datenvisualisierung | /Python_Datavorbereitung/main.py | 1,849 | 3.515625 | 4 | # This is a sample Python script.
# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import get_pdf
import extract_data
import generate_path
import os
import urllib.request
def get_pdf_by_url(folder_path, lists):
if not os.path.exists(folder_path):
print("Selected folder not exist, try to create it.")
os.makedirs(folder_path)
for url in lists:
print("Try downloading file: {}".format(url))
#filename = url.split('/')[-1]
dir = os.getcwd(); # 当前工作目录。
name = url.replace('https://www.rki.de/DE/Content/InfAZ/N/Neuartiges_Coronavirus/Situationsberichte/Okt_2020/','')
name = name.replace('?__blob=publicationFile','')
#urllib.request.urlretrieve(url,dir +'\\' + name) # 下载pdf
filepath = dir +'\\' + name
if os.path.exists(filepath):
print("File have already exist. skip")
else:
try:
urllib.request.urlretrieve(url, filename=filepath)
except Exception as e:
print("Error occurred when downloading file, error message:")
print(e)
if __name__ == "__main__":
root_path = './October'
paths = get_pdf.get_file(root_path)
print(paths)
'''
for filename, path in paths.items():
print('reading file: {}'.format(filename))
with open(path, 'r') as f:
lines = f.readlines()
url_list = []
for line in lines:
url_list.append(line.strip('\n'))
foldername = "./picture_get_by_url/pic_download/{}".format(filename.split('.')[0])
get_pdf_by_url(foldername, url_list)
'''
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
f890f92d450a22285b1405391f4727c38ceef762 | oneNutW0nder/csec380-hmwk | /hmwk_3/act1/step1/act1step1.py | 3,211 | 3.578125 | 4 | #!/usr/bin/env python
#
# Name: Simon Buchheit
# Date: October 6, 2019
#
# CSEC-380 : hmwk3 : Act1 Part 1
#
# Purpose: This script scrapes the site:
# https://www.rit.edu/study/computing-security-bs
#
# and collects the course number and corresponding course name.
# If there is no name with the number or vice versa the data will
# not be recorded. This script will output a CSV file with the data
#
import bs4
import simplerequest
import os
def get_values(chonker):
"""
This function parses the initial bs4 filter for the course numbers
and the corresponding course names. If a course does not have a number
or name it will not be saved.
:param chonker: The massive list from the intial filter from bs4
:return: Returns a dictionary of course numbers and their
corresponding name
"""
# Dict to hold the values
values = {}
# List to hold the course numbers
courseNums = []
# Loop through the tags
for tag in chonker:
# Check for None stuff
if tag.contents[1].contents[0] is not None:
# Check for newlines
if tag.contents[1].contents[0] != "\xa0":
# Make list to get just course nums
# Course nums don't have spaces in name
pos_course = tag.contents[1].contents[0].string.strip().split()
# Check for just course name and remove the dumb "Course" value
if (len(pos_course) == 1) and (pos_course[0] != "Course"):
# Save course number
courseNums = pos_course[0]
# Save corresponding course name
# find "div" tags where "class=course-name"
name = (
tag.contents[3]
.find_all("div", {"class": "course-name"})[0]
.get_text()
.strip()
)
# Build dict
values[str(courseNums)] = str(name)
return values
def write_csv(values):
"""
This function simply creates a new file and writes the values dict
to the new file in a CSV format
:param values: Dictionary of courseNum:courseName
"""
try:
if not os.path.exists("./stuff"):
os.mkdir("./stuff")
with open("./stuff/courses.csv", "w+") as fd:
for key in values:
fd.write(f"{key},{values[key]}\n")
except FileExistsError:
pass
def main():
# Send that sweet sweet request to get the goodies
r = simplerequest.SimpleRequest(
"www.rit.edu",
port=443,
resource="/study/computing-security-bs",
https=True,
)
r.render()
r.send()
# Start the soup!
soup = bs4.BeautifulSoup(r.data, "html.parser")
# Chonker is the list that holds all "tr" tags
chonker = []
# Find all "<tr>" tags with "class=hidden-row*"
chonker = soup.find_all("tr", {"class": "hidden-row"})
# parse the chonker for courseNumbers
values = get_values(chonker)
# Create CSV value
write_csv(values)
if __name__ == "__main__":
main()
|
db6cb4edcd45eb96f9960c6b00de6f98f825e42f | ankit12192/Email_encryptor | /decrypter.py | 378 | 3.5 | 4 | # -*- coding: utf-8 -*-
def Dec(key):
key = key % 26
file = open("decrypter.txt","w").close()
with open("encrypted_file.txt") as fileObj:
for line in fileObj:
for ch in line:
m=ord(ch)
S = (m - key)
k = unichr(S)
file = open("decrypter.txt","a")
file.write(str(k))
|
4c38a4173476e7520cbafdf7e664f1f54928ae51 | matheussl12/Python | /Sistema de notas.py | 604 | 4 | 4 |
print('***SISTEMA DE NOTAS ***\n')
np1 = float(input('Digite o valor de sua nota da NP1: \n'))
np2 = float(input('Digite o valor de sua nota da NP2: \n'))
media = (np1 + np2) / 2
if media < 7:
print("Você esta de exame!")
nexame = float(input('Digite a nota do exame: \n'))
nexame = (np1 + np2 + nexame) / 3
if nexame >= 5:
print("Você foi aprovado pelo exame! \nSua nota final é {:.1f}".format(nexame))
else:
print("Você foi reprovado nesta disciplina.")
else:
print("Você está aprovado! \n Sua média final é {:.1f} ".format(media)) |
fe5d16f872f9cf871d6fab855060c268ae2760fb | shreyagg2202/Python | /Learning Python/inheritence.py | 365 | 3.75 | 4 | class Animal:
def Dog(self):
print("Dog is barking")
class AnimalChild(Animal):
def DogChild(self):
print("Dog's child is eating")
class Cal(AnimalChild):
def Add(self):
n1=2
n2=3
print(n1+n2)
obj = Cal() #Always create object of child
obj.Dog()
obj.DogChild()
obj.Add()
|
3b2307ae7cbb19bd5ce14e0a2b65e3286f75a839 | ChaosNyaruko/leetcode_cn | /234.回文链表.py | 1,132 | 3.640625 | 4 | #
# @lc app=leetcode.cn id=234 lang=python3
#
# [234] 回文链表
#
# @lc code=start
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
if not head:
return True
slow = head
fast = head
# 退出循环是slow是列表的中点(奇数)或者上半个列表的末尾(偶数)
# 以fast过滤是不使slow变成下半列表的起点?
while fast.next and fast.next.next:
slow = slow.next
fast = fast.next.next
nextStart = slow.next
# print(slow.val, nextStart.val)
# reverse nextStart
cur = nextStart
prev = None
while cur:
curNext = cur.next
cur.next = prev
prev = cur
cur = curNext
h1, h2 = head, prev
while h1 and h2:
if h1.val != h2.val:
return False
h1 = h1.next
h2 = h2.next
return True
# @lc code=end
|
2b93e891e1876ec1c01c86648f14d52673e1a06f | shanmukhanand/machine-learning-exp | /supervised-learning/tens/regression/firts.py | 780 | 3.796875 | 4 | import tensorflow as tf
import matplotlib.pyplot as plt
X = [1,2,3]
Y = [1,2,3]
W = tf.placeholder(tf.float32)
# Our hypothesis for linear model
hypothesis = X * W
# cost/loss function
cost = tf.reduce_mean(tf.square(hypothesis - Y))
# Launch the graph in a session.
sess = tf.Session()
# Initializes global variables in the graph.
sess.run(tf.global_variables_initializer())
# Variables for plotting cost function
W_val = []
cost_val = []
learning_rate = 0.1
for i in range(-10 , 50):
feed_W = i*learning_rate
curr_cost, cur_w = sess.run([cost, W],feed_dict={W:feed_W})
W_val.append(cur_w)
cost_val.append(curr_cost)
print('cost_val' , cost_val)
for i in cost_val:
print(cost_val[i])
# Show the cost function
plt.plot(W_val, cost_val)
plt.show()
|
4349ec3ae67d73d5fd3bf22a1e8476780df76efa | AkshayGulhane46/hackerRank | /06_Loops.py | 119 | 3.546875 | 4 | if __name__ == '__main__':
n = int(input())
for ele in range(n):
square=ele*ele
print(square)
|
9e1c746c3a68c54efb9d0d653643249618a2f248 | ircubic/Master-Thesis | /src/testbed/simulation/chars.py | 3,674 | 3.6875 | 4 | class Shape(object):
def __init__(self, position):
self._position = list(position)
def move(self, direction, speed):
if direction == 'left':
self._position[0] -= speed
elif direction == 'right':
self._position[0] += speed
elif direction == 'up':
self._position[1] -= speed
elif direction == 'down':
self._position[1] += speed
def getPosition(self, ):
"""Gets the entity's position
"""
return tuple(self._position)
def setPosition(self, new_pos):
"""Set the entity's position
Arguments:
- `new_pos`:
"""
self._position = list(new_pos)
def getLeft(self):
return self._position[0]
def getRight(self):
return self._position[0]
def getTop(self):
return self._position[1]
def getBottom(self):
return self._position[1]
class Rect(Shape):
def __init__(self, position, size):
super(Rect, self).__init__(position)
self.setSize(size)
def getSize(self):
return tuple(self._size)
def setSize(self, new_size):
self._size = list(new_size)
def getLeft(self):
return self._position[0] - (self._size[0]/2.0)
def getRight(self):
return self._position[0] + (self._size[0]/2.0)
def getTop(self):
return self._position[1] - (self._size[1]/2.0)
def getBottom(self):
return self._position[1] + (self._size[1]/2.0)
class Circle(Shape):
def __init__(self, position, radius):
super(Circle, self).__init__(position)
self.setRadius(radius)
def getRadius(self):
return self._radius
def setRadius(self, new_radius):
self._radius = new_radius
def getLeft(self):
return self._position[0] - (self._radius)
def getRight(self):
return self._position[0] + (self._radius)
def getTop(self):
return self._position[1] - (self._radius)
def getBottom(self):
return self._position[1] + (self._radius)
class Entity(object):
"""An entity in the simulation.
"""
def __init__(self, shape, speed):
"""Set the entity's initial state.
Arguments:
- `position`: the entity's start position
- `speed`: the entity's movement speed
"""
self._shape = shape
self.setSpeed(speed)
self._last_direction = ""
def move(self, direction):
"""Move in the designated direction.
Moves the entity one step in the given direction, with the distance
given by the entity's speed.
Arguments:
- `direction`: The direction to move. One of "left", "right", "up" or "down".
"""
self._last_direction = direction
self._shape.move(direction, self._speed)
def getPosition(self, ):
"""Gets the entity's position
"""
return self._shape.getPosition()
def setPosition(self, new_pos):
"""Set the entity's position
Arguments:
- `new_pos`:
"""
self._shape.setPosition(new_pos)
def getShape(self):
return self._shape
def setShape(self, new_shape):
self._shape = new_shape
def getSpeed(self):
return self._speed
def setSpeed(self, new_speed):
self._speed = float(new_speed)
@property
def x(self):
return self.getPosition()[0]
@property
def y(self):
return self.getPosition()[1]
@property
def radius(self):
return self._shape.getRadius()
@property
def size(self):
return self._shape.getSize()
|
44159023b941fe26953bf626e8ba6b60dbadf822 | Scarecrow1024/Python-Old | /threading_simple.py | 487 | 3.53125 | 4 | import threading
import time
num = 0
def run2():
lock.acquire()
global num
num += 1
lock.release()
lock = threading.Lock()
for i in range(100):
tt = threading.Thread(target=run2)
tt.start()
print("num:", num)
def run(n):
print(n)
time.sleep(2)
start_time = time.time()
ts = []
for i in range(50):
t = threading.Thread(target=run, args=('t--%s' % i,))
t.start()
ts.append(t)
for t in ts:
t.join()
print('done', time.time()-start_time)
|
5e6c30faf3fdc48bb763fa0d604fffea8d33dc6e | Axioma42/Data_Analytics_Boot_Camp | /Week 3 - Python/Activities/3/Activities/08-Par_WrestlingWithFunctions/Solved/wrestling_functions.py | 2,135 | 4.09375 | 4 | import os
import csv
# Path to collect data from the Resources folder
wrestling_csv = os.path.join('..', 'Resources', 'WWE-Data-2016.csv')
# Define the function and have it accept the 'wrestler_data' as its sole parameter
def print_percentages(wrestler_data):
# For readability, it can help to assign your values to variables with descriptive names
name = str(wrestler_data[0])
wins = int(wrestler_data[1])
losses = int(wrestler_data[2])
draws = int(wrestler_data[3])
# Total matches can be found by adding wins, losses, and draws together
total_matches = wins + losses + draws
# Win percent can be found by dividing the the total wins by the total matches and multiplying by 100
win_percent = (wins / total_matches) * 100
# Loss percent can be found by dividing the total losses by the total matches and multiplying by 100
loss_percent = (losses / total_matches) * 100
# Draw percent can be found by dividing the total draws by the total matches and multiplying by 100
draw_percent = (draws / total_matches) * 100
# If the loss percentage is over 50, type_of_wrestler is "Jobber". Otherwise it is "Superstar".
if loss_percent > 50:
type_of_wrestler = "Jobber"
else:
type_of_wrestler = "Superstar"
# Print out the wrestler's name and their percentage stats
print(f"Stats for {name}")
print(f"WIN PERCENT: {str(win_percent)}")
print(f"LOSS PERCENT: {str(loss_percent)}")
print(f"DRAW PERCENT: {str(draw_percent)}")
print(f"{name} is a {type_of_wrestler}")
# Read in the CSV file
with open(wrestling_csv, 'r') as csvfile:
# Split the data on commas
csvreader = csv.reader(csvfile, delimiter=',')
header = next(csvreader)
# Prompt the user for what wrestler they would like to search for
name_to_check = input("What wrestler do you want to look for? ")
# Loop through the data
for row in csvreader:
# If the wrestler's name in a row is equal to that which the user input, run the 'print_percentages()' function
if name_to_check == row[0]:
print_percentages(row)
|
2ef4f2c7bc1d6bb92fd546693d39c2e7c5c57896 | jardelhokage/python | /python/reviProva/Python-master/31_NúmeroPrimo.py | 288 | 3.734375 | 4 | primos = []
num = int(input('Qual numero testar? '))
for n in range(1, num+1):
if num % n == 0:
primos.append(n)
if len(primos) > 2:
print('O número {} NÃO é Primo!'.format(num))
break
if len(primos) == 2:
print('O número {} é PRIMO.'.format(num)) |
5b7d47affb56a1395c19c051ac165b8824db8fd2 | ljwhite/python | /basics/tuples.py | 363 | 4.15625 | 4 | my_tuple = (1,2,3,5,8)
print("1st value :",my_tuple[0])
print("1st 3 values :",my_tuple[0:3])
print("Length :", len(my_tuple))
more_fibs = my_tuple + (13,21,34)
print("34 in tuple? :", 34 in more_fibs)
for i in more_fibs:
print(i)
a_list = [55,89,144]
a_tuple = tuple(a_list)
b_list = list(a_tuple)
print("Max :", max(a_tuple))
print("Min :", min(a_tuple))
|
dd5ec0417b9e2441befec6f52b1a5156150edf00 | iampkuhz/OnlineJudge_cpp | /leetcode/python/passedProblems/128-longest-consecutive-sequence.py | 1,908 | 3.9375 | 4 | #!/usr/bin/env python
# encoding: utf-8
"""
Given an unsorted array of integers, find the length of the longest consecutive elements sequence.
For example,
Given [100, 4, 200, 1, 3, 2],
The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4.
Your algorithm should run in O(n) complexity.
"""
# 看答案,使用Set删除元素, 56ms
class Solution(object):
def longestConsecutive(self, nums):
nums = set(nums)
re = 0
while nums:
stk = [next(iter(nums))]
tmp = 0
while stk:
tmp += 1
cur = stk.pop()
nums.discard(cur)
if cur + 1 in nums: stk.append(cur + 1)
if cur - 1 in nums: stk.append(cur - 1)
re = max(re, tmp)
return re
# 看答案,使用字典, 56ms
class Solution(object):
def longestConsecutive(self, nums):
nlen = len(nums)
dic = {}
re = 0
for n in nums:
if n in dic: continue
left, right = 0, 0
le = 1
if n-1 in dic:
left = dic[n-1]
le += left
if n+1 in dic:
right = dic[n+1]
le += right
dic[n] = 1
dic[n-left] = le
dic[n+right] = le
re = max(re, le)
return re
# 非O(n)的算法也可以过。。。,52ms
class Solution(object):
def longestConsecutive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
nums.sort()
re = 1; i, slen = 0, len(nums)
while i < slen:
j = i
dup = 0
while j < slen -1 and nums[j] >= nums[j+1] -1:
if nums[j] == nums[j+1]: dup += 1
j += 1
re = max(re, j-i+1 - dup)
i = j + 1
return re
|
bf421c2d34027e1724faafcc4663eb1ffc69e96d | choco9966/Algorithm-Master | /programmers/코딩테스트 대비반/1주차/올바른괄호.py | 394 | 3.515625 | 4 | def solution(s):
# [실행] 버튼을 누르면 출력 값을 볼 수 있습니다.
# print('Hello Python')
myStack = []
for i in s:
if i == "(":
myStack.append(i)
else:
try:
myStack.pop()
except:
return False
if len(myStack) == 0:
return True
else:
return False
|
7eae67863dfadfdf966e6e32c38fc9a006dacc5f | CommanderKV/SchoolChatApp | /Server/chatAppServerGUI.py | 14,569 | 3.59375 | 4 | import pygame
class Button():
def __init__(self, color, x, y, width, height, text='', function=None, args=None):
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
self.function = function
self.args = args
def draw(self, win, outline=None):
#Call this method to draw the button on the screen
if outline:
pygame.draw.rect(win, outline, (self.x-2,self.y-2,self.width+4,self.height+4),0)
pygame.draw.rect(win, self.color, (self.x,self.y,self.width,self.height),0)
if self.text != '':
pygame.font.init()
font = pygame.font.SysFont('comicsans', 30)
text = font.render(self.text, 1, (0,0,0))
win.blit(text, (self.x + (self.width/2 - text.get_width()/2), self.y + (self.height/2 - text.get_height()/2)))
def isOver(self, pos):
#Pos is the mouse position or a tuple of (x,y) coordinates
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
return False
class Screen(pygame.Surface):
def __init__(self, backgroundColor, topic, buttons=[], screenshares=[], otherSurfaces=[], *args, **kwargs):
super().__init__(*args, **kwargs)
self.buttons = buttons
self.bgColor = backgroundColor
self.screenshares = screenshares
self.otherSurfaces = otherSurfaces
self.active = True
self.topic = topic.upper()
def draw(self, win):
self.fill(self.bgColor)
# draw each button in the buttons list if there is any
if len(self.buttons) > 0:
for button in self.buttons:
button.draw(self)
# draw each screen share if there are any
if len(self.screenshares) > 0:
for ScreenShare in self.screenshares:
ScreenShare.draw(self)
if len(self.otherSurfaces) > 0:
for surface in self.otherSurfaces:
self.blit(surface, (surface.x, surface.y))
# add screen to win
win.blit(self, (0, 0))
class TextWindow(pygame.Surface):
def __init__(self, x, y, text=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.x = x
self.y = y
self.textpos = text
self.color = (255, 255, 255)
self.fontSize = 30
self.XPadding = 5
self.YPadding = 5
pygame.font.init()
self.font = pygame.font.SysFont("comicsans", self.fontSize)
def draw(self, text):
self.fill((48, 48, 48))
if "\t" in text:
text = text.replace("\t", " "*10)
if "\n" in text:
splitText = text.split("\n")
split_Max = int(self.get_width()-self.fontSize)+int(SIZE[0]/self.fontSize)*62
split_Mark = int(split_Max/self.fontSize)
# print(len(splitText[0])*self.fontSize, split_Max)
for pos, t in enumerate(splitText):
if len(t)*self.fontSize > split_Max:
splitText.insert(pos+1, str(t[split_Mark:]))
splitText[pos] = str(t[:split_Mark])+"-"
y = self.YPadding
for textToRender in splitText:
renderedText = self.font.render(textToRender, 1, self.color)
self.blit(renderedText, (self.XPadding, y))
y += self.fontSize
else:
text = self.font.render(text, 1, self.color)
if self.textpos == None:
self.blit(text, (self.YPadding, self.XPadding))
elif self.textpos.upper() == "CENTER":
self.blit(text, (self.YPadding*3, self.XPadding*3))
def switchScreenTo(screentopic):
for screen in screens:
if screen.topic == screentopic.upper():
screen.active = True
else:
screen.active = False
def drawWindow(win):
win.fill((0, 0, 0))
for screen in screens:
if screen.active is True:
screen.draw(win)
pygame.display.update()
def exitGUI():
global run
run = False
def main(usernamesLink, outputLink, heartbeatsMsg, heartbeartStatus):
global screens, run, SIZE
SIZE = (800, 850)
PADDINGX = 10
PADDINGY = 10
WIN = pygame.display.set_mode(SIZE)
clock = pygame.time.Clock()
serverOutput = []
HeartBeatMsgs = []
screens = []
if True:
# Make the server start screen
if True:
serverStartScreenButtons = [
Button(
(255, 255, 255),
int(SIZE[0]-200)-PADDINGX,
int(PADDINGY),
200,
50,
"Conected users",
switchScreenTo,
"conected users"
),
Button(
(255, 255, 255),
int(SIZE[0]-200)-PADDINGX,
int((PADDINGY*2)+50),
200,
50,
"HeartBeats",
switchScreenTo,
"heartbeat msgs"
),
Button(
(255, 255, 255),
PADDINGX,
int(SIZE[1]-50-PADDINGY),
200,
50,
"Stop server",
exitGUI
)
]
serverStartScreenTextWindow = [
TextWindow(
PADDINGX,
PADDINGY,
size=((SIZE[0]-(PADDINGX*3))-200, (SIZE[1]-(PADDINGY*3)-50))
)
]
serverStartScreen = Screen(
(0, 0, 0),
"SERVER START SCREEN",
serverStartScreenButtons,
size=SIZE,
otherSurfaces=serverStartScreenTextWindow
)
screens.append(serverStartScreen)
serverStartScreen.active = True
# Make the Conected users screen
if True:
ConectedUsersScreenButtons = [
Button(
(255, 255, 255),
int(PADDINGX),
int(SIZE[1]-PADDINGY)-50,
200,
50,
"BACK",
switchScreenTo,
"server start screen"
)
]
ConectedUsersScreenTextWindows = [
TextWindow(
PADDINGX,
PADDINGY,
size=((SIZE[0]-(PADDINGX*3))-200, (SIZE[1]-(PADDINGY*3)-50))
),
TextWindow(
(SIZE[0]-PADDINGX)-200,
PADDINGY,
text="CENTER",
size=(200, 50)
)
]
ConectedUsersScreen = Screen(
(0, 0, 0),
"CONECTED USERS",
ConectedUsersScreenButtons,
size=SIZE,
otherSurfaces=ConectedUsersScreenTextWindows
)
screens.append(ConectedUsersScreen)
ConectedUsersScreen.active = False
# Make the HeartBeat msgs screen
if True:
HeartBeatMsgsButtons = [
Button(
(255, 255, 255),
int(PADDINGX),
int(SIZE[1]-PADDINGY)-50,
200,
50,
"BACK",
switchScreenTo,
"server start screen"
),
Button(
(255, 255, 255),
int(SIZE[0]-200)-PADDINGX,
int(PADDINGY),
200,
50,
"HeartBeats status",
switchScreenTo,
"heartbeat status"
),
]
HeartBeatMsgsTextWindows = [
TextWindow(
PADDINGX,
PADDINGY,
size=((SIZE[0]-(PADDINGX*3))-200, (SIZE[1]-(PADDINGY*3)-50))
)
]
HeartBeatMsgsScreen = Screen(
(0, 0, 0),
"HEARTBEAT MSGS",
HeartBeatMsgsButtons,
otherSurfaces=HeartBeatMsgsTextWindows,
size=SIZE
)
screens.append(HeartBeatMsgsScreen)
HeartBeatMsgsScreen.active = False
# Make the HearBeat statuss screen
if True:
HeartBeatStatusButtons = [
Button(
(255, 255, 255),
int(PADDINGX),
int(SIZE[1]-PADDINGY)-50,
200,
50,
"BACK",
switchScreenTo,
"heartbeat msgs"
),
]
HeartBeatStatusTextWindows = [
TextWindow(
PADDINGX,
PADDINGY,
size=((SIZE[0]-(PADDINGX*3))-200, (SIZE[1]-(PADDINGY*3)-50))
),
TextWindow(
(SIZE[0]-PADDINGX)-200,
PADDINGY,
text="CENTER",
size=(200, 50)
)
]
HeartBeatStatusScreen = Screen(
(0, 0, 0),
"HEARTBEAT STATUS",
HeartBeatStatusButtons,
otherSurfaces=HeartBeatStatusTextWindows,
size=SIZE
)
screens.append(HeartBeatStatusScreen)
HeartBeatStatusScreen.active = False
run = True
while run:
clock.tick()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
elif event.type == pygame.MOUSEBUTTONDOWN:
for screen in screens:
if screen.active is True:
for button in screen.buttons:
if button.function != None:
if button.isOver(pygame.mouse.get_pos()) is True:
button.function(button.args) if button.args != None else button.function()
if serverStartScreen.active is True:
msg = outputLink()
if len(msg) > 0:
for msgOutput in msg:
serverOutput.append(str(msgOutput)+"\n")
serverOutputText = ""
if len(serverOutput) > 0:
for msg in serverOutput:
serverOutputText += str(msg)
serverStartScreenTextWindow[0].draw(serverOutputText)
outputLink(True)
elif ConectedUsersScreen.active is True:
usernames, clientStatus, clientIps = usernamesLink()
# Set up the layout message at the top
if True:
usernamesText = "IP"
usernamesTextList = list(str(usernamesText.center(70)))
for pos, letter in enumerate(str("Username")):
usernamesTextList[pos] = letter
for pos, letter in enumerate(str("Status")):
pos = int((len("Status") - pos) * -1)
usernamesTextList[pos] = letter
usernamesText = ""
for letter in usernamesTextList:
usernamesText += letter
usernamesText += "\n"
for pos, username in enumerate(usernames):
result = clientIps[pos]
resultList = list(str(result.center(70)))
for pos2, letter in enumerate(str(username)):
resultList[pos2] = letter
for pos1, letter in enumerate(str(clientStatus[pos])):
pos1 = int((len(str(clientStatus[pos])) - pos1) * -1)
resultList[pos1] = letter
result = ""
for letter in resultList:
result += letter
usernamesText += result + "\n"
connectedUsersAmount = len(usernames)
for status in clientStatus:
if status.upper() == "DISCONECTED":
connectedUsersAmount -= 1
ConectedUsersScreenTextWindows[0].draw(usernamesText)
ConectedUsersScreenTextWindows[1].draw(f"Connected: ({connectedUsersAmount})")
elif HeartBeatMsgsScreen.active is True:
HeartBeatMsg = heartbeatsMsg()
if len(HeartBeatMsg) > 0:
for heartbeatOutput in HeartBeatMsg:
HeartBeatMsgs.append(str(heartbeatOutput)+"\n")
HeartBeatOutputText = ""
if len(HeartBeatMsgs) > 0:
for msg in HeartBeatMsgs:
HeartBeatOutputText += msg
HeartBeatMsgsTextWindows[0].draw(HeartBeatOutputText)
heartbeatsMsg(True)
elif HeartBeatStatusScreen.active is True:
HeartBeatStatusList = heartbeartStatus()
HeartBeatText = ""
resultText = list(str("Username").center(70))
for pos, letter in enumerate(str("Ip")):
resultText[pos] = letter
for pos, letter in enumerate(str("Status")):
pos = int((len("Status") - pos) * -1)
resultText[pos] = letter
for letter in resultText:
HeartBeatText += letter
HeartBeatText += "\n"
conectedHeartBeats = 0
if len(HeartBeatStatusList) > 0:
for heartbeat in HeartBeatStatusList:
# heartbeat[-len("Terminated")] = " "
HeartBeatText += str(heartbeat)+"\n"
if "Terminated..." not in heartbeat:
conectedHeartBeats += 1
conectedHeartBeats = f"Conected: ({conectedHeartBeats})"
HeartBeatStatusTextWindows[0].draw(HeartBeatText)
HeartBeatStatusTextWindows[1].draw(conectedHeartBeats)
drawWindow(WIN)
|
fc3cd9074d165d2555e7ddb656a9962e56154852 | liuhu0514/py1901_0114WORK | /days0214/封装练习/封装简单练习.py | 628 | 4.03125 | 4 | """
面向对象封装练习
"""
class Person:
"""人的类型"""
def __init__(self, name, age):
self.__name = name
self.__age = age
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
def get_age(self):
return self.__age
def set_age(self, age):
if self.__age >= 18:
self.__age = age
else:
print("您的年龄不到18,请到18以后再来")
# 创建一个对象
p = Person("小花", 17)
print(p.get_name(), p.get_age())
# 修改姓名
p.set_age(20)
print(p.get_name(),p.get_age())
|
ce6f6a81a226c04221274afd77b9dc6c51eac8a1 | anitakamboj1997/task2 | /test.py | 6,213 | 4.34375 | 4 |
import sys
from enum import Enum
# Python3 implementation to build a
# graph using Dictonaries
from collections import defaultdict
# Function to build the graph
def build_graph():
edges = [
["A", "B",5], ["A", "E"],
["A", "C"], ["B", "D"],
["B", "E"], ["C", "F"],
["C", "G"], ["D", "E"]
]
graph = defaultdict(list)
# Loop to iterate over every
# edge of the graph
for edge in edges:
a, b = edge[0], edge[1]
# Creating the graph
# as adjacency list
graph[a].append(b)
graph[b].append(a)
return graph
if __name__ == "__main__":
graph = build_graph()
print(graph)
class DijkstrasAlg:
"""Implements Dijkstra's algorithm and stores the shortest paths from all nodes to all reachable nodes."""
"""
'shortest_dists' is a dictionary storing the shortest distances between any two cities.
In the example below, the shortest distance from A to B is 5.0, from E to D is 15.0, etc.
Note that a city is not at distance 0 from itself; at least one edge must be traversed to create a route.
Destinations that can't be reached will not appear; for example from A to A.
{'A': {'B': 5.0, 'C': 9.0, 'D': 1.0, 'E': 3.0},
'B': {'B': 9.0, 'C': 4.0, 'D': 12.0, 'E': 6.0},
'C': {'B': 5.0, 'C': 9.0, 'D': 8.0, 'E': 2.0},
'D': {'B': 5.0, 'C': 8.0, 'D': 16.0, 'E': 2.0},
'E': {'B': 3.0, 'C': 7.0, 'D': 15.0, 'E': 9.0}}
"""
def __init__(self, graph_dict):
"""Find and store all shortest routes for this graph."""
self.shortest_dists = {}
# Run Dijkstra's algorithm with each node as the start node.
for start_node in graph_dict.keys():
self.shortest_dists[start_node] = self._compute_shotest_paths(graph_dict, start_node)
def _compute_shotest_paths(self, graph_dict, start_node):
"""Use Dijkstra's algorithm to compute all shortest paths."""
completed_nodes = {}
visited_nodes = {start_node: 0}
while visited_nodes:
min_value_key = min(visited_nodes, key=visited_nodes.get)
cost_to_min_node = visited_nodes.pop(min_value_key)
for k, v in graph_dict[min_value_key].items():
if k not in completed_nodes:
comparison_min = cost_to_min_node + v
if k not in visited_nodes:
visited_nodes[k] = comparison_min
else:
visited_nodes[k] = min(comparison_min, visited_nodes[k])
# Don't mark start node completed at a distance of 0
if min_value_key != start_node or cost_to_min_node > 0:
completed_nodes[min_value_key] = cost_to_min_node
return completed_nodes
def get_distance(self, start_node, end_node):
if end_node in self.shortest_dists.get(start_node, {}):
return self.shortest_dists[start_node][end_node]
return "NO SUCH ROUTE"
class TrainGraph:
"""
Takes a string representing a directed graph of city-to-city connections and their distances of
the format "AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7" and allows querying of
- shortest routes,
- the distance of specific routes,
- the number of routes from one city to another with a max number of stops,
- the number of routes from one city to another with an exact number of stops,
- the number of routes from one city to another with less than a specified distance.
Formatting of the graph string and the submitted routes is assumed to be valid.
All distances are required to be greater than 0 so that the algorithms used have valid answers.
"""
TripType = Enum('TripType', 'exact_stops max_stops')
def __init__(self, graph):
self.graph = self._convert_graph_to_dict(graph)
self.dijkstras_alg = DijkstrasAlg(self.graph)
def _convert_graph_to_dict(self, graph):
"""Convert the 'graph' string to a dictionary."""
graph_dict = {}
connection_list = [x.strip() for x in graph.split(',')]
for connection in connection_list:
start_city = connection[0]
next_city = connection[1]
distance = float(connection[2:])
if start_city not in graph_dict:
graph_dict[start_city] = {}
graph_dict[start_city][next_city] = distance
return graph_dict
def get_distance(self, route):
"""Calculate distance for a specific route, where 'route' is a string of format "A-B-D" """
if route == "":
return "NO SUCH ROUTE"
route_cities = route.split('-')
current_city = route_cities[0]
total_distance = 0
# Iterate through cities on the route and sum their distances.
for i in range(1, len(route_cities)):
next_city = route_cities[i]
if current_city in self.graph and next_city in self.graph[current_city]:
total_distance += self.graph[current_city][next_city]
else:
return "NO SUCH ROUTE"
current_city = next_city
return total_distance
def get_number_trips(self, start_city, end_city, num_stops, trip_type):
"""
Get the number of possible trips from start_city to end_city.
If trip_type is TripType.max_stops, all trips with stops <= num_stops are counted.
Otherwise only trips with exactly num_stops are counted.
"""
sum_routes = 0
if num_stops == 0:
return 0
# iterate through all connections from start_city
for next_city in self.graph[start_city]:
if next_city == end_city and (trip_type == self.TripType.max_stops or num_stops == 1):
sum_routes += 1
sum_routes += self.get_number_trips(next_city, end_city, num_stops - 1, trip_type)
return sum_routes
my_routes = TrainGraph("AB5, BC4, CD8, DC8, DE6, AD5, CE2, EB3, AE7")
distance =my_routes.get_distance("A-B-C")
print("the distance of the route A-B-C output#1:",distance)
tripnumber=my_routes.get_number_trips("C", "C", 3, TrainGraph.TripType.max_stops)
print("The number of trips starting at C and ending at C output#6:",tripnumber)
|
8786c3c55d882471d9b64669b514b09e68bcbaf3 | SteenJennings/Neural-Net-Options | /Kevin/Archive/nn_code_midpoint.py | 1,810 | 3.890625 | 4 | #predict
from numpy import loadtxt
#import keras functionality for sequential architecture
#Keras is a free open source Python library for developing and evaluating deep learning models
from keras.models import Sequential
from keras.layers import Dense
#load and format dataset
dataset = loadtxt('/content/AMD_withoutHeaders.csv', delimiter=',')
x = dataset[:,0:12]
y = dataset[:,12]
#model format - models in Keras are defined as a sequence of layers
#we will use a Sequential Model and add layers as needed
model = Sequential()
#model uses dense class for fully connected layers
#first argument = # of neurons/nodes, 'activation' argument is the activation function
#relu activation function applied for first 2 layers, 8 args, sigmoid last for binary output
model.add(Dense(12, input_dim=12, activation='relu')) #input layer, where input_dim = number of input features
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
#compile model using bin_xen for loss fx and adam for stochastic gradient descent fx
#adam is an optimization algorithm that tunes itself and gives good results in a wide range of problems
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
#fit model trains or 'fits' our model - training occurs over epochs and each epoch is split into batches
#the number of epochs and batch size can be chosen experimentally by trial and error
model.fit(x, y, epochs=180, batch_size=10)
# after training our NN on the dataset, we will make class predictions with the model
predictions = model.predict_classes(x)
#summarize the first X cases - the goal is to achieve the lowest loss (0) and highest accuracy (1) possible
for i in range(len(x)):
print('%s => predicted %d (expected %d)' % (x[i].tolist(), predictions[i], y[i]))
|
f9d955fef713f8fa07c7e77b1c3110f19a089348 | uch1/CS-2-Tweet-Generator | /coursework/classwork/whatever.py | 3,899 | 4.28125 | 4 | # Defines a "repeat" function that takes 2 arguments
def repeat(s, exclaim):
'''
Returns the string 's' repeated 3 times.
If exclaim is true, add exclamation marks.
'''
result = s * 3
if exclaim:
result = result + '!!!'
return result
# String literals
s = 'hi'
print s[1] ## i
print len(s) ## 2
print s + ' there' ## hi there
pi = 3.14
##test = 'The value of pi is ' + pi ## NO, does not work
text = 'The value of pi is ' + str(pi) ## yes
## String Methods
s.lower(), s.upper() # -- returns the lowercase or uppercase V of the String
s.strip() #-- returns a string with whitespace removed from the start and end
s.startswith('other'), s.endswith('other') # -- tests if the string starts or ends with the given other string
s.find('other') #-- searches for the given other string
#returns the first index where it begins or -1 if not found
s.replace(old, new) #-- returns a string where all occurences of old have
# been replaced by new
s.split('delim') #--
s.join(iterable) #-- joins the elements in the given list
#for and in
squares = [1, 4, 9, 16]
sum = 0
for num in squares:
sum += num
print sum ##0
lst = ['fidelia', 'obi', 'uchenna']
if 'uchenna' in lst:
print("OKAY")
for i in range(100):
print i
#while loop
# while loop gives you total control over the index numbers
## Access every 3rd element in a list
i = 0
while i < len(a):
print a[i]
i += 3
## List Methods
list.append() #add single elements to the end of the list while changing the original
list.insert(index, object) #-- inserts the element at the given index
list.extend(iterable)
list.index()#-- searches for the given element and returns its index
list.remove()#-- searches for the first instance and removes it (throws valueError if not present)
list.sort()# doesn't returns
list.reverse()#reverses the list in place (does not return it)
list.pop()# removes and returns the element at the given index
#Python Sorting
#sorted function takes a list and sorts it in order but doesn't change the list
a = [5, 1, 4, 3]
print sorted(a)
print a
#Tuples
tuple = (1, 2, 'hi')
print len(tuple)
print tuple[2]
tuple[2] = 'bye' ## NO, tuples cannot be changed
tuple = (1, 2, 'bye') ## this works
#List Comprehesion is a way to write an expression that expands to whole list
nums = [1, 2, 3, 4]
squares = [ n * n for n in nums ] ##[1, 4, 9, 16]
#strings
strs = ['hello', 'and', 'goodbye']
shouting = [ s.upper() + '!!!' for s in strs]
## ['HELLO!!!', 'AND!!!', 'GOODBYE!!!']
# Select values <= 2
nums = [2, 8, 1, 6]
small = [ n for n in nums if n <= 2] ## [2, 1]
## Select fruits containing 'a', change to upper case
fruits = ['apple', 'cherry', 'bannana', 'lemon']
afruits = [ f.upper() for f in fruits if 'a' in f]
##Python Dict and file
# dict is a key/value hash table
#-- looking up or setting a value uses square brackets
## Can build up a dict by starting with the the empty dict {}
## and storing key/value pairs into the dict like this:
## dict[key] = value-for-that-key
dict = {}
dict['a'] = 'alpha'
dict['g'] = 'gamma'
dict['o'] = 'omega'
#iterating through a dictionary
## Methods
dict.keys(), dict.values(), dict.items() ## returns a list of (key, value) tuples
for key in dict: print key
for key in dict.keys(): print key
print dict.keys()
print dict.values()
## Common case -- loop over the keys in sorted order,
## accessing each key/value
for key in sorted(dict.keys()):
print key, dict[key]
## .items() is the dict expressed as (key, value) tuples
print dict.items() ## [('a', 'alpha'), ('o', 'omega'), ('g', 'gamma')]
## Regular Expresions
##Regular expressions are used for matching text patterns.
'''
'\d' = 0-9
'\d\w' = 0s or 1f or 4n
'3n'
'4m'
'6g'
if '6g' in whatever:
do something
if '4m' in whatever:
do something
if '\d\w' in whatever:
do something
''
'''
|
b8d83b1fe2ead806b7ce3ba4ba4456d3e8184bdb | GrubbClub/CoderBytes | /check_nums.py | 243 | 4.09375 | 4 | def check_nums(num1, num2): #if 1 is < 2 its true, 1 > 2 false, if same return -1
if num1 == num2:
return (-1)
elif num1 < num2:
return True
else:
return False
print check_nums(3,122)
print check_nums(122, 3)
print check_nums(32, 32) |
c885239cc1a78c056c384b2e73c55d39d591d965 | leoCardosoDev/Python | /1-Curso-em-Video/00-desafios-python/desafio007.py | 191 | 3.921875 | 4 | nota1 = float(input('Primeira nota: '))
nota2 = float(input('Segunda nota: '))
media = (nota1 + nota2) / 2
print('A nota {} e a nota {} tem a média de {:.1f} '.format(nota1, nota2, media))
|
ff0d53d00df17aa857d1c2deae593363aa44fbfa | Inverseit/fifteen-puzzle | /timer.Py | 1,286 | 3.578125 | 4 | # provides timer for the application
import time
class Timer(object):
def __init__(self, master, canvas):
self.master = master
self.canvas = canvas
self.total = 0 # total passed since start
self.passed = 0 # passed after past resume or start
self.tag = ""
self.running = False # is started
self.stoped = False # is paused
def run(self):
print("started running")
self.running = True
self.start = time.time()
self.draw()
def draw(self):
if not self.stoped:
self.delete()
self.passed = round(time.time() - self.start,2)
self.tag = self.canvas.create_text(
255, 520, text=self.getTime(), font="Helvetica 16")
self.master.after(2, self.draw)
def getTime(self):
t = self.total + self.passed
return round(t, 2)
def getTotal(self):
return self.total
def delete(self):
if self.tag:
self.canvas.delete(self.tag)
def resume(self):
self.stoped = False
if not self.running:
return
self.start = time.time()
self.draw()
def stop(self):
self.stoped = True
self.total += self.passed
|
870e71a08d66afde1c8e1aa400bdfe034eabf996 | tmorgan181/Space_Blocks | /game_over.py | 4,037 | 4.03125 | 4 | # CS 3100 Team 8
# Spring 2021
#
# This file contains the functions needed to display the game over screen after a
# session is completed. If the final score of the game is a new high score, it
# will prompt the user to enter their name and add the score to the database.
import pygame as pg
import sys
from button import Button
import leaderboard as lb
from inputbox import InputBox
def show_game_over(window, score):
# Button colors
light_color = ("#50dbd4") # light teal
dark_color = ("#27aca5") # dark teal
# Store the width and height of the window
s_width = window.get_width()
s_height = window.get_height()
# Define button dimensions
button_width = 600
button_height = 60
# Define the game over screen dimensions and position
g_width = 380
g_height = 600
g_x = (s_width - g_width) / 2
g_y = (s_height - g_height) / 2
g_radius = 30
# Load game over image and determine placement position
img = pg.image.load("game_over_round.png")
img_width = img.get_width()
img_pos = (g_x+4, g_y+4)
img_small = pg.transform.scale(img, (g_width-8, g_height-8))
# Create the QUIT button in the bottom left corner
quit_pos = (10, s_height - button_height - 10)
quit_button = Button(quit_pos, button_width/2, button_height, text='EXIT GAME')
# Create the BACK button in the bottom right corner
back_pos = (s_width - button_width/2 - 10, s_height - button_height - 10)
back_button = Button(back_pos, button_width/2, button_height, text='BACK')
# Create the PLAY AGAIN button on the game over screen
play_again_pos = (g_x + (g_width - button_width/2)/2, g_y + (g_height - 100))
play_again_button = Button(play_again_pos, button_width/2, button_height, text='PLAY AGAIN')
# List of all buttons on this window
button_list = [quit_button, back_button, play_again_button]
# Retrieve the top ten scores to be placed in the table
table_data = lb.return_top_ten()
# print(table_data)
# Define a text box for the user's name
box_w = 300
box_h = 60
# InputBox(x, y, w, h)
name_box = InputBox(g_x + (g_width - box_w)/2, g_y + (g_height - 450), box_w, box_h)
input_boxes = [name_box]
### MENU LOOP ###
running = True
while running:
# Store the current mouse coordinates
mouse = pg.mouse.get_pos()
# Loop through all events
for event in pg.event.get():
# If a quit event is found, then exit the application
if event.type == pg.QUIT:
# Exit application
sys.exit()
# If the mouse is clicked
if event.type == pg.MOUSEBUTTONDOWN:
# If the mouse is positioned over the QUIT button
if quit_button.is_over(mouse):
# Exit application
sys.exit()
# If the mouse is positioned over the BACK button
if back_button.is_over(mouse):
running = False
break
# If mouse is over play again, then launch another game session
if play_again_button.is_over(mouse):
running = False
return True
# Handle input box events
for box in input_boxes:
output = box.handle_event(event)
if output != "":
print("Submission received:", output, "/", score)
lb.add_entry(output, score)
# Create a rectangle to outline the game over screen
pg.draw.rect(window, "black", (g_x, g_y, g_width, g_height), border_radius=g_radius)
window.blit(img_small, img_pos)
# Draw the GAME OVER text
text = "GAME OVER"
font = pg.font.SysFont('freesansbold.ttf', 64)
label = font.render(text, 1, "white")
window.blit(label, (g_x + 50, g_y + 40))
# Draw the Final Score text
text = "Final Score: " + str(int(score))
font = pg.font.SysFont('freesansbold.ttf', 32)
label = font.render(text, 1, "white")
window.blit(label, (g_x + 50, g_y + 100))
# Draw the buttons one at a time, checking if mouse is hovering
for button in button_list:
# Highlight buttons when moused over
if button.is_over(mouse):
button.draw(window, light_color)
else:
button.draw(window, dark_color)
# Draw the input box
for box in input_boxes:
box.draw(window)
# Updates the frame
pg.display.update()
return False |
8bfb06030a9b39f695ee038379f5ef6829e13bec | Bittu0184/PlacementPortal | /logindatab.py | 517 | 3.546875 | 4 | import sqlite3;
conn = sqlite3.connect('login.db');
conn.execute("create table logintab1 (username char(20) primary key NOT NULL,pass char(20) NOT NULL);")
conn.execute("insert into logintab1(username,pass) values('aditya','ag16')")
conn.execute("insert into logintab1(username,pass) values('aditya1','ag16')")
conn.execute("insert into logintab1(username,pass) values('aditya2','ag16')")
conn.execute("insert into logintab1(username,pass) values('aditya3','ag16')")
conn.commit()
conn.close() |
29477558fd988a9d33466596cd9c20cce6e6a9a4 | hschilling/OpenMDAO-Framework | /openmdao.units/openmdao/units/units.py | 26,215 | 3.90625 | 4 | """This module provides a data type that represents a physical
quantity together with its unit. It is possible to add and
subtract these quantities if the units are compatible and
a quantity can be converted to another compatible unit.
Multiplication, subtraction, and raising to integer powers
are allowed without restriction, and the result will have
the correct unit. A quantity can be raised to a non-integer
power only if the result can be represented by integer powers
of the base units.
The module provides a basic set of predefined physical quanitites
in its built-in library; however, it also supports generation of
personal libararies which can be saved and reused.
This module is based on the PhysicalQuantities module
in Scientific Python, by Konrad Hinsen. Modifications by
Justin Gray."""
import re, ConfigParser
import os.path
import numpy as N
# pylint: disable-msg=E0611,F0401, E1101
try:
from pkg_resources import resource_stream
except ImportError:
pass
#Class definitions
class NumberDict(dict):
"""
Dictionary storing numerical values
Constructor: NumberDict()
An instance of this class acts like an array of numbers with
generalized (non-integer) indices. A value of zero is assumed
for undefined entries. NumberDict instances support addition
and subtraction with other NumberDict instances, and multiplication
and division by scalars.
"""
def __getitem__(self, item):
try:
return dict.__getitem__(self, item)
except KeyError:
return 0
def __coerce__(self, other):
if isinstance(other, dict):
other = NumberDict(other)
return self, other
def __add__(self, other):
sum_dict = NumberDict()
for k, v in self.iteritems():
sum_dict[k] = v
for k, v in other.iteritems():
sum_dict[k] = sum_dict[k] + v
return sum_dict
def __sub__(self, other):
sum_dict = NumberDict()
for k, v in self.iteritems():
sum_dict[k] = v
for k, v in other.iteritems():
sum_dict[k] = sum_dict[k] - v
return sum_dict
def __mul__(self, other):
new = NumberDict()
for key, value in self.iteritems():
new[key] = other*value
return new
__rmul__ = __mul__
def __div__(self, other):
new = NumberDict()
for key, value in self.iteritems():
new[key] = value/other
return new
class PhysicalQuantity(object):
""" Physical quantity with units
PhysicalQuantity instances allow addition, subtraction,
multiplication, and division with each other as well as
multiplication, division, and exponentiation with numbers.
Addition and subtraction check that the units of the two operands
are compatible and return the result in the units of the first
operand.
"""
#class attributes
_number = re.compile('[+-]?[0-9]+(\\.[0-9]*)?([eE][+-]?[0-9]+)?')
def __init__(self, *args):
"""
There are two constructor calling patterns:
1. PhysicalQuantity(value, unit), where value is any number
and unit is a string defining the unit.
2. PhysicalQuantity(value_with_unit), where value_with_unit
is a string that contains both the value and the unit,
i.e. '1.5 m/s'. This form is provided for more convenient
interactive use.
@param args: either (value, unit) or (value_with_unit,)
@type args: (number, C{str}) or (C{str},)
"""
if len(args) == 2:
self.value = args[0]
self.unit = _find_unit(args[1])
else:
s = args[0].strip()
match = PhysicalQuantity._number.match(s)
if match is None:
raise TypeError("No number found in input argument: '%s'"%s)
self.value = float(match.group(0))
self.unit = _find_unit(s[len(match.group(0)):].strip())
def __str__(self):
return str(self.value) + ' ' + self.unit.name()
def __repr__(self):
return (self.__class__.__name__ + '(' + `self.value` + ',' +
`self.unit.name()` + ')')
def _sum(self, other, sign1, sign2):
"""sums units"""
if not isinstance(other, PhysicalQuantity):
raise TypeError('Incompatible types')
new_value = sign1*self.value + \
sign2*other.value*other.unit.conversion_factor_to(self.unit)
return PhysicalQuantity(new_value, self.unit)
def __add__(self, other):
return self._sum(other, 1, 1)
__radd__ = __add__
def __sub__(self, other):
return self._sum(other, 1, -1)
def __rsub__(self, other):
return self._sum(other, -1, 1)
def __cmp__(self, other):
diff = self._sum(other, 1, -1)
return cmp(diff.value, 0)
def __mul__(self, other):
if not isinstance(other, PhysicalQuantity):
return self.__class__(self.value*other, self.unit)
value = self.value*other.value
unit = self.unit*other.unit
if unit.is_dimensionless():
return value*unit.factor
else:
return PhysicalQuantity(value, unit)
__rmul__ = __mul__
def __div__(self, other):
if not isinstance(other, PhysicalQuantity):
return self.__class__(self.value/other, self.unit)
value = self.value/other.value
unit = self.unit/other.unit
if unit.is_dimensionless():
return value*unit.factor
else:
return self.__class__(value, unit)
def __rdiv__(self, other):
if not isinstance(other, PhysicalQuantity):
return self.__class__(other/self.value, pow(self.unit, -1))
value = other.value/self.value
unit = other.unit/self.unit
if unit.is_dimensionless():
return value*unit.factor
else:
return self.__class__(value, unit)
def __pow__(self, other):
if isinstance(other, PhysicalQuantity):
raise TypeError('Exponents must be dimensionless')
return self.__class__(pow(self.value, other), pow(self.unit, other))
def __rpow__(self, other):
raise TypeError('Exponents must be dimensionless')
def __abs__(self):
return self.__class__(abs(self.value), self.unit)
def __pos__(self):
return self
def __neg__(self):
return self.__class__(-self.value, self.unit)
def __nonzero__(self):
return self.value != 0
def convert_value(self, target_unit):
"""Converts the values of the PQ to the target_unit."""
(factor, offset) = self.unit.conversion_tuple_to(target_unit)
return (self.value + offset) * factor
def convert_to_unit(self, unit):
"""
Change the unit and adjust the value so that
the combination is equivalent to the original one. The new unit
must be compatible with the previous unit of the object.
@param unit: a unit
@type unit: C{str}
@raise TypeError: if the unit string is not a known unit or a
unit incompatible with the current one.
"""
unit = _find_unit(unit)
self.value = self.convert_value(unit)
self.unit = unit
def in_units_of(self, unit):
"""
Express the quantity in different units. If one unit is
specified, a new PhysicalQuantity object is returned that
expresses the quantity in that unit. If several units
are specified, the return value is a tuple of
PhysicalObject instances with with one element per unit such
that the sum of all quantities in the tuple equals the
original quantity and all the values except for the last one
are integers. This is used to convert to irregular unit
systems like hour/minute/second.
@param units: one or several units
@type units: C{str} or sequence of C{str}
@returns: one or more physical quantities
@rtype: L{PhysicalQuantity} or C{tuple} of L{PhysicalQuantity}
@raises TypeError: if any of the specified units are not compatible
with the original unit.
"""
unit = _find_unit(unit)
value = self.convert_value(unit)
return self.__class__(value, unit)
# Contributed by Berthold Hoellmann
def in_base_units(self):
"""
@returns: the same quantity converted to base units,
i.e. SI units in most cases
@rtype: L{PhysicalQuantity}
"""
new_value = self.value * self.unit.factor
num = ''
denom = ''
for unit, power in zip(_unit_lib.base_names, self.unit.powers):
if power < 0:
denom = denom + '/' + unit
if power < -1:
denom = denom + '**' + str(-power)
elif power > 0:
num = num + '*' + unit
if power > 1:
num = num + '**' + str(power)
if len(num) == 0:
num = '1'
else:
num = num[1:]
return self.__class__(new_value, num + denom)
def is_compatible(self, unit):
"""
@param unit: a unit
@type unit: C{str}
@returns: C{True} if the specified unit is compatible with the
one of the quantity
@rtype: C{bool}.
"""
unit = _find_unit(unit)
return self.unit.is_compatible(unit)
def get_value(self):
"""Return value (float) of physical quantity (no unit)."""
return self.value
def get_unit_name(self):
"""Return unit (string) of physical quantity."""
return self.unit.name()
def sqrt(self):
"""Parsing Square Root"""
return pow(self, 0.5)
def sin(self):
"""Parsing Sine."""
if self.unit.is_angle():
return N.sin(self.value * \
self.unit.conversion_factor_to(PhysicalQuantity('1rad').unit))
else:
raise TypeError('Argument of sin must be an angle')
def cos(self):
"""Parsing Cosine."""
if self.unit.is_angle():
return N.cos(self.value * \
self.unit.conversion_factor_to(PhysicalQuantity('1rad').unit))
else:
raise TypeError('Argument of cos must be an angle')
def tan(self):
"""Parsing tangent."""
if self.unit.is_angle():
return N.tan(self.value * \
self.unit.conversion_factor_to(PhysicalQuantity('1rad').unit))
else:
raise TypeError('Argument of tan must be an angle')
class PhysicalUnit(object):
"""
Physical unit
A physical unit is defined by a name (possibly composite), a scaling
factor, and the exponentials of each of the SI base units that enter into
it. Units can be multiplied, divided, and raised to integer powers.
"""
def __init__(self, names, factor, powers, offset=0):
"""
@param names: a dictionary mapping each name component to its
associated integer power (e.g. C{{'m': 1, 's': -1}})
for M{m/s}). As a shorthand, a string may be passed
which is assigned an implicit power 1.
@type names: C{dict} or C{str}
@param factor: a scaling factor
@type factor: C{float}
@param powers: the integer powers for each of the nine base units
@type powers: C{list} of C{int}
@param offset: an additive offset to the base unit (used only for
temperatures)
@type offset: C{float}
"""
if isinstance(names, str):
self.names = NumberDict(((names, 1),))
#self.names[names] = 1;
else:
self.names = names
self.factor = float(factor)
self.offset = float(offset)
self.powers = powers
def __repr__(self):
return 'PhysicalUnit(%s,%s,%s,%s)'% (self.names, self.factor,
self.powers, self.offset)
def __str__(self):
return '<PhysicalUnit ' + self.name() + '>'
def __cmp__(self, other):
if self.powers != other.powers:
raise TypeError('Incompatible units')
return cmp(self.factor, other.factor)
def __mul__(self, other):
if self.offset != 0 or (isinstance(other, PhysicalUnit) and \
other.offset != 0):
raise TypeError("cannot multiply units with non-zero offset")
if isinstance(other, PhysicalUnit):
return PhysicalUnit(self.names+other.names,
self.factor*other.factor,
[a+b for (a, b) in zip(self.powers, other.powers)])
else:
return PhysicalUnit(self.names+{str(other): 1},
self.factor*other,
self.powers,
self.offset * other)
__rmul__ = __mul__
def __div__(self, other):
if self.offset != 0 or (isinstance(other, PhysicalUnit) and \
other.offset != 0):
raise TypeError("cannot divide units with non-zero offset")
if isinstance(other, PhysicalUnit):
return PhysicalUnit(self.names-other.names,
self.factor/other.factor,
[a-b for (a, b) in zip(self.powers, other.powers)])
else:
return PhysicalUnit(self.names+{str(other): -1},
self.factor/float(other), self.powers)
def __rdiv__(self, other):
return PhysicalUnit({str(other): 1}-self.names,
float(other)/self.factor,
[-x for x in self.powers])
def __pow__(self, other):
if self.offset != 0:
raise TypeError("cannot exponentiate units with non-zero offset")
if isinstance(other, int):
return PhysicalUnit(other*self.names, pow(self.factor, other),
[x*other for x in self.powers])
if isinstance(other, float):
inv_exp = 1./other
rounded = int(N.floor(inv_exp+0.5))
if abs(inv_exp-rounded) < 1.e-10:
if all([x%rounded==0 for x in self.powers]):
f = self.factor**other
p = [x/rounded for x in self.powers]
if all([x%rounded==0 for x in self.names.values()]):
names = self.names/rounded
else:
names = NumberDict()
if f != 1.:
names[str(f)] = 1
for x, name in zip(p, _unit_lib.base_names):
names[name] = x
return PhysicalUnit(names, f, p)
raise TypeError('Only integer and inverse integer exponents allowed')
def conversion_factor_to(self, other):
"""
@param other: another unit
@type other: L{PhysicalUnit}
@returns: the conversion factor from this unit to another unit
@rtype: C{float}
@raises TypeError: if the units are not compatible.
"""
if self.powers != other.powers:
raise TypeError('Incompatible units')
if self.offset != other.offset and self.factor != other.factor:
raise TypeError(('Unit conversion (%s to %s) cannot be expressed' +
' as a simple multiplicative factor') % \
(self.name(), other.name()))
return self.factor/other.factor
# added 1998/09/29 GPW
def conversion_tuple_to(self, other):
"""
@param other: another unit
@type other: L{PhysicalUnit}
@returns: the conversion factor and offset from this unit to another unit
@rtype: (C{float}, C{float})
@raises TypeError: if the units are not compatible.
"""
if self.powers != other.powers:
raise TypeError('Incompatible units')
# let (s1,d1) be the conversion tuple from 'self' to base units
# (ie. (x+d1)*s1 converts a value x from 'self' to base units,
# and (x/s1)-d1 converts x from base to 'self' units)
# and (s2,d2) be the conversion tuple from 'other' to base units
# then we want to compute the conversion tuple (S,D) from
# 'self' to 'other' such that (x+D)*S converts x from 'self'
# units to 'other' units
# the formula to convert x from 'self' to 'other' units via the
# base units is (by definition of the conversion tuples):
# ( ((x+d1)*s1) / s2 ) - d2
# = ( (x+d1) * s1/s2) - d2
# = ( (x+d1) * s1/s2 ) - (d2*s2/s1) * s1/s2
# = ( (x+d1) - (d1*s2/s1) ) * s1/s2
# = (x + d1 - d2*s2/s1) * s1/s2
# thus, D = d1 - d2*s2/s1 and S = s1/s2
factor = self.factor / other.factor
offset = self.offset - (other.offset * other.factor / self.factor)
return (factor, offset)
# added 1998/10/01 GPW
def is_compatible(self, other):
"""
@param other: another unit
@type other: L{PhysicalUnit}
@returns: C{True} if the units are compatible, i.e. if the powers of the base units are the same
@rtype: C{bool}.
"""
return self.powers == other.powers
def is_dimensionless(self):
"""Dimensionless PQ"""
return not any(self.powers)
def is_angle(self):
"""Checks if this PQ is an Angle."""
return (self.powers[_unit_lib.base_types['angle']] == 1 and \
sum(self.powers) == 1)
def set_name(self, name):
"""Sets the name."""
self.names = NumberDict()
self.names[name] = 1
def name(self):
"""Looks like it's parsing fractions."""
num = ''
denom = ''
for unit in self.names.keys():
power = self.names[unit]
if power < 0:
denom = denom + '/' + unit
if power < -1:
denom = denom + '**' + str(-power)
elif power > 0:
num = num + '*' + unit
if power > 1:
num = num + '**' + str(power)
if len(num) == 0:
num = '1'
else:
num = num[1:]
return num + denom
#Helper Functions
_unit_cache = {}
def _find_unit(unit):
"""Find unit helper function."""
if isinstance(unit, str):
name = unit.strip()
try:
unit = _unit_cache[name]
except KeyError:
try:
unit = eval(name, {'__builtins__':None}, _unit_lib.unit_table)
except:
#check for single letter prefix before unit
if(name[0] in _unit_lib.prefixes and \
name[1:] in _unit_lib.unit_table):
add_unit(unit, _unit_lib.prefixes[name[0]]* \
_unit_lib.unit_table[name[1:]])
#check for double letter prefix before unit
elif(name[0:2] in _unit_lib.prefixes and \
name[2:] in _unit_lib.unit_table):
add_unit(unit, _unit_lib.prefixes[name[0:2]]* \
_unit_lib.unit_table[name[2:]])
#no prefixes found, unknown unit
else:
# Hack for currency, since $ is not a valid python var
if name[0] == "$":
unit = name[0]
return unit
else:
raise ValueError, "no unit named '%s' is defined" % name
unit = eval(name, {'__builtins__':None}, _unit_lib.unit_table)
_unit_cache[name] = unit
if not isinstance(unit, PhysicalUnit):
raise TypeError(str(unit) + ' is not a unit')
return unit
def _new_unit(name, factor, powers):
"""create new Unit"""
_unit_lib.unit_table[name] = PhysicalUnit(name, factor, powers)
def add_offset_unit(name, baseunit, factor, offset, comment=''):
"""Adding Offset Unit."""
if isinstance(baseunit, str):
baseunit = _find_unit(baseunit)
#else, baseunit should be a instance of PhysicalUnit
#names, factor, powers, offset=0
unit = PhysicalUnit(baseunit.names, baseunit.factor*factor,
baseunit.powers, offset)
unit.set_name(name)
if name in _unit_lib.unit_table:
if (_unit_lib.unit_table[name].factor!=unit.factor or \
_unit_lib.unit_table[name].powers!=unit.powers):
raise KeyError, "Unit %s already defined with " % name + \
"different factor or powers"
_unit_lib.unit_table[name] = unit
_unit_lib.set('units', name, unit)
if comment:
_unit_lib.help.append((name, comment, unit))
def add_unit(name, unit, comment=''):
"""Adding Unit."""
if comment:
_unit_lib.help.append((name, comment, unit))
if isinstance(unit, str):
unit = eval(unit, {'__builtins__':None}, _unit_lib.unit_table)
unit.set_name(name)
if name in _unit_lib.unit_table:
if (_unit_lib.unit_table[name].factor!=unit.factor or \
_unit_lib.unit_table[name].powers!=unit.powers):
raise KeyError, "Unit %s already defined with " % name + \
"different factor or powers"
_unit_lib.unit_table[name] = unit
_unit_lib.set('units', name, unit)
_unit_lib = ConfigParser.ConfigParser()
def do_nothing(string):
"""Makes the ConfigParser case sensitive."""
return string
_unit_lib.optionxform = do_nothing
def import_library(libfilepointer):
"""Imports a library."""
global _unit_lib
global _unit_cache
_unit_cache = {}
_unit_lib = ConfigParser.ConfigParser()
_unit_lib.optionxform = do_nothing
_unit_lib.readfp(libfilepointer)
required_base_types = ['length', 'mass', 'time', 'temperature', 'angle']
_unit_lib.base_names = list()
#used to is_angle() and other base type checking
_unit_lib.base_types = dict()
_unit_lib.unit_table = dict()
_unit_lib.prefixes = dict()
_unit_lib.help = list()
for prefix, factor in _unit_lib.items('prefixes'):
_unit_lib.prefixes[prefix] = float(factor)
base_list = [0 for x in _unit_lib.items('base_units')]
for i, (unit_type, name) in enumerate(_unit_lib.items('base_units')):
_unit_lib.base_types[unit_type] = i
powers = list(base_list)
powers[i] = 1
#print '%20s'%unit_type, powers
#cant use add_unit because no base units exist yet
_new_unit(name, 1, powers)
_unit_lib.base_names.append(name)
#test for required base types
missing = [utype for utype in required_base_types if not utype in \
_unit_lib.base_types]
if any(missing):
raise ValueError,"Not all required base type were present in the " + \
"config file. missing: %s, at least %s required" % \
(missing, required_base_types)
# Explicit unitless 'unit'.
_new_unit('unitless', 1, list(base_list))
retry1 = set()
retry2 = set()
retry_count = 0
last_retry_count = 99999
for name, unit in _unit_lib.items('units'):
data = unit.split(',')
if len(data) == 2:
try:
comment = data[1]
unit = data[0]
add_unit(name, unit, comment)
except NameError:
retry1.add((name, unit, comment))
elif len(data) == 4:
try:
factor, baseunit, offset, comment = tuple(data)
add_offset_unit(name, baseunit, float(factor), float(offset),
comment)
except NameError:
retry1.add((name, baseunit, float(factor), float(offset),
comment))
for cruft in ['__builtins__', '__args__']:
try:
del _unit_lib.unit_table[cruft]
except:
pass
while (last_retry_count != retry_count and len(retry1)!=0):
last_retry_count = retry_count
retry_count = 0
retry2 = retry1.copy()
for data in retry2:
if len(data) == 3:
name, unit, comment = data
try:
add_unit(name, unit, comment)
retry1.remove(data)
except NameError:
retry_count += 1
if len(data) == 5:
try:
name, factor, baseunit, offset, comment = data
add_offset_unit(name, factor, baseunit, offset, comment)
retry1.remove(data)
except NameError:
retry_count += 1
if(len(retry1) >0):
raise ValueError, "The following units were not defined because " + \
"they could not be resolved as a function of any other " + \
"defined units:%s" % [x[0] for x in retry1]
def convert_units(value, units, convunits):
"""Return the given value (given in units) converted
to convunits.
"""
pq = PhysicalQuantity(value, units)
pq.convert_to_unit(convunits)
return pq.value
try:
default_lib = resource_stream(__name__, 'unitLibdefault.ini')
except NameError: #pck_resources was not imported, try __file__
default_lib = open(os.path.join(os.path.dirname(__file__),
'unitLibDefault.ini'))
import_library(default_lib)
|
47fbd7660f9c6022ad67caf06c6648d3644d887a | virajbpatel/text_message_analysis | /sms_preprocess.py | 1,293 | 3.578125 | 4 | # NLP Project
# Import relevant modules
import pandas as pd
import re
import nltk
from nltk.tokenize import word_tokenize
#nltk.download('punkt')
# Function to remove URLs from message
def remove_url(message):
url = re.compile(r'https?://\S+|www\.\S+')
return url.sub(r'', message)
# Function to remove HTML tags from message
def remove_html(message):
html = re.compile(r'<.*?>')
return html.sub(r'', message)
# Import SMS data into a pandas dataframe
df = pd.read_csv('clean_nus_sms.csv', index_col = 0)
# Used df.info() to find that there are 3 null entries in Message field
# Conducting text preprocessing
# Remove null entries
df = df.dropna()
# Normalise text by setting all messages to lowercase
df["clean_message"] = df["Message"].str.lower()
# Remove punctuation
df['clean_message'] = df['clean_message'].replace('[^\w\s]','')
# Remove URLs
df['clean_message'] = df['clean_message'].apply(lambda message: remove_url(message))
# Remove HTML tags
df['clean_message'] = df['clean_message'].apply(lambda message: remove_html(message))
# Tokenize messages
df['tokenized_message'] = df.apply(lambda x: nltk.word_tokenize(x['clean_message']), axis = 1)
print(df.head())
df.to_csv("preprocessed_clean_nus_sms.csv", header = True) |
285107477f42dc9d5fb22f05d26e30c5c3041765 | eteq/keckguihws | /tkhelloworld2.py | 529 | 3.6875 | 4 | #!/usr/bin/env python
from Tkinter import Tk, Frame, Button, LEFT
class HelloApp(object):
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.button = Button(frame, text="QUIT", fg="red", command=frame.quit)
self.button.pack(side=LEFT)
self.hi_there = Button(frame, text="Hello", command=self.say_hi)
self.hi_there.pack(side=LEFT)
def say_hi(self):
print "Welcome to the world of tomorrow!"
root = Tk()
app = HelloApp(root)
root.mainloop() |
843291cf73e0df86bb483207b4f09a9971253e62 | sunlingyu2931/Tensorflow- | /example 1.py | 1,092 | 3.609375 | 4 | import tensorflow as tf
import numpy as np
x_data = np.random.rand(100).astype(np.float32) # create data
y_data = x_data * 0.1 +0.3 # 真实值
# create tensorflow stracture (start)
Weight = tf.Variable(tf.random_uniform([1],-1,1)) # weight 一般用variable inpout output 神经元等用constant
biases = tf.Variable(tf.zeros([1]))
# 和上面的y_data对比可以知道我们将weight define在-1-1之间而实际上上0。1,bias是0实际上是0。3。。通过不断的学习最后优化到0。1和0。3
y = Weight * x_data + biases
loss = tf.reduce_mean(tf.square(y-y_data)) #cost function
optimizer = tf.train.GradientDescentOptimizer(0.5) #learnining rate 0-1
train = optimizer.minimize(loss)
init = tf.initialize_all_variables() #variable 需要进行初始化
sess = tf.Session()
sess.run(init) # 激活initial
for step in range(201): # 训练201步
sess.run(train) # 指向train
if step % 20 == 0: # %取余,所以是每20步打印一次
print(step,sess.run(Weight),sess.run(biases)) # 激活weight biases
#sess.run()很重要,要注意 |
ee89cea4c018fea0dcb1318ab837f419328ee34b | jagchat/python | /02-language-basics/05-tuples/test.py | 2,667 | 4.75 | 5 | #tuple
# -a collection of elements/values
# -immmutable (not changeable)
# -allows duplicate elements
# -indexed (with an integer)
# -guaranteed of same order of elements
# -enclosed in parantensis - ()
#--initializing tuple with elements, nested tuples
s = ("hello", "hai", "world", "apple", "bat", "cat")
s = "hello", "hai", "world", "apple", "bat", "cat" #just another way
s = tuple(("hello", "hai", "world", "apple", "bat", "cat")) #just another way
print(s) #just prints the above tuple object
#s = ("hi") #this is not tuple, just a string
#s = "hi" #this is not tuple, just a string
s = "hi", #note comma at end. That makes it tuple
print(s)
s = () #empty tuple
print(s)
s1 = "hello", "hai"
print(s1[1]) #hai
s2 = "apple", "boy"
s3 = s1, s2 #nested tuple
print(s3)
print(s3[1][1]) #boy
print(len(s3)) #2
#--accessing and slicing elements
s = ("hello", "hai", "world", "apple", "bat", "cat")
print(s[1]) #prints "hai" (2nd element)
print(s[-2]) #prints "bat" (2nd from last)
s1 = s[2:] #slices from 3rd element into new list (subset)
print(s1) #['world', 'apple', 'bat', 'cat']
s1 = s[-3:] #reverse slicing
print(s1) #['apple', 'bat', 'cat']
s1 = s[:] #clone to new list
print(s1)
print(s[2]) #world
print(s[4]) #bat
s1 = s[1:4] #slice
print(s1) #["hai", "world", "apple"]
#tuple methods
s = ("1", "2", "3", "1", "4", "1", "2", "5")
print(s.count("1")) #3 - no. of "1" in tuple
print(s.index("5")) #find "5" in tuple - 7
s1 = [1, 2] #list
s2 = (1, 2, 3, 4, [1, 2], 5) #tuple with list as an element
print(s2.index(s1)) #search for list in a tuple - 4
#unpacking tuple
print("------------unpacking")
s = ("1", "2", "3")
f1, f2, f3 = s #need to match the size
print(f"f1 = {f1}, f2 = {f2}, f3 = {f3}")
#use "if" with tuples
print("-------------------with if")
s = ("hello", "hai", "world", "apple", "bat", "cat")
if "hai" in s:
print("exists")
#use "for" loop with tuples
print("-------------------for loop")
s = ("hello", "hai", "world", "apple", "bat", "cat")
for e in s:
print(e, end = " ")
print("\n")
for i in range(len(s)):
print(s[i], end = " ")
print("\n-------------------sliced")
for e in s[2:]: #using slicing
print(e, end = " ")
print("\n-------------------sorted")
for e in sorted(s):
print(e, end = " ")
print("\n-------------------reversed")
for e in reversed(s):
print(e, end = " ")
print("\n-------------------enumerated")
for i, e in enumerate(s):
print(f"{i} = {e}", end = ", ")
print("\n-------------------zipped")
s1 = ("hello", "hai", "world", "apple", "bat", "cat")
s2 = (10, 20, 30, 40, 50)
for e1, e2 in zip(s1, s2):
print(f"{e1} - {e2}", end = ", ") #shows only 5 as there are only 5 elements in s2
|
bbbc34ab3687d59ae5656f0c8c38ce0447756fbd | naveensr89/sound_classification_methods | /src/utils.py | 1,104 | 3.765625 | 4 | import os
def get_path_fname_ext(full_file_path):
"""Return path, filename without extension and extension
ex: get_path_fname_ext('/Users/example/test.txt')
('/Users/example', 'test', '.txt')"""
path, filename = os.path.split(full_file_path)
fname, ext = os.path.splitext(filename)
return path, fname, ext
def get_file_list(folder, extension=['.wav', '.aiff'], subdirectories=True):
""" Returns list of all the files in the given folder
recursively
"""
file_list = []
if subdirectories:
for path, subdirs, files in os.walk(folder):
for file in files:
if any(file.lower().endswith(ext.lower()) for ext in extension):
f = os.path.join(path, file)
file_list.append(f)
else:
for file in os.listdir(folder):
if os.path.isfile(os.path.join(folder, file)):
if any(file.lower().endswith(ext.lower()) for ext in extension):
f = os.path.join(folder, file)
file_list.append(f)
return file_list
|
6e9cc576794dfa8b28bf350685bedec94e56ec88 | porigonop/code_v2 | /cours_POO/TP2/CompteEpargne.py | 1,375 | 4 | 4 | #!/usr/bin/env python3
from CompteBancaire import *
class CompteEpargne(CompteBancaire):
"""permet de representer un compte epargne a partire d'un compte bancaire
"""
def __init__(self, nom_titulaire, solde_initial = 1000, \
interet = 0.3):
"""on initialise a l'aide de l'interet mensuel et des anciennes
valeur de compte bancaire
"""
CompteBancaire.__init__(self, nom_titulaire, solde_initial)
self.interet_mensuel = interet
def changeTaux(self, valeur):
"""permet de changer le taux mensuel du compte
"""
self.interet_mensuel = valeur
def capitalisation(self, nombreMois):
"""permet de faire monter le solde bancaire en fonction de
l'interet mensuel et du nombre de mois
"""
print("Capitalisation sur "+ str(nombreMois)+\
" mois au taux mensuel de "+str(self.interet_mensuel)+\
"% effectuée : ")
interet = self.solde*(self.interet_mensuel/100)*nombreMois
self.solde += interet
print("intérêt = " + str(interet)+"euro")
if __name__ == "__main__":
compte = CompteEpargne("Antoine")
compte.depot(1000)
compte.affiche()
compte.capitalisation(12)
compte.affiche()
compte.changeTaux(2)
compte.capitalisation(6)
compte.affiche()
|
cc6db5709b9ba5ccbb0160ad3336d5914334231f | elenaborisova/Python-Advanced | /18. Exam Prep/repeating_dna.py | 578 | 3.703125 | 4 | def get_repeating_dna(string):
repeating_subsequences = set()
index = 0
while index + 10 < len(string):
subsequence = string[index:index + 10]
if subsequence in string[index + 1:]:
repeating_subsequences.add(subsequence)
index += 1
return list(repeating_subsequences)
test = "AAAAAACCCCAAAAAACCCCTTCAAAATCTTTCAAAATCT"
result = get_repeating_dna(test)
print(result)
test = "TTCCTTAAGGCCGACTTCCAAGGTTCGATC"
result = get_repeating_dna(test)
print(result)
test = "AAAAAAAAAAA"
result = get_repeating_dna(test)
print(result)
|
11bb66562eefa09ca041e828237885c822efe9ed | xiaomingxian/python_base | /1.xxm/day12_minweb/3.装饰器/1/Demo2_装饰器.py | 562 | 3.84375 | 4 | # 持有原函数的引用 再对它加额外功能 同理与 java中的 装饰者模式
def out(fun):
def inner():
print("-----检验1------")
print("-----检验2------")
fun()
return inner
# @out
# def test1():
# print('-----test1-----')
def test1():
print('-----test1-----')
def main():
# @out
test1()
if __name__ == '__main__':
# 装饰者模式
# main()
# 相当于将函数引用传递给闭包 对它做功能增强后 再赋值给同名的引用
test1 = out(test1)
test1()
|
ac750073b1548456a6cf0089fa46b0bc1da9d27b | JesperGlas/networktool | /src/node.py | 778 | 3.5625 | 4 | from typing import Dict
from connection import Connection
class Node:
def __init__(self, name: str, processing: float = 0, queue: float = 0, connections: [Connection] = []):
self.name = name
self.proc = processing
self.queue = queue
self.con = connections
def __str__(self):
str_repr = f'Node {id(self)} | Name: {self.name} | Delays: Processing: {self.proc} ms | Queue: {self.queue} ms'
if len(self.con) > 0:
str_repr = str_repr + ' | Connections:'
return str_repr
def print_network(self, depth: int = 0):
print(('-' * depth) + self.__str__())
for connection in self.con:
destination: Node = connection.get_dest()
destination.print_network(depth=depth+1) |
7a07ef8a606a9b2943d9fecf980384c126bff0e8 | petersNikolA/turtle1 | /turtle8.py | 253 | 4 | 4 | import turtle
turtle.shape('turtle')
def sqspiral(n):
l = 5
while n > 0:
l += 5
for i in range(2):
turtle.forward(l)
turtle.left(90)
n -= 1
n = int(input())
sqspiral(n) |
6cc98eaaa9d4fd5be5af0eb4f77fcaa88df1e03b | anton1k/mfti-homework | /lesson_11/test_3.py | 377 | 4.125 | 4 | '''Напишите функцию calculate_min_cost(n, price) вычисления наименьшей стоимость достижения клетки n из клетки 1'''
def calculate_min_cost(n, price):
C = [float('-inf'), price[1], price[1]+price[2]] + [0]*(n-2)
for i in range(3, n+1):
C[i] = price[i] + min(C[i-1], C[i-2])
return C[n]
|
96abc8681717a9be43266bf9ce66b88ae6bab8dc | namntran/2021_python_principles | /workshops/4_busWhile2.py | 1,246 | 4 | 4 | # import math
n = int(input('Enter number of teams: '))
passengers = n*15
# num_small = int(math.ceil(passengers/10)) #number of small buses
# math.ceil(x) returns the smallest integer not less than x.
small = 0
big = 0
cost = 0.0
min_num_small = small # to keep track of number of small buses which gives minimum cost
min_num_large = big #to keep track of number of large buses which gives minimum cost
min_cost = small*95 #initial cost assuming all small buses
while(n>=0):
if(n>20):# small bus capacity of 10 passengers
cost = cost+200
n = n-48 # big bus capacity of 48 passengers
big = big+1
elif(n<=20):
cost=cost+95
n=n-10
small+=1
if cost<min_cost:
min_cost = cost
min_num_large = big
min_num_small = small
print('Book',min_num_small,'small buses and',min_num_large,'large buses')
print('The minimum cost is = $', min_cost)
# while(n>=0):
# if(n>20):# small bus capacity of 10 passengers
# cost = cost+200
# n = n-48 # big bus capacity of 48 passengers
# big = big+1
# elif(n<=20):
# cost=cost+95
# n=n-10
# small+=1
# print("Hire", big, "big buses and", small, "small buses. Cost = $", cost) |
543bdcb309c599cb4dcb414ddcef1c5ee9be9e1f | fabifer/talleres | /matematicas.py | 7,701 | 4.15625 | 4 | #!/usr/bin/python
#-*- coding: utf-8 -*-
#matematicas.py: ejemplo de estructuras de datos
def validarEntero(s):
ingresoCorrecto = False
while(not ingresoCorrecto):
try:
valor = int(raw_input(s))
ingresoCorrecto = True
except ValueError:
print("Debes ingresar un numero entero")
return valor
def sumarYRestar(n1, d1, n2, d2):
print("")
print("PRIMER PASO: Hallar el denominador comun")
print "Escribiremos el denominador comun como el producto entre", d1, "y",d2
print("")
msj1 = "Escriba el producto entre " + str(d1) + " y " + str(d2) + ": "
prod = validarEntero(msj1)
while(prod <> d1 * d2):
print("El resultado ingresado no es correcto. Intentalo nuevamente")
print("")
prod = validarEntero(msj1)
print("Muy bien. A partir de ahora trabajaremos con este resultado como denominador de las fracciones")
print("")
print "SEGUNDO PASO: Escribe las fracciones equivalentes de las fracciones originales con denominador ", prod
print("")
print str(n1) + "/" + str(d1) + " = --/" + str(prod)
print("")
msj2 = "Ingresa el numerador que corresponde a la fraccion de la derecha: "
num1 = validarEntero(msj2)
while(num1 <> prod * n1 / d1):
print "El resultado ingresado no es correcto. La fraccion " + str(num1) + "/" + str(prod) + " no es equivalente a la fraccion " + str(n1) + "/" + str(d1)
print("")
print str(n1) + "/" + str(d1) + " = --/" + str(prod)
print("")
num1 = validarEntero(msj2)
print("Muy bien. Hagamos el mismo procedimiento para la segunda fraccion")
print("")
print str(n2) + "/" + str(d2) + " = --/" + str(prod)
print("")
num2 = validarEntero(msj2)
while(num2 <> prod * n2 / d2):
print "El resultado ingresado no es correcto. La fraccion " + str(num2) + "/" + str(prod) + " no es equivalente a la fraccion " + str(n2) + "/" + str(d2)
print("")
print str(n2) + "/" + str(d2) + " = --/" + str(prod)
print("")
num1 = validarEntero(msj2)
print("Muy bien. Ahora tenemos dos fracciones con el mismo denominador")
print("")
def sumar(n1, d1, n2, d2):
aux2 = str(n1) + "/" + str(d1) + " + " + str(n2) + "/" + str(d2)
asteriscos = " "
for x in range(0, len(aux2) / 2 + 1):
asteriscos = asteriscos + " *"
if((len(aux2) % 2 == 0)):
asteriscos = asteriscos + " *"
else:
asteriscos = asteriscos + " * *"
print("")
print asteriscos
print " EJERCICIO * " + aux2 + " *"
print asteriscos
print("")
sumarYRestar(n1, d1, n2, d2)
print("TERCER PASO: Suma las fracciones de igual denominador")
print("Lo unico que debes hacer es sumar los numeradores")
prod = d1 * d2
num1 = prod * n1 / d1
num2 = prod * n2 / d2
mensaje = "Escribe el resultado de sumar " + str(num1) + " y " + str(num2) + ": "
numResultado = validarEntero(mensaje)
while(numResultado <> num1 + num2):
print("El resultado ingresado no es correcto. Intentalo nuevamente")
numResultado = validarEntero(mensaje)
print("")
print "Muy bien. Por lo tanto " + aux2 + " = " + str(numResultado) + "/" + str(prod)
simplificar(n1, d1, n2, d2, numResultado, prod)
def restar(n1, d1, n2, d2):
aux2 = str(n1) + "/" + str(d1) + " - " + str(n2) + "/" + str(d2)
asteriscos = " "
for x in range(0, len(aux2) / 2 + 1):
asteriscos = asteriscos + " *"
if((len(aux2) % 2 == 0)):
asteriscos = asteriscos + " *"
else:
asteriscos = asteriscos + " * *"
print("")
print asteriscos
print " EJERCICIO * " + aux2 + " *"
print asteriscos
print("")
sumarYRestar(n1, d1, n2, d2)
print("TERCER PASO: Resta las fracciones de igual denominador")
print("Lo unico que debes hacer es restar los numeradores")
prod = d1 * d2
num1 = prod * n1 / d1
num2 = prod * n2 / d2
mensaje = "Escribe el resultado de restar " + str(num1) + " menos " + str(num2) + ": "
numResultado = validarEntero(mensaje)
while(numResultado <> num1 - num2):
print("El resultado ingresado no es correcto. Intentalo nuevamente")
numResultado = validarEntero(mensaje)
print("")
print "Muy bien. Por lo tanto " + aux2 + " = " + str(numResultado) + "/" + str(prod)
simplificar(n1, d1, n2, d2, numResultado, prod)
def simplificar(n1, d1, n2, d2, num, den):
print("")
print("CUARTO PASO: Simplifica la fraccion obtenida como resultado")
a = num
b = den
n = num
m = den
while(a % b <> 0):
a, b = b, a % b
if(b == 1):
print("En este caso la fraccion es irreducible. No es necesario simplificar")
else:
print("Para ello debes calcular el maximo común divisor entre el numerador y el denominador")
msj = "Ingresa el maximo común divisor entre " + str(num) + " y " + str(den) + ": "
mcd = validarEntero(msj)
while(mcd <> b):
print("El resultado ingresado no es correcto. Intentalo nuevamente")
mcd = validarEntero(msj)
print("")
print("Correcto. Ahora divide el numerador y el denominador entre el maximo comun divisor hallado")
msj1 = "Ingrese el resultado de dividir " + str(num) + " entre " + str(mcd) + ": "
msj2 = "Ingrese el resultado de dividir " + str(num) + " entre " + str(mcd) + ": "
n = validarEntero(msj1)
while(n <> num / mcd):
print("El resultado ingresado no es correcto. Intentalo nuevamente")
n = validarEntero(msj1)
m = validarEntero(msj2)
while(m <> den / mcd):
print("El resultado ingresado no es correcto. Intentalo nuevamente")
m = validarEntero(msj2)
print("")
print("Muy bien. Has finalizado el ejercicio")
print("")
aux2 = "* " + str(n1) + "/" + str(d1) + " + " + str(n2) + "/" + str(d2) + " = " + str(n) + "/" + str(m) + " *"
asteriscos = "*"
for x in range(0, len(aux2) / 2 - 2):
asteriscos = asteriscos + " *"
if(len(aux2) % 2 == 0):
asteriscos = asteriscos + " *"
else:
asteriscos = asteriscos + " * *"
print("")
print " " + asteriscos
print " " + aux2
print " " + asteriscos
print ("")
print ("Bienvenido a la actividad de Matematicas. A continuacion veras una ayuda para sumar o restar fracciones.")
print ("")
num1 = 0
den1 = 0
num2 = 0
den2 = 0
while(num1 == 0):
try:
num1 = int(raw_input("Escribe el numerador de la primera fraccion (debe ser un entero distinto de cero): "))
except ValueError:
print("Debe ingresar un numero entero distinto de cero")
while(den1 == 0):
try:
den1 = int(raw_input("Escribe el denominador de la primera fraccion (debe ser un entero distinto de cero): "))
except ValueError:
print("Debe ingresar un numero entero distinto de cero")
while(num2 == 0):
try:
num2 = int(raw_input("Escribe el numerador de la segunda fraccion (debe ser un entero distinto de cero): "))
except ValueError:
print("Debe ingresar un numero entero distinto de cero")
while(den2 == 0):
try:
den2 = int(raw_input("Escribe el denominador de la segunda fraccion (debe ser un entero distinto de cero): "))
except ValueError:
print("Debe ingresar un numero entero distinto de cero")
print("")
opcion = raw_input("Si deseas sumar estas fracciones, ingresa la letra S. Si deseas restar estas fracciones, ingresa la letra R. Presiona 'Enter' para continuar: ")
while((opcion <> "R") and (opcion <> "S") and (opcion <> "s") and (opcion <> "r")):
print("Debes ingresar 'R' para restar o 'S' para sumar")
print("")
opcion = raw_input("Si deseas sumar estas fracciones, ingresa la letra S. Si deseas restar estas fracciones, ingresa la letra R. Presiona 'Enter' para continuar: ")
if((opcion == "R") or (opcion == "r")):
restar(num1, den1, num2, den2)
if((opcion == "S") or (opcion == "s")):
sumar(num1, den1, num2, den2)
|
cba209273dc6319505bdfdd98be6aaee8fc93042 | Karan1012/GMM-using-PCA | /gmm.py | 9,195 | 3.515625 | 4 | """Functions for fitting Gaussian mixture models"""
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import multivariate_normal
def gmm(data, num_clusters, plot=False):
"""
Compute the cluster probabilities, means, and covariances of a Gaussian mixture model
:param data: d x n matrix of n d-dimensional data points
:type data: ndarray
:param num_clusters: number of Gaussians to fit
:type num_clusters: int
:param plot: mode for plotting two-dimensional data. Can be False (no plotting), 'iter' (plot every iteration), or
'final' (plot the final Gaussians).
:return: tuple of (means, sigma, probs), where means is a d x num_clusters matrix, sigma is a list of num_clusters
matrices of size d by d, and probs is a length-k vector of cluster-membership probabilities
:rtype: tuple
"""
d, n = data.shape
# initialize clusters
mu = np.mean(data, 1)
centered_data = data - mu.reshape([-1, 1])
full_sigma = np.inner(centered_data, centered_data) / n
means = sample_gaussian(mu, full_sigma, num_clusters)
sigmas = []
for i in range(num_clusters):
sigmas.append(np.eye(d))
probs = np.ones(num_clusters) / num_clusters
# start outer loop
max_iters = 1000
tolerance = 1e-4
prev_probs = 0
# add this to covariance matrices to prevent them from getting too skinny
reg = 1e-4 * np.eye(d)
for i in range(max_iters):
membership = compute_membership_probs(data, means, sigmas, probs)
###################################################################
# Insert your code to update cluster prior, means, and covariances
# (probs, means, sigma)
###################################################################
probs = np.mean(membership, 1)
means = data.dot(membership.T) / np.sum(membership, 1)
for j in range(num_clusters):
diff = data - means[:, j].reshape((-1, 1))
sigmas[j] = (diff * membership[j, :]).dot(diff.T) / sum(membership[j, :], 0) + reg
##################################################################
# End of code to compute probs, means, and sigma
##################################################################
# plot GMM
if d == 2 and plot is 'iter':
plot_gmm(data, means, sigmas, probs)
plt.pause(1.0 / 30.0)
plt.clf()
# check for convergence
change = np.linalg.norm(prev_probs - probs)
prev_probs = probs
if change < tolerance:
break
if d == 2 and plot is 'final' or plot is 'iter':
plot_gmm(data, means, sigmas, probs)
return means, sigmas, probs
def compute_membership_probs(data, means, sigmas, probs):
"""
Compute the probability of each data example coming from each Gaussian in the Gaussian mixture model (GMM)
:param data: d x n matrix of n d-dimensional data points. Each column is an example.
:type data: ndarray
:param means: d x num_clusters matrix where each column is one of the Gaussian means
:type means: ndarray
:param sigmas: list of num_clusters covariance matrices (each of shape (d, d))
:type sigmas: list
:param probs: vector of length num_clusters of the prior probability of each cluster generating data
:type probs: arraylike
:return: matrix of shape (num_clusters, n) where the (i, j)th entry is the probability that example j was
generated by Gaussian i
:rtype: ndarray
"""
d, n = data.shape
num_clusters = probs.size
membership = np.zeros((num_clusters, n))
##############################################################
# Insert your code to update cluster membership probabilities
# for each data point
##############################################################
for j in range(num_clusters):
membership[j, :] = np.log(probs[j]) + gaussian_ll(data, means[:, j], sigmas[j])
log_normalizer = logsumexp(membership, 0)
membership = np.exp(membership - log_normalizer)
return membership
def gmm_ll(data, means, sigma, probs):
"""
Compute the overall log-likelihood of data given a Gaussian mixture model.
:param data: d x n matrix of n d-dimensional data points. Each column is an example.
:type data: ndarray
:param means: d x num_clusters matrix where each column is one of the Gaussian means
:type means: ndarray
:param sigma: list of num_clusters covariance matrices (each of shape (d, d))
:type sigma: list
:param probs: vector of length num_clusters of the prior probability of each cluster generating data
:type probs: arraylike
:return: the log-likelihood of all the data marginalizing out the cluster memberships
:rtype: float
"""
# The formula should be \prod_i \sum_k p(k) p(x_i | k)
# The log of that is \sum_i \log(sum_k p(k) p(x_i | k))
# p(x_i | k) should come from gaussian_ll
num_clusters = probs.size
d, n = data.shape
################################################################
# Insert your code to compute the log-likelihood. You may
# compute this using a loop over num_clusters, but you must not
# loop over n. Use logsumexp to avoid numerical imprecision.
################################################################
ll_per_cluster = np.zeros((num_clusters, n))
for i in range(num_clusters):
ll_per_cluster[i, :] = gaussian_ll(data, means[:, i], sigma[i])
ll = np.sum(logsumexp(ll_per_cluster + np.log(probs).reshape((-1, 1)), dim=0))
return ll
def gaussian_ll(data, mean, sigma):
"""
Compute the log-likelihoods of data points for a single Gaussian (parameterized by a mean and a covariance matrix).
:param data: d x n matrix of n d-dimensional data points. Each column is an example.
:type data: ndarray
:param mean: length-d vector mean
:type mean: arraylike
:param sigma: shape (d, d) covariance matrix
:type sigma: ndarray
:return: length-n array of log-likelihoods
:rtype: arraylike
"""
return multivariate_normal.logpdf(data.T, mean=mean, cov=sigma)
def sample_gaussian(mean, sigma, n):
"""
Sample from a multivariate Gaussian (parameterized by a mean and a covariance matrix).
:param mean: length-d vector mean
:type mean: arraylike
:param sigma: shape (d, d) covariance matrix
:type sigma: ndarray
:param n: number of samples to generate
:type n: int
:return: d x n matrix where each column is a generated sample
:rtype: ndarray
"""
samples = multivariate_normal.rvs(mean=mean, cov=sigma, size=n).T
if n == 1:
samples = samples.reshape((-1, 1))
return samples
def plot_gmm(data, means, sigmas, probs):
"""
Plot a two-dimensional Gaussian mixture model.
:param data: d x n matrix of n d-dimensional data points. Each column is an example.
:type data: ndarray
:param means: d x num_clusters matrix where each column is one of the Gaussian means
:type means: ndarray
:param sigmas: list of num_clusters covariance matrices (each of shape (d, d))
:type sigmas: list
:param probs: vector of length num_clusters of the prior probability of each cluster generating data
:type probs: arraylike
:return: None
"""
d, k = means.shape
num_clusters = probs.size
resolution = 50
angles = np.linspace(0, 2 * np.pi, resolution)
x = [np.cos(angles), np.sin(angles)]
for i in range(k):
a = 2 * np.linalg.cholesky(sigmas[i])
ellipse = a.dot(x) + means[:, i].reshape((-1, 1))
plt.plot(ellipse[0, :], ellipse[1, :], 'r:')
memberships = compute_membership_probs(data, means, sigmas, probs).argmax(0)
plot_k_means(data, means, memberships)
plt.title("GMM with %d Gaussians" % num_clusters)
def plot_k_means(data, means, memberships):
"""
Plot clustered data
:param data: d x n matrix of n d-dimensional data points. Each column is an example.
:type data: ndarray
:param means: d x num_clusters matrix where each column is one of the Gaussian means
:type means: ndarray
:param memberships: array of cluster-membership indices (each entry is an integer from 0 to num_clusters)
:type memberships: arraylike
:return: None
"""
num_clusters = len(np.unique(memberships))
for i in range(num_clusters):
members = memberships == i
plt.plot(data[0, members], data[1, members], 'xC%d' % i)
plt.plot(means[0, :], means[1, :], 'ok')
def logsumexp(matrix, dim=None):
"""
Compute log(np.sum(np.exp(matrix), dim)) in a numerically stable way.
:param matrix: input ndarray
:type matrix: ndarray
:param dim: integer indicating which dimension to sum along
:type dim: int
:return: numerically stable equivalent of np.log(np.sum(np.exp(matrix), dim)))
:rtype: ndarray
"""
max_val = np.nan_to_num(matrix.max(axis=dim, keepdims=True))
with np.errstate(under='ignore', divide='ignore'):
return np.log(np.sum(np.exp(matrix - max_val), dim, keepdims=True)) + max_val
|
096402638f0769a1465cbd88bb2efcab282c4c01 | vikramjit-sidhu/algorithms | /data_structures/fib_heap.py | 7,590 | 4.0625 | 4 | """
Fibonacci heap implementation
http://www.growingwiththeweb.com/2014/06/fibonacci-heap.html
http://stackoverflow.com/questions/19508526/what-is-the-intuition-behind-the-fibonacci-heap-data-structure
http://stackoverflow.com/questions/14333314/why-is-a-fibonacci-heap-called-a-fibonacci-heap
"""
import pdb
class FibHeapNode:
def __init__(self, key):
self.key = key
self.children = []
self.parent = None
self.degree = 0 #no of children
self.marked = False #has a child node been removed
def _update_degree(self):
self.degree = 0
for child in self.children:
self.degree += child.degree + 1
def insert_child(self, node):
""" Inserts a child node into the object from where method is called """
node.parent = self
self.children.append(node)
self.degree += node.degree + 1
def remove_child(self, child_remove):
height_removed = 0
for index, child in enumerate(self.children):
if child is child_remove:
height_removed = child.degree + 1
self.degree -= height_removed
del self.children[index]
break
else:
print("\nChild with key {0} not found in node with key: {1}".format(child_remove.key, self.key))
return height_removed
def traversal(self):
print(self.key, end=' ->')
for child in self.children:
print(child.key, end=' ')
print('\n', end=' ')
for child in self.children:
child.traversal()
class FibonacciHeap:
def __init__(self):
self.roots_list = []
self.min_root_index = None
def insert(self, elt):
""" Simply append node to roots list, leave maintenance operations for later """
if isinstance(elt, FibHeapNode):
node = elt
node.parent = None
node.marked = False
else:
elt_key = elt
node = FibHeapNode(elt)
if self.min_root_index is None:
self.min_root_index = 0
else:
min_node = self.roots_list[self.min_root_index]
if node.key < min_node.key:
self.min_root_index = len(self.roots_list)
self.roots_list.append(node)
def _add_as_root(self, node):
""" Add a node as root, change its parent property, mark it as False, etc """
node.parent = None
node.marked = False
self.roots_list.append(node)
def extract_min(self):
""" Removes min node, makes its children as roots and starts consolidate operation """
if self.min_root_index is None:
return None
min_node = self.roots_list[self.min_root_index]
min_key = min_node.key
del self.roots_list[self.min_root_index]
for children in min_node.children:
self._add_as_root(children)
# del(min_node) #operation not really necessary
self._consolidate()
self._set_min_index()
return min_key
def _consolidate(self):
""" Merge all roots which have the same degree. (same number of children) """
node_degree_hash = {} #hash containing, node degree:node index pairs
for node in self.roots_list:
if node.degree in node_degree_hash:
while node.degree in node_degree_hash:
#other node, with same degree, which has to be merged
merge_node = node_degree_hash[node.degree]
#deleting this degree entry from node_degree_hash as we are merging them
del node_degree_hash[node.degree]
node = self._merge(node, merge_node)
node_degree_hash[node.degree] = node
#update roots_list with new roots
self.roots_list = list(node_degree_hash.values())
def _merge(self, node1, node2):
""" node with smaller key becomes a child of other node """
if node1.key < node2.key:
node1.insert_child(node2)
return node1
node2.insert_child(node1)
return node2
def _set_min_index(self):
""" Iterates through all roots of heap and sets pointer to one with minimum key """
if self.roots_list:
min_val = self.roots_list[0].key
min_index = 0
else:
self.min_root_index = None
return
for index, node in enumerate(self.roots_list):
if node.key < min_val:
min_val = node.key
min_index = index
self.min_root_index = min_index
def update_key(self, old_key, new_key):
"""
Search node with BFS and update key
IMPORTANT: only supports decrease of key, increase not supported
"""
if old_key < new_key:
print("New key is greater, change not possible")
return None
from queue import Queue
qu = Queue()
for root in self.roots_list:
if root.key <= old_key:
qu.put_nowait(root)
while not qu.empty():
node = qu.get_nowait()
if node.key == old_key:
node.key = new_key
self._maintain_heap(node)
break
#accessing children of node to put into queue
for child in node.children:
if child.key <= old_key:
qu.put_nowait(child)
else:
#key not found, hence else is executed
print("\nKey: {0} not found in heap, hence not updated".format(old_key))
del(qu)
def _maintain_heap(self, node):
"""
Checks if node.key < parent.key if so branches it off and makes it a separate root, marking its parent (done in this method)
If parent was already marked, the parent has to be made a separate root as well,
continuing until an unmarked node is found or root (done in _check_marking)
"""
if (node.parent is not None) and (node.key < node.parent.key):
father = node.parent
ht_chd = father.remove_child(node)
self.insert(node)
self._check_marking(father, ht_chd)
elif node.parent is None:
min_key = self.roots_list[self.min_root_index].key
if min_key > node.key:
self.min_root_index = self.roots_list.index(node)
def _check_marking(self, node, ht_changed):
"""
If node has marked property set, remove it from its parent and make it a root, else mark it.
Root can never be marked, hence no need to check to see if root
"""
if node.marked:
father = node.parent
father.degree -= ht_changed
ht_changed += father.remove_child(node)
self.insert(node)
self._check_marking(father, ht_changed)
else:
if node.parent is None:
#check to see if node is root, root cannot be marked, hence break out
return
node.marked = True
node = node.parent
while node is not None:
#updating height of nodes upto root
node.degree -= ht_changed
node = node.parent
|
34c91b86f8873bc55fbdad235a85bde1ea0eec07 | csangh94/python | /test02/mega/big13.py | 886 | 3.640625 | 4 | a = input("스티커 값 =") # 스티커값(변수)
q = int(a) # 저장값 정수 변환
b = input("사려는 스티커 갯수 :")
w = int(b)
c = input("책갈피 값 =")
e = int(c)
d = input("책갈피 사려는 갯수 :")
r = int(d)
t=q*w # 스티커 총 더한 값 저장
y=e* # 책갈피 총 더한 값 저장
u=t+y # 스티커 총 값 + 책갈피 총 값
i=u/10 # 총 금액의 10% 값
print("---------------------------")
print("우수회원 할인으로 10% 할인을 받았습니다.") # "입력"
print("내가 낼 금액 = ",u-i,"원 입니다.") # 총 금액의 10%를 제한 값
|
86b777fc38b93f9f1b26cda4f0ef178e9e3f75e9 | MiguelVillanuev4/EDA1-Practica11 | /Incremental.py | 568 | 3.96875 | 4 | def insertionSort(n_lista):
for index in range(1, len(n_lista)):
actual=n_lista[index]
posicion=index
print("valor a ordenar={}".format(actual))
while posicion>0 and n_lista[posicion-1]>actual:
n_lista[posicion]=n_lista[posicion-1]
posicion=posicion-1
n_lista[posicion]=actual
print(n_lista)
print()
return n_lista
lista =[21, 10, 0, 11, 9, 24, 20, 14, 1]
print('lista desordenada {}'.format(lista))
insertionSort(lista)
print('lista ordenada {}'.format(lista))
|
cd416a6380b0a0872b200f43aa060bb8e5bebfcf | PET-Comp-UFMA/Monitoria_Alg1_Python | /05 - Funções/q05.py | 277 | 3.671875 | 4 | def Primo(n):
countDivision = 2
if n%2 ==0 and n!=2:
countDivision=countDivision+1
elif n%3 == 0 and n!=3:
countDivision= countDivision+1
if countDivision>2:
print("false")
else:
print("true")
n = int(input())
Primo(n)
|
cf386459b075e8947153bf6748d5b2783346d428 | rafaelperazzo/programacao-web | /moodledata/vpl_data/420/usersdata/323/87560/submittedfiles/exe11.py | 272 | 3.8125 | 4 | # -*- coding: utf-8 -*-
Numero=int(input('Digite seu numero inteiro com 8 algarismos:'))
if Numero//10000000 < 1:
print ('NAO SEI')
else:
soma=0
while Numero>0:
ultimo= Numero%10
soma = soma + ultimo
Numero = Numero//10
print(soma) |
d3af5b9e19dbc1e6aef5f03ef8482fc0e3711f7a | user-lmz/python | /function/t1.py | 158 | 3.703125 | 4 | #!/usr/bin/env python3
def add_end(L=None):
if L is None:
L = []
L.append('END')
return L
m = add_end()
n = add_end()
print(m)
print(n)
|
05e3a53a361169997822a1d43c7152368628789e | helloworld575/leetcode | /longestSubString.py | 541 | 3.703125 | 4 | class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
maxlength = 0
substring = ""
for i in range(len(s)):
print(substring)
while s[i] in substring:
substring = substring[1:]
substring+=s[i]
if len(substring)>maxlength:
maxlength = len(substring)
return maxlength
if __name__ == '__main__':
s = Solution()
print(s.lengthOfLongestSubstring("pwwkew"))
|
d1d8264c969ec6d2cc31720150b5505b08fc9f0b | cyberjon/app-a-day | /hangman.py | 1,254 | 4 | 4 | import random
words = ['cat', 'computer','house','desktop','python']
rand_no = random.randint(0,len(words)-1)
random_word = words[rand_no]
word = "_" * len(random_word)
clue = list(word)
lives=5
user_input = input('I am thinking of a random word. Would like to play Y/N:')
if user_input.lower() =='n':
print('Good Bye')
exit()
elif user_input.lower() =='y':
print('The numner of letters are: '+str(len(word)))
user_guess =True
while user_guess:
guess = input("Enter a letter:")
print(f'You have {lives}')
if guess in random_word:
index = random_word.index(guess)
print('The letter is in the word\n')
clue[index] = guess
word ="".join(clue)
print(word)
if word == random_word:
user_guess=False
print("You guessed right!")
print("You win")
print("Good Bye")
exit()
if guess not in random_word:
print('The letter is not in the word\n')
lives -= 1
if lives == 0:
print("You have use up all you lives\n Goodbye")
exit()
|
5bacc3d0bfd825b933715ecd18cdc59b8a4e3ad2 | Kyeongrok/python_algorithm | /chapter09_sort/01_select.py | 562 | 3.953125 | 4 | def findSmallestIndex(arr):
smallest = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest:
smallest = arr[i]
smallest_index = i
return smallest_index
def selectionSort(arr):
resultArr = []
for i in range(len(arr)):
smallest = findSmallestIndex(arr) # 가장 작은 숫자의 인덱스를 찾는다.
resultArr.append(arr.pop(smallest)) # 해당 인덱스에서 뽑아다가 resultArr에 넣는다.
return resultArr
print(selectionSort([5, 3, 6, 2, 10]))
|
d0af1c914a40daae9a3f21c84939ba29239a14e7 | sigirisetti/python_projects | /pylearn/numpy/data_analysis/fitting_line.py | 438 | 3.65625 | 4 | x = [0, 0.5, 1, 1.5, 2.0, 3.0, 4.0, 6.0, 10]
y = [0, -0.157, -0.315, -0.472, -0.629, -0.942, -1.255, -1.884, -3.147]
import numpy as np
p = np.polyfit(x, y, 1)
print(p)
slope, intercept = p
print(slope, intercept)
import matplotlib.pyplot as plt
xfit = np.linspace(0, 10)
yfit = np.polyval(p, xfit)
plt.plot(x, y, 'bo', label='raw data')
plt.plot(xfit, yfit, 'r-', label='fit')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.show() |
47734f1982d6ad94cd0c7e6b16cdf466d973c17d | wisesky/LeetCode-Practice | /src/101. Symmetric Tree.py | 1,203 | 3.921875 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if root == None:
return True
return self.helper(root.left, root.right)
def helper(self, head1, head2):
if head1 == None and head2 == None:
return True
if head1 == None or head2 == None:
return False
if head1.val != head2.val :
return False
# b1 = self.helper(head1.left, head2.left) and self.helper(head1.right, head2.right)
b2 = self.helper(head1.left, head2.right) and self.helper(head1.right, head2.left)
return b2
def initTree(pos, nums):
if pos > len(nums):
return None
if nums[pos-1] == None:
return None
root = TreeNode(nums[pos-1])
root.left = initTree(2*pos, nums)
root.right = initTree(2*pos+1, nums)
return root
nums = [1,2,2,3,4,4,3]
nums = [1,2,2,None,3,None, 3]
root = initTree(1, nums)
so = Solution()
print(so.isSymmetric(root))
|
8aefdf9fb53dc7bd9aa7bf74ee56f50606213f86 | luizaq/100-days-of-code | /Day4_rockpaperscissors.py | 1,437 | 3.984375 | 4 | rock = '''
_______
---' ____)
(_____)
(_____)
(____)
---.__(___)
'''
paper = '''
_______
---' ____)____
______)
_______)
_______)
---.__________)
'''
scissors = '''
_______
---' ____)____
______)
__________)
(____)
---.__(___)
'''
escolha=input(" Escolha 0 para pedra, 1 para papel,2 para tesoura")
escolha=int(escolha)
import random
escPc=random.randint(0,3)
if escolha==0 and escPc==0:
print(f"Empate!\n pc escolheu {rock} \n player escolheu: {rock}")
elif escolha==1 and escPc==1:
print(f"Empate!\n pc escolheu {paper} \n player escolheu: {paper}")
elif escolha==2 and escPc==2:
print(f"Empate!\n pc escolheu {scissors} \n player escolheu: {scissors}")
elif escolha==0 and escPc==1:
print (f"PC ganha!!! \n pc escolheu {paper}\n player escolheu {rock} ")
elif escolha==0 and escPc==2:
print (f"PC ganha!!! \n pc escolheu {scissors}\n player escolheu {rock} ")
elif escolha==1 and escPc==0:
print (f"Player ganha!!! \n pc escolheu {rock}\n player escolheu {paper} ")
elif escolha==1 and escPc==2:
print (f"PC ganha!!! \n pc escolheu {scissors}\n player escolheu {paper} ")
elif escolha==2 and escPc==0:
print (f"PC ganha!!! \n pc escolheu {rock}\n player escolheu {scissors} ")
elif escolha==2 and escPc==1:
print (f"Player ganha!!! \n pc escolheu {paper}\n player escolheu {scissors}")
else:
print("erro")
|
2186d77e302e51b5b08ff572a3e589642e271463 | RaghavGoyal/Raghav-root | /python/code/src/intermediate/Decorators/6.TimedFunctionsUsingDecorator.py | 592 | 3.65625 | 4 | from functools import wraps
from time import perf_counter
def timer(func):
@wraps(func)
def wrapper(n):
startTime = perf_counter()
result = func(n)
endTime = perf_counter()
duration = endTime - startTime
print(f'{func} took {duration:.8f}s')
return result
return wrapper
@timer
def fib(n):
fibList = [1, 1]
if n == 1:
return 1
if n == 2:
return fibList
while len(fibList) < n:
fibList.append(fibList[-1] + fibList[-2])
return fibList
if __name__ == '__main__':
print(fib(20))
|
b150da66ebc3c2258ca1381f12ba58b73063aea5 | wilane/content-mit-latex2edx-demo | /python_lib/matrix_evaluator.py | 2,092 | 3.578125 | 4 | #
# formula_evaluator: allows multiple possible answers, using options
#
import numpy
from evaluator2 import is_formula_equal
def test_formula(expect, ans, options=None):
'''
expect and ans are math expression strings.
Check for equality using random sampling.
options should be like samples="m_I,m_J,I_z,J_z@1,1,1,1:20,20,20,20#50"!tolerance=0.3
i.e. a sampling range for the equality testing, in the same
format as used in formularesponse.
options may also include altanswer, an alternate acceptable answer. Example:
options="samples='X,Y,i@[1|2;3|4],[0|2;4|6],0+1j:[5|5;5|5],[8|8;8|8],0+1j#50'!altanswer='-Y*X'"
note that the different parts of the options string are to be spearated by a bang (!).
'''
samples = None
tolerance = '0.1%'
acceptable_answers = [expect]
for optstr in options.split('!'):
if 'samples=' in optstr:
samples = eval(optstr.split('samples=')[1])
elif 'tolerance=' in optstr:
tolerance = eval(optstr.split('tolerance=')[1])
elif 'altanswer=' in optstr:
altanswer = eval(optstr.split('altanswer=')[1])
acceptable_answers.append(altanswer)
if samples is None:
return {'ok': False, 'msg': 'Oops, problem authoring error, samples=None'}
# for debugging
# return {'ok': False, 'msg': 'altanswer=%s' % altanswer}
for acceptable in acceptable_answers:
try:
ok = is_formula_equal(acceptable, ans, samples, cs=True, tolerance=tolerance)
except Exception as err:
return {'ok': False, 'msg': "Sorry, could not evaluate your expression. Error %s" % str(err)}
if ok:
return {'ok':ok, 'msg': ''}
return {'ok':ok, 'msg': ''}
def test():
x = numpy.matrix('[1,2;3,4]')
y = numpy.matrix('[4,9;2,7]')
samples="x,y@[1|2;3|4],[0|2;4|6]:[5|5;5|5],[8|8;8|8]#50"
print "test_formula gives %s" % test_formula('x*y', 'x*y', options="samples='x,y,i@[1|2;3|4],[0|2;4|6],0+1j:[5|5;5|5],[8|8;8|8],0+1j#50'!altanswer='-y*x'")
return x,y, samples
|
f25fc2c67bb93bef06237828fb7650fd5575d9f0 | PrateekPethe/Small-dictionary | /dictionary.py | 1,122 | 3.78125 | 4 | import json
from difflib import get_close_matches
data = json.load(open("dictionary.json"))
def translate(w):
w = w.lower()
if w in data:
return data[w]
elif len(get_close_matches(w, data.keys())) > 0:
yn = input("Did you mean %s instead? Enter Y if yes, or N if no: " % get_close_matches(w, data.keys())[0])
if yn == "Y":
return data[get_close_matches(w, data.keys())[0]]
elif yn == "N":
return "The word doesn't exist. Please double check it."
else:
return "We didn't understand your entry."
else:
return "The word doesn't exist. Please double check it."
loop = 0
while(loop !=2):
print("\nEnter Your Choice : ")
print("1. Search Word \n2. Exit \n")
choice = int(input())
if choice == 1:
word = input("Enter word: ")
output = translate(word)
if type(output) == list:
for item in output:
print(item)
else:
print(output)
elif choice == 2:
loop = 2
else:
print("Wrong Choice !. Press Either 1 or 2 ")
|
835d4da80ceb5652d9ea6b020814ba752daa73fb | vrcunha/db_sql_and_nosql | /sqlite/funcs/crud_sqlite.py | 2,966 | 3.53125 | 4 | import os
import sqlite3
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv())
def connect():
"""Connects to SQLite database."""
try:
connection = sqlite3.connect('sqlite_python.db')
# print('Connection Succefully')
return connection
except sqlite3.Error as e:
print(f'Connection Error to SQLite server: {e}')
def disconnect(connection):
"""Disconnects to SQLite database."""
connection.close()
# print('Connection Closed.')
def list_db_columns():
"""List DB columns."""
connection = connect()
cursor = connection.cursor()
cursor.execute('SELECT * FROM products')
produtos = cursor.fetchall()
if len(produtos) > 0 :
print('Table name: products')
for produto in produtos:
result = f'Id: {produto[0]} | Name: {produto[1]} |'\
f' Price: R$ {produto[2]} | Stock: {produto[3]}'
print(len(result)*'-')
print(result)
else:
print('Table name: products is empty.')
disconnect(connection)
def check_operation(connection, cursor):
connection.commit()
if cursor.rowcount == 1:
print(f'Operação realizada com sucesso.')
else:
print(f'A operação falhou.')
def insert():
"""Insert new item in table."""
connection = connect()
cursor = connection.cursor()
nome = input('Enter product name: ')
preco = input('Enter product price: ')
estoque = input('Enter product stock: ')
cursor.execute(f"INSERT INTO products" \
f"(name, price, stock) VALUES " \
f"('{nome}', {preco}, {estoque})")
check_operation(connection, cursor)
disconnect(connection)
def update(id, name=False, price=False, stock=False):
"""Update an item selected by id."""
connection = connect()
cursor = connection.cursor()
if name:
new_name = input('Enter new product name: ')
cursor.execute(f"UPDATE products SET name='{new_name}' WHERE id = {int(id)}")
check_operation(connection, cursor)
print('Product name successfully updated.')
if price:
new_price = input('Enter new product price: ')
cursor.execute(f"UPDATE products SET price={new_price} WHERE id = {int(id)}")
check_operation(connection, cursor)
print('Product price successfully updated.')
if stock:
new_stock = input('Enter new product stock: ')
cursor.execute(f"UPDATE products SET stock={new_stock} WHERE id = {int(id)}")
check_operation(connection, cursor)
print('Product stock successfully updated.')
else:
print('No items have been updated. ')
disconnect(connection)
def delete(id):
"""Delete an item selected by id."""
connection = connect()
cursor = connection.cursor()
cursor.execute(f"DELETE FROM products WHERE id = {int(id)}")
check_operation(connection, cursor)
disconnect(connection)
|
e578e16ee1cf342a67e195d3d1cf2c0b5a120c00 | syamilisn/Python-Files-Repo | /systemSoftware/sample.py | 83 | 3.515625 | 4 | dict={1:"we",2:"i"}
print(dict)
a=4
asval="they"
dict.update({a:asval})
print(dict) |
a1b955cfe6f2e47bf5d28d4e4a1fbdd3b373db0a | hpeppercorn/connect_four | /connect4_{hopepeppercorn}.py | 10,476 | 3.78125 | 4 | # -*- coding: utf-8 -*-
"""
A connect four game that can be played by two people, a person vs a computer or
the computer vs itself
"""
from copy import deepcopy
import os
from random import choice
def newGame(player1, player2):
"""
takes 2 string parameters corresponding to each player's name, and returns a
dictionary, game, which has 4 key - value pairs
player1 - first player's name
player2 - second player's name
who - integer 1 or 2 indicating whose turn it is to play
board - list of 6 lists, each with 7 elements representing the
board
"""
game = {
'player one' : player1,
'player two' : player2,
'who' : 1,
'board' : [[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0]]
} # game dictionary describing new game state
return game
def printBoard(board):
"""
takes a list of 6 lists each with 7 elements ("board") and
prints a nicely formatted connect 4 board with "X" representing player one's
moves and "O" representing player two's moves
"""
print("| 1 | 2 | 3 | 4 | 5 | 6 | 7 |\n\
+ - + - + - + - + - + - + - +") # prints labels for each column of the board
toprint = deepcopy(board)
for row in toprint:
for i in range(7):
if row[i] == 1:
row[i] = "X"
elif row[i] == 2:
row[i] = "O"
else:
row[i] = " "
print("| {} | {} | {} | {} | {} | {} | {} |\n\
+ - + - + - + - + - + - + - +".format(row[0], row[1], row[2], row[3], row[4], row[5], row[6]))
class WrongFormatError(ValueError):
pass
def loadGame():
"""
loads a particular game state by opening file game.txt containing the names
of player one and player two, an integer 1 or 2 depending on whose turn it
is to play, and a list of lists corresponding to the board in that
game state
returns this data in the form of a game dictionary with keys "player one",
"player two", "who" and "board"
"""
game = dict()
if not os.path.exists("game.txt"):
raise FileNotFoundError("The game file could not be loaded.")
with open("game.txt", mode="rt", encoding="utf8") as f:
lines = f.readlines()
if len(lines) != 9:
raise WrongFormatError("The game file was in the wrong format and could not be loaded.")
game['player one'] = lines[0][:-1]
game['player two'] = lines[1][:-1]
game['who'] = int(lines[2][:-1])
game['board'] = list()
for line in lines[3:9]:
line = line.split(",")
if len(line) != 7:
raise WrongFormatError("The game file was in the wrong format and could not be loaded.")
for i in range(len(line)):
line[i] = int(line[i])
if line[i] > 2 or line[i] < 0:
raise WrongFormatError("The game file was in the wrong format and could not be loaded.")
game['board'].append(line)
for key in game:
if game[key] == "":
raise WrongFormatError("The game file was in the wrong format and could not be loaded.")
return game
def getValidMoves(board):
"""
takes a list of lists representing the game board and determines which
'columns' are completely full - returns a list of indices 0-6 indicating which
columns are NOT full.
"""
validmoves = list()
for i in range(7):
for row in board:
if row[i] == 0:
validmoves.append(i)
break
else:
continue
return validmoves
def makeMove(board, move, who):
"""
takes input of a board, the move to be made and the player making the move,
and prints an 'X' or an 'O' (depending on the player) in the next available
space in the column specified by 'move'
"""
for row in reversed(board):
if row[move] == 0:
row[move] = who
break
return board
def hasWon(board, who):
"""
takes input of a list of lists representing the board in any game state, and
an integer 1 or 2 representing the player whose turn it is, and returns True
if the player has won, and false if not
"""
for j in range(6):
for i in range(4):
if board[j][i] == who and board[j][i+1] == who and board[j][i+2] == who and board[j][i+3] == who:
return True #horizontal check
for j in range(3):
for i in range(7):
if board[j][i] == who and board[j+1][i] == who and board[j+2][i] == who and board[j+3][i] == who:
return True #vertical check
for j in range(3):
for i in range(4):
if board[j][i] == who and board[j+1][i+1] == who and board[j+2][i+2] == who and board[j+3][i+3] == who:
return True #diagonal check 1
for j in range(3):
for i in range(7):
if board[j][i] == who and board[j+1][i-1] == who and board[j+2][i-2] == who and board[j+3][i-3] == who:
return True #diagonal check 2
return False
def suggestMove1(board, who):
"""
first checks if any valid move will lead to the current player winning and
if so returns this move, then checks if any valid move will lead to the
opponent winning and if so returns this move, and if neither of these results
in a move, returns a random valid move
"""
if who == 1:
opponent = 2
elif who == 2:
opponent = 1
print(getValidMoves(board))
for move in getValidMoves(board):
if hasWon(makeMove(deepcopy(board), move, who), who):
return move
for move in getValidMoves(board):
if hasWon(makeMove(deepcopy(board), move, opponent), opponent):
return move
return choice(getValidMoves(board))
def saveGame(game):
with open("game.txt", mode="wt", encoding="utf8") as f:
f.write(game['player one'] + "\n")
f.write(game['player two'] + "\n")
f.write(str(game['who']) + "\n")
for row in game['board']:
line = "{},{},{},{},{},{},{}\n".format(row[0], row[1], row[2], row[3], row[4], row[5], row[6])
f.write(line)
def play():
"""
the main function of the game, prints a welcome message, prints the board
turn, asks for the move the next player wishes to make, makes that move
and then reprints the board until someone has won the game at which point
prints a congratulations message and the game ends
"""
print("*"*55)
print("***"+" "*9+"WELCOME TO HOPE'S CONNECT FOUR!"+" "*9+"***")
print("*"*55,"\n")
print("Enter the players' names, or type 'C' or 'L'.\n")
player1 = input("Player one: ")
if player1 == "L":
game = loadGame()
printBoard(game['board'])
else:
player2 = input("Player two: ")
game = newGame(player1, player2)
printBoard(game['board'])
who = int(game['who'])
board = game['board']
print("To make a move please enter the number of the column you wish to place your counter in.")
while True:
if who == 1:
activeplayer = game['player one']
elif who == 2:
activeplayer = game['player two']
if activeplayer != "C":
move = input(str(activeplayer) + ", please make a move: ")
if move == "S":
saveGame(game)
break
move = int(move) - 1
if not move in getValidMoves(board):
print("\nThe move you tried to make wasn't in the board!\n")
move = int(input("Make a valid move: ")) - 1
printBoard(makeMove(board, move, who))
if hasWon(board, who):
print("\nCongratulations {}! You've won!".format(activeplayer))
break
elif activeplayer == "C":
move = suggestMove2(board, who)
print("\nComputer plays: {}\n".format(move+1))
printBoard(makeMove(board, move, who))
if hasWon(board, who):
print("\nComputer wins!".format(activeplayer))
break
if who == 1:
who = 2
elif who == 2:
who = 1
def suggestMove2(board, who):
"""function taking inputs board and whowhich makes a slightly better
suggestion for the next move for a computer opponent by adding a few extra
conditions to check"""
if who == 1:
if board == [[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0],
[0,0,0,0,0,0,0]]:
return 3
if who == 1:
opponent = 2
elif who == 2:
opponent = 1
valid = getValidMoves(board)
for move in valid:
if hasWon(makeMove(deepcopy(board), move, who), who):
return move
for move in valid:
if hasWon(makeMove(deepcopy(board), move, opponent), opponent):
return move
if hasWon(makeMove(makeMove(deepcopy(board), move, who), move, opponent), opponent):
valid.remove(move)
for row in board:
for i in range(1, 6):
if row[i] == opponent and row[i+1]:
return i-1
print(valid)
return choice(valid)
if __name__ == '__main__' or __name__ == 'builtins':
play()
|
00212f0146dc056290ca3a4b44f61d44f7aa5113 | pvpk1994/Leetcode_Medium | /Python/LinkedLists/Nth_Node_Remove.py | 1,972 | 3.578125 | 4 | # Remove Nth Node from Linked List
# Interesting: One Pass Approach using Fast and Slow Pointers
# Time Complexity: O(N) and Space Complexity: O(1)
# Leetcode Question: https://leetcode.com/problems/remove-nth-node-from-end-of-list/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
# ONE PASS ALGORITHM
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
sent = ListNode(-1)
sent.next = head
fast,slow = sent, sent
# Make first pointer advance n+1 steps so
# while it reaches End, the slow pointer remains at the node before the one to be deleted
for i in range(0, n+1):
fast = fast.next
# if here, the lead has been created: fast is n+1 nodes ahead of slow
while fast is not None:
# advance fast and slow one node at a time
fast = fast.next
slow = slow.next
# if here: fast has reached the end and slow has reached node just before the desired node to be deleted
slow.next = slow.next.next
return sent.next
''''
# Approach - 1
if head is None:
return head
current = head
len_list = 0
while current is not None:
len_list += 1
current = current.next
node_num = (len_list-n)+1
# print(node_num)
sent = ListNode(-1)
sent.next = head
prev = sent
current = head
counter = 0
while current and counter+1 != node_num:
tmp = current
counter += 1
current = current.next
prev = tmp
# if here counter == node_num
print(current.val)
print(counter)
tmp1 = current.next
current.next = None
prev.next = tmp1
return sent.next
'''
|
bd990aa94481f6ca4ce8a8b76ce1138a29f65355 | Alhzz/Python3 | /Key_Midterm.py | 320 | 3.640625 | 4 | """ Key_Midterm2014 """
def calculate():
""" Calculate Key """
id_card = input()
last_digit = (int(id_card)%1000)*10
total = 0
for i in id_card:
total += int(i)
total += last_digit
if total < 1000:
total += 1000
total = total%10000
print("%04d" %total)
calculate()
|
08f27c4fe465ecc9fa6144da1db658683ac865c3 | chand777/python | /sha.py | 953 | 4.40625 | 4 | # first_list=[1,2,3,4]
# second_list=first_list.copy()
# print(first_list)
# print(second_list)
# second_list[1]=1000
# print(first_list)
# print(second_list) #Here you can see that item for second_list only changed not for first_list because both the list has diffrent diffrent location
# first_list=[[1,2,3,4],[5,6,7,8]] # defination of shallow list will change when we will use nested list
# second_list=first_list.copy()
# print(first_list)
# print(second_list)
# first_list[0][1]=1000
# print(first_list) #here you can see that value is changed for both the list because it is refreaing to same object inside the nested list
# print(second_list)
first_list=[[1,2,3,4],[5,6,7,8]]
second_list=first_list.copy()
first_list.append([9,10,11,12])
print(first_list) # here you can see it is appended only on first_list not in second_list because they are refaring to different memory location
print(second_list) |
25b8f3ecd8769e9e5ec17838ec746b37fe83241c | sunilnandihalli/leetcode | /editor/en/[846]Hand of Straights.py | 1,421 | 3.71875 | 4 | # Alice has a hand of cards, given as an array of integers.
#
# Now she wants to rearrange the cards into groups so that each group is size W
# , and consists of W consecutive cards.
#
# Return true if and only if she can.
#
#
#
#
#
#
# Example 1:
#
#
# Input: hand = [1,2,3,6,2,3,4,7,8], W = 3
# Output: true
# Explanation: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8].
#
# Example 2:
#
#
# Input: hand = [1,2,3,4,5], W = 4
# Output: false
# Explanation: Alice's hand can't be rearranged into groups of 4.
#
#
#
# Note:
#
#
# 1 <= hand.length <= 10000
# 0 <= hand[i] <= 10^9
# 1 <= W <= hand.length
#
# Related Topics Ordered Map
def test():
ts = [([1, 2, 3, 6, 2, 3, 4, 7, 8], 3, True), ([1, 2, 3, 4, 5], 4, False),
([6, 7, 5, 3, 4, 7, 8, 10, 9, 6], 5, True)]
for arr, w, ans in ts:
s = Solution()
actual = s.isNStraightHand(arr, w)
print(arr, w, ans, actual)
assert actual == ans
from typing import List
# leetcode submit region begin(Prohibit modification and deletion)
import heapq as h
class Solution:
def isNStraightHand(self, hand: List[int], W: int) -> bool:
if W == 1:
return True
hand = sorted(hand)
incomplete_groups = []
for x in hand:
return len(incomplete_groups) == 0
# leetcode submit region end(Prohibit modification and deletion)
|
2a284c0174789853e2fe4640fba69deefcc3948e | maokitty/IntroduceToAlgorithm | /dataStruction/avl.py | 9,130 | 3.859375 | 4 | import random
class Node(object):
def __init__(self,key,right=None,left=None,parent=None):
self.right = right
self.left = left
self.parent = parent
self.key = key
# 树是单独的结构,BST用来操作BST树,确保BST的性质不会有改变
class AvlBST(object):
"""左子树的值小于父子树的值小于等于右子树的值
最坏情况是:成为一条链
"""
def __init__(self):
self.root = None
def insert(self,key):
node = Node(key)
x = self.root
xParent = None
while x!=None:
xParent = x
if node.key< x.key:
x=x.left
else:
x = x.right
if xParent == None:
self.root = node
return node
node.parent = xParent
if node.key<xParent.key:
xParent.left = node
else:
xParent.right = node
return node
def maximum(self,node = None):
startPosition = self.root if node is None else node
while startPosition is not None and startPosition.right is not None:
startPosition = startPosition.right
return startPosition
def minimun(self,node = None):
startPosition = self.root if node is None else node
while startPosition is not None and startPosition.left is not None:
startPosition = startPosition.left
return startPosition
def search(self,key):
node = self.root
while node is not None and node.key != key:
if key <node.key:
node = node.left
else:
node = node.right
return node
# 在没有重复的BST中,比key要大的最小的节点
def successor(self,key,node = None):
node = self.search(key) if node is None else node
if node is not None:
if node.right is not None:
return self.minimun(node.right)
nodeP = node.parent
while nodeP is not None and node != nodeP.left:
node = nodeP
nodeP=node.parent
return nodeP
return None
# ’_‘开头表示是内部实现
def _translate(self,delete,replace):
deleteP = delete.parent
if deleteP == None:
self.root = replace
elif delete == deleteP.left:
deleteP.left = replace
else:
deleteP.right = replace
if replace!=None:
replace.parent = deleteP
return delete
#左子树和右子树都存在是时需要找后继节点,如果后继节点不是要删除节点的右节点,需要再删除一次
def delete(self,key,node=None):
node = self.search(key) if node is None else node
if node is None:
return node
if node.right is None:
return self._translate(node,node.left)
elif node.left is None:
return self._translate(node,node.right)
else:
successor = self.minimun(node.right)
if successor != node.right:
self._translate(successor,successor.right)
successor.right = node.right
node.right.parent = successor
self._translate(node,successor)
node.left.parent = successor
successor.left = node.left
return successor
# 打印的方法
# 1:先序遍历
# 2:如果子节点不存在,那么所有子节点的打印空格数和父节点的长度保持一致
# 3:左右节点只要有一个不存在,就不显示斜杠
def __str__(self):
if self.root == None:
print("<empty tree>")
def recurse(node):
if node is None:
return [], 0 ,0
key = str(node.key)
left_lines ,left_num_pos, left_total_width=recurse(node.left)
right_lines ,right_num_pos ,right_total_width=recurse(node.right)
# 如果存在子元素 left_total_width - left_num_pos + right_num_pos + 1 加1保证两个子树之间最少存在一个空格,同事斜杠之间和数字的距离能反馈出这个加1
# 对于倒数第一层和第二层,倒数第一层不存在子元素,倒数第一层左右子节点都只有元素的长度,为了显示好看,横线在两者之间的间隔应该有元素字符串的长度 len(key)
length_between_slash = max(left_total_width - left_num_pos + right_num_pos +1,len(key))
# 数字在的位置 :左子树数字在的位置+斜杠之间
num_pos= left_num_pos + length_between_slash // 2
# 由于初始化的时候line_total_width都是0,不能用左边的距离加上右边的距离
line_total_width= left_num_pos+length_between_slash+(right_total_width - right_num_pos)
# 如果key的长度只有1,则不会替换
key = key.center(length_between_slash,'.')
# 由于斜线和点在同一列,会不美观
if key[0] == '.':key=' ' + key[1:]
if key[-1] == '.':key=key[:-1]+' '
parent_line = [' '*left_num_pos +key+' '*(right_total_width- right_num_pos)]
#扣除斜杠占据的位置
slash_line_str = [' '*(left_num_pos)]
if node.left is not None and node.right is not None:
slash_line_str.append('/')
slash_line_str.append(' '*(length_between_slash-2))
slash_line_str.append('\\')
elif node.left is None and node.right is not None:
slash_line_str.append(' '*(length_between_slash-1))
slash_line_str.append('\\')
elif node.left is not None and node.right is None:
slash_line_str.append('/')
slash_line_str.append(' '*(length_between_slash-1))
else:
slash_line_str.append(' '*(length_between_slash))
slash_line_str.append(' '*(right_total_width- right_num_pos))
slash_line=[''.join(slash_line_str)]
while len(left_lines)<len(right_lines):
# 最上的一层肯定是最长的,下面的每一行保持和最长层的长度一致
left_lines.append(' '*left_total_width)
while len(right_lines) < len(left_lines):
right_lines.append(' '*right_total_width)
child_line = [l+' '*(line_total_width-left_total_width-right_total_width)+r for l , r in zip(left_lines,right_lines)]
value = parent_line+slash_line+child_line
return value, num_pos, line_total_width
# list拼接直接换行就行
return '\n'.join(recurse(self.root)[0])
class Avl(AvlBST):
"""
高度平衡的二叉查找树
左子树的值小于父子树的值小于右子树的值,同时每个左子树的高度与右子树的高度差值不大于1
情况1:
1
\
2
\
3
左旋
2
/\
1 3
情况2:
3
/
1
\
2
对1进行左旋
3
/
2
/
1
再右旋
2
/\
1 3
情况3:
3
/
2
/
1
右旋
2
/\
1 3
情况4:
1
\
3
/
2
右旋:
1
\
2
\
3
左旋:
2
/\
1 3
"""
def __init__(self):
super(Avl, self).__init__()
def _height(self,node):
if node is None:
return -1
else:
return node.height
def _update_height(self,node):
node.height = max(self._height(node.left),self._height(node.right))+1
def insert(self,key):
node=super().insert(key)
self._reblance(node)
def _reblance(self,node):
while node is not None:
self._update_height(node)
if self._height(node.left) - self._height(node.right) >=2:
nodeL = node.left
if self._height(nodeL.left) < self._height(nodeL.right):
self._left_roate(nodeL)
self._right_roate(node)
elif self._height(node.right) - self._height(node.left) >=2:
nodeR = node.right
if self._height(nodeR.left) > self._height(nodeR.right):
self._right_roate(nodeR)
self._left_roate(node)
node = node.parent
def _right_roate(self,node):
'''当前节点的左节点高度-右节点高度>=2
右旋表示左边节点高
'''
pivot=node.left
pivot.parent = node.parent
if node == self.root:
self.root=pivot
else:
if node.parent.left is node:
pivot.parent.left = pivot
else:
pivot.parent.right = pivot
node.parent = pivot
tempNode = pivot.right
pivot.right = node
node.left = tempNode
if tempNode is not None:
tempNode.parent = node
self._update_height(pivot)
self._update_height(node)
def _left_roate(self,node):
'''当前节点的右节点高度-左节点高度>=2
从上到下,按照父子一对一对处理
'''
pivot = node.right
pivot.parent = node.parent
if node == self.root:
self.root = pivot
else:
if node.parent.left is node:
pivot.parent.left = pivot
else:
pivot.parent.right = pivot
tempNode = pivot.left
pivot.left = node
node.parent = pivot
node.right = tempNode
if tempNode is not None:
tempNode.parent = node
self._update_height(pivot)
self._update_height(node)
# 删除需要重新旋转
if __name__ == '__main__':
def testBST():
bst=AvlBST()
for x in range(1,60):
bst.insert(random.randint(1,1000))
val(bst.maximum(),"bst maximum:","empty bst")
val(bst.minimun(),"bst minimun:","empty bst")
bst.insert(23)
val(bst.search(23),"search result","key:"+str(23)+"not exist")
bst.insert(200)
bst.insert(210)
bst.insert(209)
bst.insert(202)
bst.insert(214)
bst.insert(216)
val(bst.successor(200),"successor is:","key:"+str(200)+"successor not exist")
val(bst.successor(216),"successor is:","key:"+str(216)+"successor not exist")
val(bst.delete(210),"delete is:","key:"+str(210)+" not exist")
print(bst)
def val(node,msg,reason):
print(msg,node.key) if node is not None else print(reason)
def testAVL():
avl = Avl()
for x in range(1,40):
avl.insert(random.randint(1,1000))
print(avl)
testAVL()
|
c25ef4b7f4e87ec0604b457093c0dcd1f76a9460 | anlanamy/DSA | /hw-1700015495/date_without_datetime.py | 448 | 3.921875 | 4 | #date
dtstr=input('Enter the datetime:(20170228):')
datekey={1:0,2:31,3:59,4:90,5:120,6:151,7:181,8:212,9:243,10:273,11:304,12:334}
datekeyr={1:0,2:31,3:60,4:91,5:121,6:152,7:182,8:213,9:244,10:274,11:305,12:335}
year=int(dtstr[:4])
month=int(dtstr[4:6])
day=int(dtstr[6:])
if year%4==0:
if year%100==0 and year%400!=0:
count=datekey[month]+day
else:
count=datekeyr[month]+day
else:
count=datekey[month]+day
print(count) |
31b54a5fe7ff8bea36169a8821891aa460f6c443 | wating41/game | /Python-game/01-if语句.py | 997 | 3.875 | 4 | import datetime
# if True :
# print('hello')
a = '赢'
if False:
print('你猜 1')
else:
print('你猜 2')
print('你确认是 %s' % a)
b = 'low'
c = ''
d = '98'
# 在命令行让用户输入一个用户名,获取用户输入,并进行判断
# 如果用户输入的用户名是admin,则显示欢迎管理员光临
# 如果用户输入的是其他的用户名,则什么也不做
name = input('请输入用户名:')
if name == 'admin':
print('欢迎管理员 %s' % name)
else:
print('您好!!!欢迎 %s 登录' % name)
# 让用户在控制台中输入一个年龄
# age = int(input('请输入你的年龄:'))
# 如果用户的年龄大于18岁,则显示你已经成年了
age = input('请输入你的年龄:')
# Year = datetime.date.strftime(datetime.date(), '%Y - %m - % d')
nameid = input('请输入你的生日:')
if age >= 18 :
print('恭喜你已经成年,可以喝酒!!')
else :
print('您还未成年!!')
# print(Year)
|
bd54456f0efd89489dc5bd9d0aab5b0f49dc5602 | Kobe-J/Python | /seleniumtest1/stu1.py | 6,638 | 3.890625 | 4 | import math
#
#
# def enroll(name, gender, age=6, city='Beijing'):
# print('name:', name)
# print('gender:', gender)
# print('age:', age)
# print('city:', city)
# print(enroll("yaoxilong","aa",22,"haerbin"))
#
#
# def calc(*a):
# sum = 0
# for n in a:
# sum = sum + n * n
# return sum
#
# print(calc(3,2))
#
# def enroll(name, age):
# print('name:', name)
# print('age:', age)
# print(enroll('姚希龙','22'))
#
#
# def quadratic(a, b, c):
# if b * b - 4 * c * a < 0:
# print('方程无解')
# else:
# x1 = (-b + math.sqrt(b * b - 4 * c * a)) / (2 * a)
# x2 = (-b - math.sqrt(b * b - 4 * a * c)) / (2 * a)
# return x1, x2
#
# print(quadratic(1, 2, 1))
#
# print(pow(5,4))
#
#
# n1 = 100
# n2 = 1500
# L = (n1,n2)
# for x in L:
# print("十六进制数为: "+hex(x))
#
#
# def yxl(ws):
# if ws>0:
# return ws
# else: ws<0
# return -ws
#
# print(yxl(int("1")))
#
# aa=input("您想打印的数字为:")
# # print(aa)
#
# a=100
# b=200
# l=(a,b)
# print(hex(min(l)))
# print(hex(max(l)))
#
# 计算任意n次方
# def power(x, n):
# s = 1
# n = abs(n)
# while n > 0:
# n = n - 1
# s = s * x
# return s
# print(power(2,-4))
#
# 递归函数
# def move(n, a, b, c):
# if n == 1:
# print(a, '-->', c)
# else:
# move(n - 1, a, c, b)#将n-1块由a绕过c搬运至b
# print(a, '-->', c)#将最后一块最大块由a搬运至c
# move(n - 1, b, a, c)#将b上的n-1块由把绕过a搬运至c
# move(3,"A","B","C")
#
#
# def list():
# L = []
# for i in range(100):
# if i != 0 & i % 2 == 1:
# L.append(i)
# print(L)
#
# print(list())
# 切片
# Y = ["a","b","c","v",]
# print(Y[0:5])
# def a(str):
# while str[-1:] == " " :
# str = str[:-1]
# while str[:1] == " " :
# str = str[1:]
# return str
# print(a(" kobe"))
# shuzu = ["a","b","c"]
# for a,b in enumerate(shuzu):
# print(a,b)
#
# def findone(L):
# if L == None:
# return (None,None)
# else:
# return (min(L),max(L))
#
# print(findone([1,4,3,5]))
#
# print(list(range(1, 11)))
#
# L = ['Hello', 'World', 18, 'Apple', None]
# print([s.lower() for s in L if isinstance(s,str)])
# Generator
# def fib(max):
# n, a, b = 0, 0, 1
# while n < max:
# print(b)
# a, b = b, a + b
# n = n + 1
# return None
# print(fib(6))
# def test():
# arr = [1]
# while True:
# yield arr
# arr = [1] + [arr[i] + arr[i + 1] for i in range(len(arr) - 1)] + [1]
# print(arr)
# def triangles():
# line = [1]
# while True:
# try:
# yield line
# line = [1] + [line[i] + line[i + 1] for i in range(len(line) - 1)] + [1]
# print(line)
# except StopIteration as e:
# print('Generator return value:', e.value)
# break
# a = 'python'
# print('hello,', a or 'world')
# b = a and False
# print(b)
# import time
# from functools import reduce
#
#
# def performance(a):
# def fn(*args, **kw):
# t1 = time.time()
# r = a(*args, **kw)
# t2 = time.time()
# print('call %s() in %fs' % (a.__name__, (t2 - t1)))
# print(a)
# print(fn)
# return r
# return fn
# @performance
# def factorial(n):
# return reduce(lambda x,y: x*y, range(1, n+1))
# print(factorial(10))
# 装饰器
# import time
# from functools import reduce
# def yxl(f):
# def ws(*args, **kw):
# t1=time.time()
# r = f(*args, **kw)
# time.sleep(0.3)
# t2=time.time()
# print("执行完毕,本次执行时间为:",t2-t1)
# print("执行完毕,本次执行结果为:",r)
# return ws
# @yxl
# def demo(n):
# return reduce(lambda x,y:x*y ,range(1,n))
#
# print(demo(6))
# import time
# from functools import reduce
#
#
# def performance(unit):
# def perf_decorator(f):
# def wrapper(*args, **kw):
# t1 = time.time()
# r = f(*args, **kw)
# t2 = time.time()
# t = (t2 - t1) * 1000 if unit == 'ms' else (t2 - t1)
# print('call %s() in %f %s' % (f.__name__, t, unit))
# return r
#
# return wrapper
#
# return perf_decorator
#
#
# @performance('ms')
# def factorial(n):
# return reduce(lambda x, y: x * y, range(1, n + 1))
#
#
# print(factorial(10))
# import os
#
# print(os.path.isdir(r'E:\project')) # 判断文件夹在该地址是否存在
# print(os.path.isfile(r'E:\project')) # 文件
# x = True
# # y = False
# # z = False
# #
# # if not x or y:
# # print(1)
# # elif not x or not y and z:
# # print(2)
# # elif not x or y or not y and x:
# # print(3)
# # else:
# # print(4)
# while 4==4:
# print("Hello")
# i = sum = 0
# print(i,sum)
# while i<=4:
# sum += i
# i = i+1
# print(i, sum)
# def Foo(x):
# print(x)
# if (x==1):
# return 1
# else:
# return x+Foo(x-1)
#
# print(Foo(6))
# str = '最短 = 1ms,最长 = 2ms,平均 = 1ms'
# i = 0
# j = []
# res1 = list(str)
# for r in res1:
# i += 1
# if r == "s":
# j.append(i)
# print(j)
# min = str[j[0]-3:j[0]-2]
# max = str[j[1]-3:j[1]-2]
# avg = str[j[2]-3:j[2]-2]
# print(min, avg, max)
# res = str[str.index("(")+1:str.index("%")+1]
# res1 = list(str)
# a = 0
# b = 0
# for r in res1:
# b +=1
# if r == "=":
# a = b
# print(a)
# print(b)
# print(str[a+1:-2])
# a = [1, 2, 3, 4]
# print(a[:-2])
# print(a[1:])
# print(a[:])
# a = 'This,is-Xsky'
# q = list(a)
# b = "".join(a[0:4])
# c = "".join(a[5:7])
# d = "".join(a[8:])
# # q.remove()
# q.append(b)
# q.append(c)
# q.append(d)
# print(str(q[q.index("This"):]).lower())
# print(sum(range(1, 5)))
mylist = [x for x in range(1, 100)]
mylist1 = [x for x in range(1, 100, 2) if x < 5] #嵌套判断
mylist2 = [x * x + x for x in range(1, 101, 2) if x < 50] #嵌套元素公式
mylist3 = [[x * x] for x in range(1, 100, 2) if x < 50] #嵌套列表
mylist4 = [x + y for x in range(100) for y in range(100)] #嵌套循环
#print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
#这是print的参bai数。其中sep代表两字符间隔开du方式,默认的zhi是一个空格,所以你哪里会出现一个空格,在后面加上sep=""就可以了
print(mylist,"\n",mylist1,"\n",mylist2,"\n",mylist3,"\n",mylist4,sep="")
# 使用列表生成器生成矩阵
# mylist = []
# for i in range(10):
# mylist.append([i * 10 + x for x in range(10)])
# for i in mylist:
# print(i) |
f0fb4cb44e672d8e3da738bf94840febdff6564e | Sagar-Kumar-007/ML-and-Ds- | /practice/Bengaluru House Price Detection/Flask basics/flask_basics_3.py | 916 | 3.953125 | 4 | # More about Dynamic Url
# The default variable type is string...you can change the data type to int, float and path...ex: <int:variable-name>
# You can also use two or more route decorators to run more functions on different web addresses.
# Note that using while using the parameters of route decorator it is preferred to use "/" at the end. Take an example of @app.route("/abc") and @app.route("/abc/")... In both the cases, if you enter /abc at the end of the url, you will get the same output but if you enter /abc/, you will get output only for the second case.
from flask import Flask
app=Flask(__name__)
@app.route("/a/<int:phone>/")
def func(phone):
return f"Your Phone number is {phone}"
@app.route("/b/<float:var>/") # Note that if you entered the address in the wrong data type then you will get an error.
def func2(var):
return f"You have entered: {var}"
if __name__=="__main__":
app.run() |
11e3dfb3d97bc7afd526283af39e672e72bcf56f | lorenzo3117/python-text-finder | /pythonTextFinder.py | 2,271 | 3.65625 | 4 | import os
import shutil
import re
def askInput():
print("This script will search for text you type in all txt files from the current directory and all its subdirectories. If any .txt files containing your text are found, you can copy them in a folder of your choice if you'd like to.\n")
text = input('What text are you searching for? ')
path = input('In what folder (from where the script is located, enter nothing for same folder)? ')
print()
path = f'{os.getcwd()}\\{path}'
return text, path
def findAllTxtFilesInDirectoryAndSubdirectories(path):
txtFiles = []
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.txt' in file:
txtFiles.append(os.path.join(r, file))
return txtFiles
def isTextInFile(text, file):
return re.search(rf'{text}', file, re.IGNORECASE)
def findTextInFiles(text, files):
filesWithTextFound = []
for file in files:
with open(file) as fileContent:
try:
if (isTextInFile(text, fileContent.read())):
filesWithTextFound.append(fileContent.name)
except Exception:
pass
return filesWithTextFound
def moveFiles(newFolderPath, files):
destination = f'{os.getcwd()}\\{newFolderPath}\\'
try:
os.mkdir(destination)
except Exception:
pass
for file in files:
try:
shutil.copy(file, destination)
except Exception:
pass
# Script
text, path = askInput()
txtFiles = findAllTxtFilesInDirectoryAndSubdirectories(path)
filesWithTextFound = findTextInFiles(text, txtFiles)
if (not filesWithTextFound):
print(f'No files found containing: {text}\n')
else:
print(f'The files contain: {text}')
for file in filesWithTextFound:
print(file)
copyFiles = input('\nDo you wish to copy the files (y/n)? ')
if (copyFiles.lower() == 'y' or copyFiles.lower() == 'yes'):
newFolderPath = input('\nIn what folder would you like to copy the files (can be an existing or a new one)? ')
moveFiles(newFolderPath, filesWithTextFound)
print('\nDone!\n')
input('Press any key to quit...') |
2f167f5317c8c3dc8fb146761eedb72d5f65dcc8 | Athreyan/guvi_python | /num_wrd.py | 237 | 3.921875 | 4 |
def int_to_en(num):
d = { 0 : 'Zero', 1 : 'One', 2 : 'Two', 3 : 'Three', 4 : 'Four', 5 : 'Five',
6 : 'Six', 7 : 'Seven', 8 : 'Eight', 9 : 'Nine', 10 : 'Ten'}
return d[num]
num=int(input())
print(int_to_en(num))
|
98d6efee02a276736abaccc1d04b8bd698dcbd01 | lilyfofa/python-exercises | /exercicio37.py | 517 | 4.15625 | 4 | numero = int(input('Digite um número inteiro: '))
base = int(input('Digite a base para a qual ele será convertido:\n1 - Binária\n2 - Octal\n3 - Hexadecimal\nSua resposta: '))
if base == 1:
print(f'O número {numero} na base binária é {bin(numero)[2:]}.')
elif base == 2:
print(f'O número {numero} na base octal é {oct(numero)[2:]}.')
elif base == 3:
print(f'O número {numero} na base hexadecimal é {hex(numero)[2:]}.')
else:
print('Por favor, digite somente algum desses números: 1, 2 e 3!') |
62e25ea245025f9b856766ce40eb39c88cfa4211 | jetli123/python_files | /Python基础教程/Python教程-字符串.py | 538 | 3.75 | 4 | width = input("Please enter width: ")
price_width = 10
item_width = width - price_width
header_format = '%-*s%*s'
Format = '%-*s%*.2f'
print '=' * width
print header_format % (item_width, 'Item', price_width, 'Price')
print '-' * width
print Format % (item_width, 'Apples', price_width, 0.4)
print Format % (item_width, 'Banana', price_width, 4.0)
print Format % (item_width, 'Orange', price_width, 3.2)
print Format % (item_width, 'Prunes (4 lbs.)', price_width, 0.34)
print Format % (item_width, 'Pineapple (16 oz.)', price_width, 8.5)
|
8eecf88f1c9e569482f71f41e222a8648f68da26 | bakeunbi99/Python | /Example/book/4_3_Ex01.py | 333 | 3.6875 | 4 | # 원소가 한 개인 경우
t = (10, )
print(t)
# 원소가 여러개인 경우
t2 = (1, 2, 3, 4, 5, 3)
print(t2)
# 튜플 색인
print(t2[0], t2[1:4], t2[-1])
# 수정 불가
# t2[0] = 10 #error
# 요소 반복
for i in t2 :
print(i, end=' ')
# 요소 검사
if 6 in t2 :
print("6 있음")
else:
print("6 없음") |
fda2029330ea1c3e781343d0ff159435b3fb1fa3 | alllecs/l_python | /inputout3.py | 447 | 3.53125 | 4 | #!/usr/bin/python3
d = int(input())
know_words = []
new_words = []
for i in range(0, d):
know_words.append(str(input().lower()))
l = int(input())
for i in range(0, l):
new_words.append(list(map(str, input().lower().split())))
for i in range(0, len(new_words)):
for j in range(0, len(new_words[i])):
if not new_words[i][j] in know_words:
print(new_words[i][j])
know_words.append(new_words[i][j])
|
935e91d3ec7bef8ccb3e07dbc41060d0068788ab | Activity00/Python | /leetcode/零钱兑换.py | 810 | 3.6875 | 4 | # coding: utf-8
"""
@author: 武明辉
@time: 2018/6/7 14:43
"""
"""
给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
示例 1:
输入: coins = [1, 2, 5], amount = 11
输出: 3
解释: 11 = 5 + 5 + 1
示例 2:
输入: coins = [2], amount = 3
输出: -1
说明:
你可以认为每种硬币的数量是无限的。
"""
def coinChange(coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
dp = [0] * amount
for i in range(1, amount):
dp[i] = min([dp[i-j]+1 for j in coins if i-j >= 0], default=-1)
return dp[-1]
if __name__ == '__main__':
print(coinChange([1, 2, 5], 11))
|
84f67d4e99e7f0634f4f8053fe7048914915b78c | erjan/coding_exercises | /unique_length_3_palindromic_subsequences.py | 2,068 | 4.1875 | 4 | '''
Given a string s, return the number of unique palindromes of length three that are a subsequence of s.
Note that even if there are multiple ways to obtain the same subsequence, it is still only counted once.
A palindrome is a string that reads the same forwards and backwards.
A subsequence of a string is a new string generated from the original string with some characters (can be none) deleted without changing the relative order of the remaining characters.
For example, "ace" is a subsequence of "abcde".
'''
basicsally first stores all elements with indices
now for elment having twice occurence of more using the first and last occurnces and getting how many distinct characters are there in between this way u can form palindrom
if u like the way i solved do upvote it gives A Lot of motivation
class Solution(object):
def countPalindromicSubsequence(self, s):
d=defaultdict(list)
for i,c in enumerate(s):
d[c].append(i)
ans=0
for el in d:
if len(d[el])<2:
continue
a=d[el][0]
b=d[el][-1]
ans+=len(set(s[a+1:b]))
return(ans)
------------------------------------------------------------------------------------------------------------
class Solution:
def countPalindromicSubsequence(self, s: str) -> int:
if len(s) < 3:
return 0
elif len(s) == 3:
return 1 if s[0]==s[2] else 0
else:
num_of_palindromes = 0
unique = list(set(s))
for char in unique:
count = s.count(char)
if count > 1:
# find first and last index of char in s
a_index = s.index(char)
c_index = s.rindex(char)
# find num of unique chars between the two indeces
between = s[a_index+1:c_index]
num_of_palindromes += len(list(set(between)))
return num_of_palindromes
|
186f0c48fa8e1351129377ade79bb1b50cf775c4 | mattfrancis888/Python_Data_Structures | /fran0880_a8/src/functions.py | 2,646 | 3.75 | 4 | '''
-------------------------------------------------------
[program description]
-------------------------------------------------------
Author: Matthew Francis
ID: 180920880
Email: fran0880@mylaurier.ca
__updated__ = "2019-03-20"
-------------------------------------------------------
'''
from Letter import Letter
DATA1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
DATA2 = "MFTCJPWADHKNRUYBEIGLOQSVXZ"
DATA3 = "ETAOINSHRDLUCMPFYWGBVKJXZQ"
def do_comparisons(file_variable, bst):
"""
-------------------------------------------------------
Retrieves every letter in file_variable from bst. Generates
comparisons in bst objects. Each Letter object in bst contains
the number of comparisons found by searching for that Letter
object in file_variable.
-------------------------------------------------------
Parameters:
file_variable - the already open file containing data to evaluate (file)
bst - the binary search tree containing 26 Letter objects
to retrieve data from (BST)
Returns:
None
-------------------------------------------------------
"""
file_variable.seek(0)
for line in file_variable:
for char in line.strip():
if char.isalpha():
#what is l
l = Letter(char.upper())
bst.retrieve(l)
return
def comparison_total(bst):
"""
-------------------------------------------------------
Sums the comparison values of all Letter objects in bst.
-------------------------------------------------------
Parameters:
bst - a binary search tree of Letter objects (BST)
Returns:
total - the total of all comparison fields in the bst
Letter objects (int)
-------------------------------------------------------
"""
total = 0
a = bst.inorder()
for v in a:
total = total + v.comparisons
return total
def letter_table(bst):
"""
-------------------------------------------------------
Prints a table of letter counts.
-------------------------------------------------------
Parameters:
bst - a binary search tree of Letter objects (BST)
Returns:
None
-------------------------------------------------------
"""
t_c = 0
a = bst.inorder()
for i in a:
t_c += i.count
print("Letter Count/Percent Table")
print()
print("Total Count: {:,}".format(t_c))
print()
print("Letter Count %")
print("------------------------")
for i in a:
print("{:>2}{:9,d}{:>13.2%}".format(i.letter, i.count, i.count / t_c))
return |
7c3bfb385d867930d0f8563f7d49e7a8655d4c1e | Chandan-CV/school-lab-programs | /lab program 36.py | 949 | 4.125 | 4 | #Program 36
#Write a program to create a dictionary of product name and price. Return
#the price of the product entered by the user.
#Name: Neha Namburi
#Date of Excetution: October 14, 2020
#Class: 11
d={} # empty dict
ans='y'
while((ans=='y') or (ans=='Y')):
# values of p and pr are local to this while loop- i.e. once leaves loop, new values
p=input("enter product name")
pr=float(input("enter price"))
d[p]= pr
ans= input("enter y or Y to continue")
print(d)
p=input("enter product name")
for i in d:
if(i==p):
print("price =", d[i])
break
else:
print("product not found")
''' Output for Program 36
enter product nameapple
enter price200
enter y or Y to continuey
enter product namebanana
enter price250
enter y or Y to continuey
enter product nameorange
enter price140
enter y or Y to continuej
{'apple': 200.0, 'banana': 250.0, 'orange': 140.0}
enter priduct nameorange
price = 140.0
'''
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.