blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
980704a325d7845138060370d2975c2ba5e42ea0 | jdiaz-dev/practicing-python | /SECTION 13 modules and packets/65 dates modules.py | 472 | 3.515625 | 4 | #date modules
#this module is in python by default
import datetime
#show today date
print(datetime.date.today())
#to get complete date
completeDate = datetime.datetime.now()
print(completeDate)
print(completeDate.year) #show year
print(completeDate.month) #show month
print(completeDate.day) #show day
# to custom date
customDate = completeDate.strftime('%d/%m/%Y, %H:%M:%S')
print(customDate)
#getting time in other format
print(datetime.datetime.now().time())
|
f20ac75fe9af810058223a9a2f534958f357ee8e | cehdeti/pyeti | /pyeti/utils.py | 2,643 | 3.953125 | 4 | import datetime
import re
def ignore_exception(*exception_classes):
"""
A function decorator to catch exceptions and pass.
@ignore_exception(ValueError, ZeroDivisionError)
def my_function():
...
Note that this functionality should only be used when you don't care about
the return value of the function, as it will return `None` if an exception
is caught.
"""
def decorator(func):
def func_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except (exception_classes):
pass
return func_wrapper
return decorator
_yes_values = ['y', 'yes', '1', 'true']
_no_values = ['n', 'no', '0', 'false', '']
def is_truthy(value):
"""
Utility function that converts various values to a boolean. Useful for web
requests, where the value that comes in may be "0" or "false", etc.
"""
if isinstance(value, str):
value = value.strip().lower()
if value in _yes_values:
return True
if value in _no_values:
return False
return bool(value)
_integer_re = re.compile(r'^\-?[\d,]*$')
_float_re = re.compile(r'^[-+]?[\d,]*\.?\d+([eE][-+]?\d+)?$')
def typecast_guess(value):
"""
Try to typecast the given string value into a proper python datatype.
"""
if not isinstance(value, str):
return value
stripped = value.strip()
if stripped.lower() in ['', 'none', 'na', 'n/a']:
return None
if _integer_re.match(value):
return int(clean_numeric_string(value))
if _float_re.match(value):
return float(clean_numeric_string(value))
return stripped
_non_numeric_re = re.compile(r'[^\+\-\d\.eE]')
def clean_numeric_string(value):
"""
Removes extraneous characters (commas, spaces, etc.) from number-like
strings.
"""
return _non_numeric_re.sub('', value)
class AgeMixin(object):
"""
Calculates the age of a person given a DateField of a person's birthday
"""
BIRTH_DATE_FIELD = 'birth_date'
@property
def age(self):
"""
The age today.
"""
return self.age_on(datetime.date.today())
def age_on(self, date):
"""
Returns the age on the given date.
"""
birth_date = getattr(self, self.BIRTH_DATE_FIELD)
if not birth_date:
return
if birth_date > date:
raise ValueError('Birth date after %s!' % date)
return date.year - birth_date.year - (
(date.month, date.day) < (birth_date.month, birth_date.day)
)
|
e5b19a2665932c1af7bdaeaa738ad6008f2c7d22 | KAPILJHADE/banking_system_python | /deposit.py | 878 | 3.703125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 25 19:08:25 2017
@author: dell
"""
from database import accountlist as items
def depositing():
amount=0
while 1:
entry = int(input("Enter the account number (1 for entire list,0 to exit) : "))
if entry==0:
break
elif entry==1:
for key in items.keys():
print (' {} {} {}'.format(key,items[key][0],items[key][1]))
elif entry in items.keys() :
print ('Name: {} Balance : {} '.format(items[entry][0],items[entry][1]))
deposit=int(input("\n Enter amount to be deposited : "))
items[entry][1]=items[entry][1]+deposit
amount+=items[entry][1]
break
else:
print(' account does not exists ')
print ("\n\n Your new balance is : ",amount) |
e070f0feedb5b6c1efa3f08e80e98e2484ea7574 | monikarychter/assigments | /rewrite_bigger.py | 86 | 3.6875 | 4 |
def bigger(x,y):
if x > y:
print(x)
else:
print(y)
bigger(1,8)
|
3a39966a47097e02b11823c38b11975df0e7feec | 20191014/kit2020-myflask | /testdb.py | 339 | 4.03125 | 4 | import sqlite3
conn = sqlite3.connect('mydb.db')
# Cursor 객체 생성
c = conn.cursor()
# 데이터 불러 와서 출력
for row in c.execute('SELECT * FROM student'):
print(row)
# 접속한 db 닫기
conn.close()
# CREATE TABLE "users" (
# "id" varchar(50),
# "pw" varchar(50),
# "name" varchar(50),
# PRIMARY KEY("id")
# ); |
1e3c93b94d57fbd151699296838a32dabb105ec0 | satishsolanki1990/Leetcode | /643_MaxAvgSubarray.py | 757 | 3.84375 | 4 | '''
Given an array consisting of n integers,
find the contiguous subarray of given length k that has the maximum average value.
And you need to output the maximum average value.
Example 1:
Input: [1,12,-5,-6,50,3], k = 4
Output: 12.75
Explanation: Maximum average is (12-5-6+50)/4 = 51/4 = 12.75
'''
class Solution:
def findMaxAverage(self, nums, k) :
p1 = 0
p2 = p1 + k
cur_sum = sum(nums[p1:p2])
ans = -float('inf')
n = len(nums)
while p2 <= n:
ans = max(ans, cur_sum / k)
if p2 < n:
cur_sum = cur_sum - nums[p1] + nums[p2]
p2 += 1
p1 += 1
return ans
s=Solution()
nums=[1,12,-5,-6,50,3]
k=4
print(s.findMaxAverage(nums,k)) |
195315f70d1ea0565494a8ea958d5ad2e1675f44 | rifatmondol/Python-Exercises | /008 - [Strings] Contagem de Vogais.py | 640 | 4.03125 | 4 | #008 - Conta espaços e vogais. Dado uma string com uma frase informada pelo usuário (incluindo espaços
#em branco), conte:
#a. quantos espaços em branco existem na frase.
#b. quantas vezes aparecem as vogais a, e, i, o, u.
frase = input('Digite uma frase: ')
letraA = frase.count('a')
letraE = frase.count('e')
letraI = frase.count('i')
letraO = frase.count('o')
letraU = frase.count('u')
espaco = frase.count(' ')
print('Letra A: {}'.format(letraA))
print('Letra E: {}'.format(letraE))
print('Letra I: {}'.format(letraI))
print('Letra O: {}'.format(letraO))
print('Letra U: {}'.format(letraU))
print('Espaços: {}'.format(espaco)) |
07ad2860872539501b7aa59dc6f42af8ed79166d | ramangerami/Home_Manager | /detached_home.py | 3,161 | 3.65625 | 4 | from abstract_home import AbstractHome
from sqlalchemy import Column, String, Integer, Float, DateTime
class DetachedHome(AbstractHome):
""" Child class of AbstractHome that creates a DetachedHome object """
FLOORS_LABEL = "Number of Floors"
HAS_SUITE_LABEL = "Has Suite"
DETACHED_HOME_TYPE = 'detached home'
# booleans are represented as Integer 0 and 1
number_of_floors = Column(Integer)
has_rental_suite = Column(Integer)
def __init__(self, home_id, square_feet, year_built, rooms, bathrooms, city, seller, tax, floors, has_suite):
""" Constructor for Condo object """
super().__init__(home_id, square_feet, year_built, rooms, bathrooms, city, seller, tax, DetachedHome.DETACHED_HOME_TYPE)
AbstractHome._validate_int_input(DetachedHome.FLOORS_LABEL, floors)
self.number_of_floors = floors
AbstractHome._validate_bool_input(DetachedHome.HAS_SUITE_LABEL, has_suite)
self.has_rental_suite = has_suite
# def get_number_of_floors(self):
# """ Returns the number of floors for a DetachedHome object """
# return self._number_of_floors
def get_has_rental_suite_bool(self):
""" Returns boolean for if a home has a rental suite """
return self.has_rental_suite == AbstractHome.BOOLEAN_TRUE
def get_description(self):
""" Returns a description of a DetachedHome object with details relevant to buyers and seller """
description = "This is a " + str(self.square_footage) + " square foot home " + "built in " + str(self.year_built)\
+ " " + "with " + str(self.number_of_floors) + " floors, " + str(self.number_of_rooms) + " rooms, "\
+ str(self.number_of_bathrooms) + " bathrooms"\
+ " and a yearly property tax of " + str(self.yearly_property_tax) + ". This home is being sold by "\
+ self.selling_agent
return description
# def get_type(self):
# """ Return type of a DetachedHome Object """
# return DetachedHome.DETACHED_HOME_TYPE
def to_dict(self):
""" Get a Python Dictionary representation of the Detached Home """
detached_home_dict = dict()
detached_home_dict["square_feet"] = int(self.square_footage)
detached_home_dict["year_built"] = int(self.year_built)
detached_home_dict["number_of_rooms"] = int(self.number_of_rooms)
detached_home_dict["number_of_bathrooms"] = int(self.number_of_bathrooms)
detached_home_dict["city"] = str(self.city)
detached_home_dict["selling_agent"] = str(self.selling_agent)
detached_home_dict["yearly_property_tax"] = float(self.yearly_property_tax)
detached_home_dict["number_of_floors"] = int(self.number_of_floors)
# detached_home_dict["has_rental_suite"] = bool(self.has_rental_suite)
detached_home_dict["has_rental_suite"] = int(self.has_rental_suite)
detached_home_dict["type"] = self.home_type
detached_home_dict["id"] = int(self.home_id)
# if self.get_id() is not None:
# detached_home_dict["id"] = self.get_id()
return detached_home_dict |
a899c345580eac52adb3168290bbc50d2718bf34 | CalamariDude/youtube | /Intro to Multiprocessing - Python/extras/example.py | 710 | 3.5625 | 4 | import multiprocessing
from multiprocessing import Process
import time
class Chef(Process):
def __init__(self):
Process.__init__(self)
def season_chicken(self):
#Takes 3 seconds to season chicken
time.sleep(1)
def cook_chicken(self):
#Takes 10 seconds to cook the chicken
time.sleep(1)
def run(self):
self.season_chicken()
self.cook_chicken()
print(multiprocessing.current_process().name, 'done with chicken')
print('total processors', multiprocessing.cpu_count())
chef1 = Chef()
ts = time.time()
chef1.start()
chef1.join()
print('Time taken for all 4 chefs to finish cooking chicken:', round(time.time()-ts,2), 'seconds.') |
58f29876890d89495e98614e63b8af38f89e6874 | dx19910707/LeetCode | /637(二叉树的层平均值).py | 1,060 | 3.78125 | 4 | # Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def averageOfLevels(self, root):
"""
:type root: TreeNode
:rtype: List[float]
"""
l = []
if not root:
return l
current_level = [root]
while current_level:
next_level = []
level_sum = 0
for current_root in current_level:
level_sum += current_root.val
if current_root.left:
next_level.append(current_root.left)
if current_root.right:
next_level.append(current_root.right)
l.append(level_sum / float(len(current_level)))
current_level = next_level
return l
a1 = TreeNode(3)
a2 = TreeNode(9)
a3 = TreeNode(20)
a4 = TreeNode(15)
a5 = TreeNode(7)
a1.left = a2
a1.right = a3
a3.left = a4
a3.right = a5
x = Solution().averageOfLevels(a1)
print(x) |
d2c9bcff5fad9e301e48c22bec8bba955e119564 | BaijunY/smart_alarm | /playground/reading_brightness.py | 1,635 | 3.75 | 4 | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
def read_photocell():
"""reads the surrounding brightness using the
connected photocell and transforms the values to
a scale of 0 - 15 in order to adjust the displays
brightness"""
photocell_input_pin = 20
upper_limit = 400
lower_limit = 1
counter = 0
summed_up_brightness = 0
max_iterations = 5
while counter < max_iterations:
brightness = 0
# needs to be put low first, so the capacitor is empty
GPIO.setup(photocell_input_pin, GPIO.OUT)
GPIO.output(photocell_input_pin, GPIO.LOW)
time.sleep(0.1)
# set to input to read out
GPIO.setup(photocell_input_pin, GPIO.IN)
# increases the brightness variable depending on the charge
# of the capacitor (400 = dark; 0 = bright)
while GPIO.input(photocell_input_pin) == GPIO.LOW:
brightness += 1
summed_up_brightness = summed_up_brightness + brightness
counter += 1
# calculate the mean of the last 'max_iterations' measurements:
brightness = summed_up_brightness / max_iterations
# turn values up-side down: dark-to-bright
brightness = upper_limit - brightness
# limit the value of measured brightness
if brightness > upper_limit:
brightness = brightness - (brightness - upper_limit)
elif brightness < lower_limit:
brightness = brightness - brightness + lower_limit
# scale brightness to the scale of 0 - 15
brightness = brightness / (upper_limit / 15)
return brightness
while True:
print read_photocell()
|
46192aac5064b59a2207cd98529b0f6219d83bc0 | kanglicheng/CodeBreakersCode | /from Stephen/google list/1110. Delete Nodes And Return Forest (DFS, pass).py | 1,167 | 3.640625 | 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 delNodes(self, root: TreeNode, to_delete: List[int]) -> List[TreeNode]:
def dfs(curNode, toDel, res):
if curNode.left is not None:
curNode.left = dfs(curNode.left, toDel, res)
if curNode.right is not None:
curNode.right = dfs(curNode.right, toDel, res)
if curNode.val in toDel:
if curNode.left is not None:
res.append(curNode.left)
if curNode.right is not None:
res.append(curNode.right)
return None
return curNode
toDel = set()
for td in to_delete:
toDel.add(td)
res = []
dummy = TreeNode(-1, root, None)
toDel.add(-1)
dfs(dummy, toDel, res)
return res
|
3c6e10b1105d65dac324d5ca57ce231fa85dfdd9 | Iso-luo/python-assignment | /practice/Lab4/Task2.py | 2,253 | 4.03125 | 4 | # -*- coding: utf-8 -*-
# !/usr/bin/env python
# @Time: 2020-05-12 9:35 a.m.
"""
Task 2
"""
"""
A. count the total number of words in the book,
and the number of times each word is used.
"""
import string
# 获取文本words列表
def get_words_list():
with open("/Users/a123/Desktop/paragraph.txt", "r") as f1:
f2 = f1.read() # 这里如果是.deadline() 则已经是一个列表,for循环需要主要列表的位
for i in f2:
if i in string.whitespace + string.punctuation:
f2 = f2.replace(i, ",") # 替换后,会出现 ',,'
f2 = f2.split(',') # split 以','分割,切成列表,返回列表
for i in f2:
if i in string.whitespace: # 因为有的位之前只有一个',',split后为空值
f2.remove(i)
return f2
# 一共多少字
def count_words(words_list):
words_len = len(words_list)
return words_len
# 给字典添值:如果字典中有该字,则value+1,否则添加k=word,v=1
def add_value(dic, word):
if word in dic:
dic[word] = dic.get(word) + 1
else:
dic[word] = 1
return dic
# 生成{word频率}字典
def words_frequency(words_list):
dic = {}
count = 0
for i in words_list:
# print(i)
add_value(dic, i)
return dic
"""
B. print the 20 most frequently-used words in the book.
"""
# 给字典的值value排序
def dic_sort(dic):
lis_v = []
lis_k = []
for k, v in dic.items():
lis_v.append(v)
lis_v.sort(reverse=True)
n = 0
for v in lis_v:
for k1, v1 in dic.items():
if v == v1:
lis_k.append(k1)
return lis_k
def first_20_words(lis):
words_l = []
if len(lis) < 20:
return "plz give a list longer than 20"
else:
for i in range(20):
words_l.append(lis[i])
return words_l
# l = get_words_list()
# dic1 = words_frequency(l)
# lis1 = dic_sort(dic1)
# print(first_20_words(lis1))
"""
C. Print the number of different words
used in the book
"""
# 打印所有的key
def get_keys(dic):
return dic.keys() # 一步到位
# for item in dic:
# print(item)
lis = get_words_list()
dic1 = words_frequency(lis)
print(get_keys(dic1))
|
bcbc8a755eb3cb4a7347c5d990420a26ef59a5c0 | teoranss/Projects | /modul3/modul3.py | 3,003 | 4.125 | 4 | #is statement
def return_true():
return ""
def return_false():
return ""
if return_true():
print('True')
if return_false():
print('False')
else:
print('else exec')
if return_false():
pass
elif return_true():
print('elif exec')
else:
print('else exec')
# if assignment operator
var1 = 'a' if 3<1 else 'b'
print(var1)
print('****************E1***************')
#Exercitiu Tema:
# def FuncTem():
# numar = int(input("Numar: "))
# if numar <3:
# print('Too small')
# elif numar==3:
# print('Just right')
# else:
# print("Too big")
# FuncTem()
print('***************L********************')
#loopy loops
# tuple = (1,2,3)
# iterabil = tuple.__iter__()
# print(iterabil.__next__())
# print(next(iterabil))
# print(next(iterabil))
# #print(next(iterabil))
# print(iterabil)
#
# for var in tuple:
# print(var)
# if var == 2:
# break
# else:
# print('end of for')
#EX2
print("*******************E2****************")
def StrFunc():
var = input("Give me a string:")
for x in var:
if x == 'a':
print("The string has A's")
break
else:
print("No A's, sorry")
break
# StrFunc()
print("*******************W****************")
#While
# while True:
# print('i am lost')
# break
#
# counter = 0
# while counter <5:
# print('i am lost')
# if counter == 5:
# break
# counter += 1
#
# else:
# print("Nu merge, something fucky")
print('**********************E3****************')
def a_in_str():
prop = input("String:")
for x in prop:
if x == 'a':
print("The str has A's")
return False
else:
return True
def astr():
while a_in_str():
pass
# astr()
print("**********************E4*********************")
#instance
# print(isinstance('a', str))
# tuple1= (1, 'a', ('b', 1+1j))
# def find_complex(tuple1):
# for var in tuple1:
# print('am un numar: ', var)
# if isinstance(var, complex):
# return var
# if isinstance(var, tuple):
# for var1 in var:
# if isinstance(var1, complex):
# print(var1)
# return var1
# else:
# return False
# find_complex(tuple1)
tuple1= (1, 'a', ('b', 1+1j))
def find_complex(tuple1):
for var in tuple1:
print('am un numar: ', var)
if isinstance(var, complex):
return var
if isinstance(var, tuple):
result = find_complex(var)
if result is not False:
return result
else:
return False
# print(find_complex(tuple1))
print('***************************E5**********************')
tuple2= (((True,),),)
def print_bool(tuple2):
for var in tuple2:
print('am un obiect: ', var)
if isinstance(var, tuple):
print_bool(var)
print_bool(tuple2) |
209f2e02040d29971821a1187917e71f43a1feff | AlecLjpg/PythonSetlist1 | /Setlist1/Q6.py | 248 | 3.75 | 4 | x = input("Enter a string to be maniuplated: ")
y = list(x)
i = 0
while i <len(y):
print (y[i])
i += 1
print("Sliced string: " + x[0:len(x):2])
print(x*100)
z = input("Enter a second string to be concatenated: ")
print(x+" "+z)
|
67cc67ed7f25b4423d653b9cd6ca1371f29df029 | spdjuanse2/curso | /curso python/sintaxis/Herencia.py | 1,258 | 3.71875 | 4 | class veiculos():
def __init__(self,Modelo,marca):
self.marca=marca
self.Modelo=Modelo
self.arrancar=False
self.frenar=False
self.acelerar=False
def enciende(self):
self.arrancar=True
def acelera(self):
self.arrancar=True
def freno(self):
self.frenar=True
def estado(self):
print("Marca: ", self.marca, "\nModelo: ", self.Modelo, "\nAcelerar: ", self.acelerar, "\nFrenar: ", self.frenar, "\nArrancar", self.arrancar)
class Moto(veiculos):
hcaballito=""
def caballito(self):
self.hcaballito="Estoy haciendo el caballito"
#si traemos una accion de la calse padre a la clase hijo y la sbre escribivimos invalida la clase padre y muestra la propia claro siempre y cuando se llama a la accion de la clase hijo y no padre
def estado(self):
print("Marca: ", self.marca, "\nModelo: ", self.Modelo, "\nAcelerar: ", self.acelerar, "\nFrenar: ", self.frenar, "\nArrancar", self.arrancar, "\n", self.hcaballito)
miMOTO=Moto("Honda","CTR34")
caba=str(input("deseas hacer el caballito? "))
caba=caba.lower()
if caba=="si":
miMOTO.caballito()
else:
print("")
miMOTO.estado() |
af36cbc8610864d2cb89ff98d1b73e2e16dcdc06 | chaudhary19/SDE-Interview-Problems | /G_SetMatZero.py | 874 | 3.796875 | 4 | class Solution(object):
def setZeroes(self, matrix):
col0 = 1
row, col = len(matrix), len(matrix[0])
for i in range(row):
if matrix[i][0] == 0: col0 = 0
for j in range(1, col):
if matrix[i][j] == 0:
matrix[i][0] = 0
matrix[0][j] = 0
for i in range(row - 1, -1, -1):
for j in range(col-1, 0, -1):
if matrix[0][j] == 0 or matrix[i][0] == 0:
matrix[i][j] = 0
if col0 == 0:
matrix[i][0] = 0
"""
Things to remember:
1) traverse the whole matrix, whenever got 0, put zero at the starting of row and column.
2) put mat[i][j] = 0, if mat[i][0] = 0 or mat[0][j] = 0
3) take care of column1 because it can collide with row1 values
"""
|
df968808d75e531a215675949ffbee6b4df422f8 | StanLong/Python | /01基础/02函数/闭包和迭代器.py | 1,468 | 3.734375 | 4 | # 闭包就是内层函数对外层函数(非全局)的变量的引用叫闭包。变量写在全局使不安全的,所以使用闭包,防止其他程序改变变量
# 闭包可以让一个局部变量常驻内存
# def func():
# name="沈万三"
# def inner():
# print(name) # 在内层函数调用了外层函数的变量(name),这个就叫闭包
# # print(inner.__closure__) 打印结果不为空说明inner是个闭包
# return inner
# ret = func()
# ret()
# 迭代器:节省内存,惰性机制,不能反复只能向下执行
# 可迭代对象 str, list, tuple, set, f(文件句柄) dict
# 以上数据类型中都有一个函数 __iter__()
# dir() 可以查看一个对象或者数据类型中包含了哪些东西
lst = ['沈万三', '刘伯温', '朱元璋']
#print(dir(lst))
#print('__iter__' in dir(lst)) # True
# it = lst.__iter__()
# print(it.__next__()) # 使用 __next__ 从迭代器里往外拿元素
# # 沈万三
# print(it.__next__()) # 使用 __next__ 从迭代器里往外拿元素
# # 刘伯温
# print(it.__next__()) # 使用 __next__ 从迭代器里往外拿元素
# print(it.__next__()) # 使用 __next__ 从迭代器里往外拿元素 # 迭代到最后一个元素在继续迭代的话就报错了 StopIteration
from collections.abc import Iterable
from collections.abc import Iterator
print(isinstance(lst, Iterable)) # True 可迭代的
print(isinstance(lst, Iterator)) # False # 不是迭代器 |
9bc5ca6f603d6109173ee6af95307b7b9b40c784 | salmaShahid/PythonCourse | /lec4ExerciseQ4-Q7.py | 2,438 | 4.125 | 4 | #Q4-Ask the user to enter a list containing numbers between 1 and 12. Then replace all of the
# entries in the list that are greater than 10 with 10.
lis = []
for i in range(0,12):
z = int(input("enter num "))
lis.append(z)
#list comprehension method
p = 10
if p >10:
pass
else:
w = [10 if x>10 else x for x in lis]
print("Final list: ",w)
#Q5-Ask the user to enter a list of strings. Create a new list that consists of those strings with
#their first characters removed.
#
list = []
userN = input("enter your name: ")
userC = input("enter your class: ")
userU = input("enter your University name: ")
list.append(userN)
list.append(userC)
list.append(userU)
print("First list: ",list)
list2 =[]
for i in list:
s = i[1:]
list2.append(s)
print("Second List: ",list2)
#Q6- a program that takes any two lists L and M of the same size and adds their elements
#together to form a new list N whose elements are sums of the corresponding elements in L
# and M. For instance, if L = [3,1,4] and M = [1,5,9], then N should equal [4,6,13].
L = []
user1 = int(input("enter num1: "))
user2 = int(input("enter num2: "))
user3 = int(input("enter num3: "))
L.append(user1)
L.append(user2)
L.append(user3)
print("First list: ",str(L))
M = []
user1 = int(input("enter num1: "))
user2 = int(input("enter num2: "))
user3 = int(input("enter num3: "))
M.append(user1)
M.append(user2)
M.append(user3)
print("Second list: ",str(M))
N = []
for j in range(3):
N.append(L[j] + M[j])
print("\nThe total Sum of Two Lists = ", N)
#Q7- . When playing games where you have to roll two dice, it is nice to know the odds of each
# roll. For instance, the odds of rolling a 12 are about 3%, and the odds of rolling a 7 are about
# 17%. You can compute these mathematically, but if you don’t know the math, you can write
# a program to do it. To do this, your program should simulate rolling two dice about 10,000
# times and compute and print out the percentage of rolls that come out to be 2, 3, 4, . . , 12.
import random
count = [0, 0, 0, 0, 0, 0] #make siple zero list for count purpose
for i in range(10000): #roll dice 10000 time
count[random.randint(0, 5)] += 1 #it will generate random num and place it in count list
for i in range(6):#get first 6 values result
print("Value %d happened %d times" % (i + 1, count[i])) #print those values |
31b11d92f79b639dccbf4992b7fb09d93351080d | CristofherAndres/Codigos_Python | /Clase 14/funcion1.py | 363 | 3.765625 | 4 | #función para calcular el area de un triangulo
# Def <- Indica que es una función
def AreaTriangulo(base, altura):
area = (base*altura)/2
return area
##########################################
baseEntrada = int(input("Ingresa la base: "))
alturaEntrada = int(input("Ingresa la altura: "))
area = AreaTriangulo(baseEntrada,alturaEntrada)
print(area) |
1f335d241b2a1f77bd24b92ff38f0877d4aee130 | JohnHaan/cloudtechpython | /20170327/DONE/sjhan/deduplicate.py | 1,016 | 3.84375 | 4 | # -*- coding:utf-8 -*-
def dedupe(targets):
resList = []
for target in targets:
if target not in resList:
resList.append(target)
return resList
def dedupe_dict(targets):
resList = []
for target in targets:
same = False
if len(resList) == 0:
resList.append(target)
for resDict in resList:
if target.get('x') == resDict.get('x') and target.get('y') == resDict.get('y'):
same = True
if not same:
resList.append(target)
return resList
def main(targets):
element = targets[0]
if isinstance(element, str) or isinstance(element, int):
return dedup(targets)
if isinstance(element, dict):
return dedupe_dict(targets)
if __name__ == '__main__':
a = [1,2,2,4,5,5,9]
b = ['apple', 'banana', 'kiwi', 'banana', 'melon', 'apple']
c = [{'x': 2, 'y': 3}, {'x': 1, 'y': 4}, {'x': 2, 'y': 3}, {'x': 2, 'y': 3}, {'x': 10, 'y': 15}]
res = main(c)
print(res) |
2219e82af03b455217ee688fb56672b3279c1f89 | lordjuacs/ICC-Trabajos | /Ciclo 1/discretas/ej1.py | 443 | 3.9375 | 4 | import time
n = int(input())
suma = 0
start_for = time.time()
for i in range(1, n + 1):
suma += ((3*i - 2)*(3 * i + 1))**-1
end_for = time.time()
diferencia_for = end_for - start_for
print("suma con ecuacion: ", suma)
print("tiempo del for:", diferencia_for)
start_ecu = time.time()
efe = n / (3 *n +1)
end_ecu = time.time()
diferencia_ecu = end_ecu - start_ecu
print("suma n al cuadrado:", efe)
print("tiempo de la ecu:", diferencia_ecu)
|
65befcf71f714eb7406e3506813f4390162a403c | Fan-Wang-nl/ML_Course | /1_Feature_Engeneering/TextFeatureExtract.py | 2,133 | 3.53125 | 4 | # coding=utf-8
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
def demo_CountVec():
# 文本文档列表
text = ["The quick brown fox jumped over the lazy dog."]
# 构造变换函数
vectorizer = CountVectorizer()
# vector = vectorizer.fit_transform(text) inlcudes fit and transform operations
# 词条化以及建立词汇表
vectorizer.fit(text)
# 总结,通过词汇表来查看到底是什么被词条化了
print("the vocabulary of the text:")
print(vectorizer.vocabulary_)
# 编码文档
vector = vectorizer.transform(text)#vectorize the data
# 总结编码文档, 可以看到,词汇表中有 8 个单词,于是编码向量的长度为 8。
print("vector shape:")
print(vector.shape)
print("vector type:")
print(type(vector))
print(vector)
print(vector.toarray())
def demo_TfidfVec():
# 文本文档列表
text = ["The quick brown fox jumped over the lazy dog.",
"The dog.",
"The fox"]
# 创建变换函数
vectorizer = TfidfVectorizer()
# 词条化以及创建词汇表
vectorizer.fit(text)
# 总结
print("the vocabulary of the text:")
print(vectorizer.vocabulary_)
print("Inverse document frequency:")
print(vectorizer.idf_)
# 编码文档
print("----------------------------tfidf for data[0]-----------------------------")
vector = vectorizer.transform([text[0]])
print(vector.shape)
print(vector.toarray())
print("----------------------------tfidf for data[1]-----------------------------")
vector = vectorizer.transform([text[1]])
print(vector.shape)
print(vector.toarray())
print("----------------------------tfidf for data[2]-----------------------------")
vector = vectorizer.transform([text[2]])
print(vector.shape)
print(vector.toarray())
if(__name__ == "__main__"):
# 1 count vector for text feature extraction, Bag-of-words model
demo_CountVec()
# 2 term frequency vector for text feature extraction
demo_TfidfVec()
|
a806637c6209cab267749e2eba86a978dcea174d | nik24g/Python | /main.py | 808 | 4.53125 | 5 | def add(x, y):
"""This function is use to add two numbers"""
return f"The sum of these numbers is: {x +y}"
def subtract(x, y):
"""This function is use to subtract two numbers"""
return f"The subtraction of these numbers is: {x -y}"
def multiply(x, y):
"""This function is use to multiply two numbers"""
return f"The multiply of these numbers is: {x *y}"
def divide(x, y):
"""This function is use to divide two numbers"""
return f"The divide of these numbers is: {x +y}"
def power(x, y):
"""This function is use to calculate exponent"""
return f"The value of {y} exponent of {x} is: {x**y}"
if __name__ == "__main__":
print("Nitin")
print(add(2, 6))
print(subtract(9, 8))
print(multiply(6, 7))
print(divide(16, 5))
print(power(2, 3))
|
ad3da83207b21957251129245a09693057588d5b | Abiseban147/OpenCV_Sample_Codes | /14_image_thresholding.py | 1,263 | 3.75 | 4 | import cv2
import numpy as np
import argparse
ap = argparse.ArgumentParser()
ap.add_argument('-i', required = True, help= 'Path for the image')
args = vars(ap.parse_args())
image = cv2.imread(args['i'])
"""
image thresholding is a task that convert the values of pixels
-less than the given value to 0
-greater than the given value to 255
"""
def image_preprocessing(image):
"""
this function will take an image as input and convert it to grayscale and apply Gaussian Blurring
it helps to remove high frequecy edges in the image, which will give smooth thresholding
"""
return cv2.GaussianBlur(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY), (5,5), 0)
processed = image_preprocessing(image)
(T, thresh) = cv2.threshold(processed, 155, 255, cv2.THRESH_BINARY)
"""
T - the threshold value we given 155
1st argument the image
2nd argument the threshold value 155
3rd argument the maximum value that has to be assigned to the pixels greater than threshold value
4th argument the conversion cv2.THRESH_BINARY or cv2.THRESH_BINARY_INV
"""
(T, thresh_inv) = cv2.threshold(processed, 155, 255, cv2.THRESH_BINARY_INV)
cv2.imshow('Orginal Image', image)
cv2.imshow('Thresholded Image', thresh)
cv2.imshow('Inversly Thresholded Image', thresh_inv)
cv2.waitKey(0) |
227241fbbac65bb52a95a992165e47eae869c833 | pieterdavid/adventofcode2020 | /day23.py | 5,323 | 3.9375 | 4 | # ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.7.1
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # Advent of code 2020: day 23
#
# Problem [here](https://adventofcode.com/2020/day/23)
# ## Part 1
# +
def crabCupGame(cups, nRounds, debug=False):
start = 0
highest = max(cups)
lowest = min(cups)
for i in range(nRounds):
if debug:
print(f"-- move {i+1:d} --")
print(f"cups: {' '.join(str(v) for v in cups[:start])} ({cups[start]:d}) {' '.join(str(v) for v in cups[start+1:])}")
curVal = cups[start]
crab = []
for j in range(1,4): # crab takes away
pos = start+1
if pos >= len(cups):
pos -= len(cups) # could be modulo
start -= 1 # will remove one before
crab.append(cups.pop(pos))
if debug:
print(f"Pick up: {' '.join(str(v) for v in crab)}")
assert curVal == cups[start] # check: did start follow?
destVal = (curVal-1)
if destVal < lowest:
destVal = highest
while destVal in crab:
destVal -= 1
if destVal < lowest:
destVal = highest
if debug:
print(f"Destination: {destVal}")
destPos = cups.index(destVal)+1
cups[destPos:destPos] = crab
if destPos <= start:
start += 3 # inserted before
assert curVal == cups[start] # check: did start follow?
start = (start + 1) % len(cups) # move on for the next round
if debug:
print()
if ((i+1) % 100) == 0:
print(f"Done round {i+1:d}")
if debug:
print("-- final --")
print(f"cups: ({cups[start]:d}) {' '.join(str(v) for v in cups[start+1:]+cups[:start])}")
return cups
ex10_cups = crabCupGame([int(ch) for ch in "389125467"], 10, debug=True)
ex10_i1 = ex10_cups.index(1)
print("After 10: ", "".join(str(v) for v in ex10_cups[ex10_i1+1:]+ex10_cups[:ex10_i1]))
ex100_cups = crabCupGame([int(ch) for ch in "389125467"], 100, debug=False)
ex100_i1 = ex100_cups.index(1)
print("After 100: ", "".join(str(v) for v in ex100_cups[ex100_i1+1:]+ex100_cups[:ex100_i1]))
# -
p1_cups = crabCupGame([int(ch) for ch in "394618527"], 100, debug=False)
p1_i1 = p1_cups.index(1)
print("After 100: ", "".join(str(v) for v in p1_cups[p1_i1+1:]+p1_cups[:p1_i1]))
# ## Part 2
# +
import numpy as np
def crabCupGame2(firstNums, nRounds, totalLen=None, debug=False):
if totalLen is None:
totalLen = len(firstNums)
iNext = np.zeros((totalLen,), dtype=np.int)
for i,n in zip(firstNums[:-1], firstNums[1:]):
iNext[i-1] = n-1
if totalLen != len(firstNums):
iNext[firstNums[-1]-1] = len(firstNums)
for i in range(len(firstNums), iNext.shape[0]-1):
iNext[i] = i+1
iNext[-1] = firstNums[0]-1
else:
iNext[firstNums[-1]-1] = firstNums[0]-1
if debug:
print(iNext)
iStart = firstNums[0]-1
for i in range(nRounds):
if debug:
print(f"-- move {i+1:d} --")
cupsFromStart = []
idx = iNext[iStart]
while idx != iStart:
cupsFromStart.append(idx+1)
idx = iNext[idx]
print(f"cups: ({iStart+1:d}) {' '.join(str(v) for v in cupsFromStart)}")
iSlB = iNext[iStart]
iSlLast = iNext[iNext[iSlB]]
iSlAfter = iNext[iSlLast]
iNext[iStart] = iSlAfter
iCrab = [ iSlB, iNext[iSlB], iSlLast ] # values -1
if debug:
print(f"Pick up: {iCrab[0]+1:d} {iCrab[1]+1:d} {iCrab[2]+1:d}")
iDest = iStart-1
if iDest < 0:
iDest = totalLen-1
while iDest in iCrab:
iDest -= 1
if iDest < 0:
iDest = totalLen-1
if debug:
print(f"Destination: {iDest+1}")
iNext[iSlLast] = iNext[iDest]
iNext[iDest] = iSlB
iStart = iSlAfter
if debug:
cupsFromStart = []
idx = iNext[iStart]
while idx != iStart:
cupsFromStart.append(idx+1)
idx = iNext[idx]
print("-- final --")
print(f"cups: ({iStart+1:d}) {' '.join(str(v) for v in cupsFromStart)}")
if totalLen == len(firstNums):
cupsFrom1 = []
idx = iNext[0]
while idx != 0:
cupsFrom1.append(idx+1)
idx = iNext[idx]
return cupsFrom1
else:
return iNext[0]+1, iNext[iNext[0]]+1
crabCupGame2([int(ch) for ch in "389125467"], 0)
crabCupGame2([int(ch) for ch in "389125467"], 0, totalLen=12)
# -
ex10_cups = crabCupGame2([int(ch) for ch in "389125467"], 10, debug=True)
print("After 10: ", "".join(str(v) for v in ex10_cups))
ex100_cups = crabCupGame2([int(ch) for ch in "389125467"], 100, debug=False)
print("After 100: ", "".join(str(v) for v in ex100_cups))
ex1M_cups = crabCupGame2([int(ch) for ch in "389125467"], 10000000, totalLen=1000000, debug=False)
print(ex1M_cups, ex1M_cups[0]*ex1M_cups[1])
p1M_cups = crabCupGame2([int(ch) for ch in "394618527"], 10000000, totalLen=1000000, debug=False)
print(p1M_cups, p1M_cups[0]*p1M_cups[1])
|
0a7b661a177032f2f1ab14d4e77c0589f1f446d8 | fmojica30/leetcode_practice | /test.py | 754 | 3.734375 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
temp = []
self.result = []
position = 1
self.helper(n, k, position, temp)
return self.result
def helper(self, n, k, position, temp):
if (len(temp) == k):
print(temp)
self.result.append(temp)
return
if (position > n):
return
temp.append(position)
self.helper(n, k, position + 1, temp)
temp.pop()
self.helper(n, k, position + 1, temp)
x = Solution()
print(x.combine(4,2))
|
30e47fb337341a4ba755952b7250ca99d0f5a65e | daniel-reich/ubiquitous-fiesta | /RoEn338P4xAf7mNNg_14.py | 298 | 3.53125 | 4 |
def shortest_path(lst):
pnts = []
for y, row in enumerate(lst):
for x, n in enumerate(row):
if n != '0':
pnts.append((int(n), x, y))
pnts.sort()
return sum(abs(x2-x1)+abs(y2-y1) for (n1,x1,y1), (n2,x2,y2) in
zip(pnts, pnts[1:]))
|
1d7202c139806aa1dbfd63df7f2d8b94624b6433 | WirachaLooknoo/workshop2 | /string/f-string.py | 142 | 3.78125 | 4 | name = "Looknoo"
age = 21
result = f" My name is {name}, and I am {age}"
print("result", result) # Output: "My name is Looknoo, and I am 20" |
2cd9247ebaa2249fe1794834d38f71f96a946c99 | Matheus872/Python | /Learning/teste.py | 75 | 3.59375 | 4 | resp = str(input('Digite uma letra: ')).strip().upper()[1]
print(f'{resp}') |
3e8f37b8df4bed2dc17ac5105e7de0b4031090bf | kyledavv/lpthw | /ex31_practice.py | 4,024 | 4.28125 | 4 | import random
#Basic explanation of the rules
print("Here is the sport of tennis explained in a game.")
print("""First, you spin a racquet to see who serves first.
The winner of the racquet spin gets to choose whether to serve or return,
or which side of the court they would like to start on.""")
print("Which type of racquet will you be spinning? The options are Wilson, Head, Babolat, Yonex, or Other.")
#list of possible serves/returns to hit for each point
return_options = ['crosscourt', 'down the line', 'to the middle']
serve_options_deuce = ['slice out wide', 'slice in body', 'flat down the T']
serve_options_ad = ['slice down the T', 'flat in body', 'flat out wide']
#first input to see which racquet brand gets chosen- then branches to wilson spin or up/down spin
racquet = input("Racquet Brand > ").lower()
#wilson spin if stmnt. from input above.
if racquet == "wilson":
#sets the input of m or w for a wilson racquet spin. .lower() normalizes it to lower case.
spin_wilson = input("M or W > ").lower()
#spin_option_wilson compares the input to m or w, then wilson_spin sets the random function for the spin toss
spin_option_wilson = ['m', 'w']
wilson_spin = random.choice(spin_option_wilson)
#if inside if: compares input of m or w to result of random spin. if win, sets choice to serve/receive. if lose, choice of side to go to
if spin_wilson == wilson_spin:
print("Congratulations, you won the toss. You get to choose whether to serve or receive.")
serve_receive = input("Serve or Receive > ").lower()
print(f"You chose to {serve_receive}. Here are the balls.")
print("Below is a list of the possible serves to hit.")
for serving_deuce in serve_options_deuce:
print(f"> {serving_deuce}")
serve_love_all = input("Which serve from above will you hit? ").lower()
print(f"You hit a {serve_love_all} serve.")
print("It was an ACE! You are winning 15-0.")
for serving_ad in serve_options_ad:
print(f"> {serving_ad}")
serve_fifteen_love = input("The score is 15-0. Which serve from above will you hit next?")
print(f"You hit a {serve_fifteen_love} serve.")
print(f"Your {serve_fifteen_love} serve did not get returned. You are winning 30-0!")
else:
print("You did not win the toss. Your opponent chose to serve first.\nWould you like to start play on the north or south side of the court?")
north_south = input("North or South > ").lower()
print(f"Please make your way to the {north_south} side of the court and prepare to return the serve.")
else:
spin = input("Up or Down > ").lower()
spin_option = ['up', 'down']
other_spin = random.choice(spin_option)
if spin == other_spin:
print("Congratulations, you won the toss. You get to choose whether to serve or receive.")
serve_receive = input("Serve or Receive > ").lower()
print(f"You chose to {serve_receive}. Here are the balls.")
print("Below is a list of the possible serves to hit.")
for serving_deuce in serve_options_deuce:
print(f"> {serving_deuce}")
serve_love_all = input("Which serve from above will you hit? ").lower()
print(f"You hit a {serve_love_all} serve.")
print("It was an ACE! You are winning 15-0.")
for serving_ad in serve_options_ad:
print(f"> {serving_ad}")
serve_fifteen_love = input("The score is 15-0. Which serve from above will you hit next?")
print(f"You hit a {serve_fifteen_love} serve.")
print(f"Your {serve_fifteen_love} serve did not get returned. You are winning 30-0!")
else:
print("You did not win the toss. Your opponent chose to serve first.\nWould you like to start play on the north or south side of the court?")
north_south = input("North or South > ").lower()
print(f"Please make your way to the {north_south} side of the court and prepare to return the serve.")
|
d1d5064157538280748b162be27037f851781c0d | debaratidas1994/Python-Lab | /4/2.py~ | 712 | 3.921875 | 4 | '''
Given an input file, do the following using regular expression and create
an output file.
a) Remove extra whitespaces between two words.
b) Insert a white space after the end of a sentence (after . or ? or !).
c) First letter of each sentence should be upper case
d) Remove consecutive duplicate words.
'''
f=open('inp.txt')
l=f.read()
import re
def fun1(m):
return m.group(1)
l=re.sub(r'(\s)+',fun1,l)
def fun2(m):
return m.group(1)+' '+m.group(2)
l=re.sub(r'([.?!])(\w)',fun2,l)
l=re.sub(r'(\b)(\w+)(\s\2)+',r'\1\2',l)
def fun3(m):
return m.group(1)+m.group(2)+m.group(3).upper()
l=re.sub(r'([.?!])(\s)(\w)',fun3,'. '+l)[2:]
f.close()
g=open('op.txt','w')
g.write(l)
|
fafbf66d42f700027bc5ba65da0ab4f5e4f34ff7 | codefire53/DDP1 | /UTS2016/UTS2016_5.py | 376 | 3.65625 | 4 | def string_match(str1,str2):
#Set counter ke 0
ans=0
#Looping dua lapis untuk mengecek substring str1 dengan str2
for i in range(len(str1)-1):
for j in range(len(str2)-1):
#Jika ada substring yang sama, counter bertambah
if(str1[i:i+2]==str2[j:j+2]):
ans+=1
#Mengembalikan nilai counter
return ans
#Driver program
print(string_match('xxcaaz','xxbaaz')) |
3d7c2f642268da88e38dbe5cbfb2baaaeb36529c | natiem/python-1 | /01-flow-control/loop_for.py | 1,130 | 3.53125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Przykład - pętla for na różne sposoby.
CC-BY-NC-ND 2020 Sławomir Marczyński
"""
# Generowanie tabeli pseudolosowych liczb z zakresu od 0 do 9. W każdym wierszu
# ma być 10 liczb, wierszy ma też być 10. Uwaga: parametr end=' ' powoduje że
# print nie wypisuje końca wiersza, ale znak odstępu.
from random import randint
for i in range(10):
for j in range(10):
print(randint(0, 9), end=' ')
print()
# Modyfikowanie "zmiennej kontrolnej" w pętli for nie zmienia liczby iteracji:
# choć i będzie większe niż 100, to i tak w następnej iteracji zostanie "zresetowane".
# Czyli instrukcje w pętli wykonają się 20 razy.
for i in range(10, 105, 5): # liczby 10, 15, 20, ..., 100
print(i, end=' ')
i = 200
print(i)
# Pętla for z break, continue oraz else
N = 50
for k in range(1, N):
if k < 10:
print('continue -> od razu wejście w kolejny cykl')
continue
if k > 100:
print('break -> "awaryjne" wyjście z pętli')
break
print(k)
else:
print('Normalne zakończenie pętli (nie było break)')
|
fca31d06337dd388d59f0be9043bcab57a34266a | christianwcweiss/Udacity-Datastructures-and-Algorithms | /Chapter 3/Exercise 7 - HTTPRouter using a Trie.py | 5,082 | 3.53125 | 4 |
class RouteTrieNode:
def __init__(self, path, handler):
self.path = path
self.handler = handler
self.sub_path = {}
class RouteTrie:
def __init__(self, root_path, root_handler):
self.root_node = RouteTrieNode(root_path, root_handler)
def insert(self, path_list, handler):
current_node = self.root_node
for i, path in enumerate(path_list):
if path in current_node.sub_path.keys():
current_node = current_node.sub_path[path]
if i == len(path_list) - 1:
old_handler = current_node.handler
current_node.handler = handler
print("Old handler *{0}* was overwritten by *{1}*".format(old_handler, handler))
else:
if i < len(path_list) - 1:
new_node = RouteTrieNode(path, None)
else:
new_node = RouteTrieNode(path, handler)
current_node.sub_path[path] = new_node
current_node = new_node
def find(self, path_list):
current_node = self.root_node
for path in path_list:
if path in current_node.sub_path.keys():
current_node = current_node.sub_path[path]
else:
return None
class Router:
def __init__(self, root_path, root_handler, not_found_handler):
self.route_trie = RouteTrie(root_path, root_handler)
self.not_found_handler = not_found_handler
def add_handler(self, path, handler):
path_list = self.split_path(path)
self.route_trie.insert(path_list, handler)
def lookup(self, path):
if self.route_trie.root_node.path == path:
return self.route_trie.root_node.handler
path = path.rstrip('/')
path_list = self.split_path(path)
current_node = self.route_trie.root_node
for path in path_list:
if path in current_node.sub_path.keys():
current_node = current_node.sub_path[path]
else:
return self.not_found_handler
return current_node.handler
def split_path(self, s):
return s.split('/')
router = Router("/", "root handler", "not found handler")
router.add_handler("/home/about", "about handler")
print(router.lookup("/"))
print(router.lookup("/home"))
print(router.lookup("/home/about"))
print(router.lookup("/home/about/"))
print(router.lookup("/home/about/me"))
print("\n\n")
#own test_cases
print("Test Case 1 - create new router")
tc_router = Router("/", "home handler", "error 404 handler")
temp_node = RouteTrieNode("/", None)
solution = temp_node.path
output = tc_router.route_trie.root_node.path
print("Output: {0}".format(output))
assert(output == solution)
print("TestCase 1 passed! - Given output {0}; Expected output {1}".format(output, solution))
print("---------------------------")
print("Test Case 2 - add handler")
tc_router.add_handler("/home/about/test", "test handler")
solution = "test handler"
output = tc_router.lookup("/home/about/test")
print("Output: {0}".format(output))
assert(output == solution)
print("TestCase 2 passed! - Given output {0}; Expected output {1}".format(output, solution))
print("---------------------------")
print("Test Case 3 - lookup with / on the end")
solution = "test handler"
output = tc_router.lookup("/home/about/test/")
print("Output: {0}".format(output))
assert(output == solution)
print("TestCase 3 passed! - Given output {0}; Expected output {1}".format(output, solution))
print("---------------------------")
print("Test Case 4 - overwrite handler")
solution = "overwrite handler"
tc_router.add_handler("/home/about/test", "overwrite handler")
output = tc_router.lookup("/home/about/test/")
print("Output: {0}".format(output))
assert(output == solution)
print("TestCase 4 passed! - Given output {0}; Expected output {1}".format(output, solution))
print("---------------------------")
print("Test Case 5 - add new handler")
solution = "new handler"
tc_router.add_handler("/home/about/new", "new handler")
output = tc_router.lookup("/home/about/new/")
print("Output: {0}".format(output))
assert(output == solution)
print("TestCase 5 passed! - Given output {0}; Expected output {1}".format(output, solution))
print("---------------------------")
print("Test Case 6 - lookup and return no handler")
solution = "error 404 handler"
output = tc_router.lookup("/home/about/this does not exist/")
print("Output: {0}".format(output))
assert(output == solution)
print("TestCase 6 passed! - Given output {0}; Expected output {1}".format(output, solution))
print("---------------------------")
print("Test Case 7 - lookup home handler")
solution = "home handler"
output = tc_router.lookup("/")
print("Output: {0}".format(output))
assert(output == solution)
print("TestCase 7 passed! - Given output {0}; Expected output {1}".format(output, solution))
print("---------------------------") |
136efc26c0d215234813382bcf0fdede83f955d0 | rajdipa/Sentiment-Analysis | /extras/deprecated_NB.py | 1,449 | 3.65625 | 4 | # naive bayes from https://opensourceforu.com/2016/12/analysing-sentiments-nltk/
import csv
import re
import nltk
#nltk.download('punkt')
from nltk.tokenize import word_tokenize
def readcsv():
with open('train.csv', newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter=',')
cnt = 0
useless_words = ['and', 'the', 'of', '']
for row in spamreader:
# skip first line of train file (names)
if cnt > 0:
# clean: remove punctuation
phrase = re.sub(r'[^\w\s]','',row[2])
label = row[3]
train.append((phrase, label))
cnt +=1
if cnt > 50: break
if __name__ == "__main__":
# Step 1 load in data
train = []
readcsv()
#print(train)
# Step 2 clean: convert to lowercase
# passage is a tuple in the train dictionary
dictionary = set(word.lower() for passage in train for word in word_tokenize(passage[0]))
#print(dictionary)
# Step 3
t = [({word: (word in word_tokenize(x[0])) for word in dictionary}, x[1]) for x in train]
print(t)
# Step 4 – the classifier is trained with sample data
classifier = nltk.NaiveBayesClassifier.train(t)
test_data = "that was terrible i hate it"
test_data_features = {word.lower(): (word in word_tokenize(test_data.lower())) for word in dictionary}
print (classifier.classify(test_data_features))
|
fa8c90288b9a841d2cb50b9863c1f04544dfde62 | shuxinzhang/nltk-learning | /exercises/Chapter 03/03-18.py | 421 | 3.75 | 4 | # -*- coding: utf-8 -*-
import matplotlib
matplotlib.use('TkAgg')
import nltk
'''
◑ Read in some text from a corpus, tokenize it, and print the list of
all wh-word types that occur. (wh-words in English
are used in questions, relative clauses and exclamations:
who, which, what, and so on.) Print
them in order. Are any words duplicated in this list, because of
the presence of case distinctions or punctuation?
''' |
8ee37497a745bc0ab88832315d43eccf47d14637 | mgracioli/conexaoSQLitePython | /usuario.py | 1,040 | 3.859375 | 4 | #cria um modelo de usuário
class Usuario(object):
#método construtor
def __init__(self, nome, telefone, email, cpf):
self.__nome = nome #o __ informa que essa variável é do tipo private. Em python não existe variável privada, então, isso é só uma convenção para dizer que essa variável deve ser usada como se fosse private
self.__telefone = telefone #o self deixa essa variável disponivel para uso dentro de todos os métodos dessa classe
self.__email = email
self.__cpf = cpf
@property
def nome(self):
return self.__nome.title() #.title() é para que o nome seja formatado com a primeira letra maiuscula. É um tratamento desse dado para que ele seja adicionado no banco de dados de forma correta, isso justifica o uso das @property
@property
def telefone(self):
return self.__telefone
@property
def email(self):
return self.__email.lower()
@property
def cpf(self):
return self.__cpf
|
b8b2eb89716b3c2b1b3e20b63080030b90b2e652 | KierstenPage/Intro-to-Programming-and-Problem-Solving | /Homework/hw1/kep394_hw1_q6.py | 594 | 3.640625 | 4 | print("Please enter your amount in the format of dollars and cents in two seperate lines:")
dollarValue = int(input())
centsValue = int(input())
dollarToCentsValue = int(dollarValue * 100)
totalCents = int(dollarToCentsValue + centsValue)
quarters = int(totalCents/25)
dimes = int((totalCents - (quarters*25))/10)
nickels = int((totalCents - (quarters*25) - (dimes*10))/5)
pennies = int(totalCents - (quarters*25) - (dimes*10) - (nickels*5))
print(dollarValue, "dollars and", centsValue, "cents are:")
print(quarters, "quarters,", dimes, "dimes,", nickels, "nickels and", pennies, "pennies")
|
27c67d3d438f5b0e6480774b987459b1a73ccff5 | zatzk/INF032A | /Atividade lista 9 python/q2.py | 312 | 3.90625 | 4 | nums = []
i=0
while i < 8:
nums.insert(i, input("Digite o numero: "))
i+=1
i=0
while i < len(nums):
x = nums[i]
y = 2
print("numero {}: {}".format(i, nums[i]))
for y in range (20):
if(int(x)) == 6*y:
print("multiplo de 6")
y+=1
i+=1
|
d416388f7f60370051933676ee6369ab7e9a93ef | huttonb/BBB | /languageMaker.py | 1,162 | 3.703125 | 4 | """ Language parser for the pseudo-language"""
class LanParser():
def __init__(self, spell):
sad = False
# The lexer works by giving it a set of code, it can use regex to determine whether or not it's a key-word
def lexer(self, lex):
keyword = True;
# if Keyword send it to the correct function
if keyword:
# Convert lex to the same name as the function
func_name = 'bb' + str(lex)
# calls the method, then returns
# Getattr attaches a method to func, returning it with () calls it,
# if it can't find the function name, it assigns lambda to it, which is error
func = getattr(self, func_name, lambda: "Keyword Error: Could not find keyword")
return func()
def bbwhile(self):
print("-While Detected-")
return
def bbfor(self, arg):
print("For detected")
return
def bbint(self, arg):
print("Int detected")
return
l = lanParser("howdy")
l.lexer("while")
# For custom variables a dictionary is used to store the string name to the actual variable that it creates for it.
|
f345ba23214923d21839b5c9477bfa8b000a8f52 | pololee/oj-leetcode | /companies/uber/692.top-freq-words.py | 1,113 | 3.765625 | 4 | import heapq
class Wrapper:
def __init__(self, freq, word):
self.freq = freq
self.word = word
def __lt__(self, other):
if self.freq == other.freq:
return self.word > other.word
else:
return self.freq < other.freq
class Solution:
def topKFrequent(self, words, k):
"""
:type words: List[str]
:type k: int
:rtype: List[str]
"""
table = dict()
for word in words:
table[word] = table.get(word, 0) + 1
heap = []
for word, freq in table.items():
heapq.heappush(heap, Wrapper(freq, word))
if len(heap) > k:
heapq.heappop(heap)
ans = []
while heap:
item = heapq.heappop(heap)
ans.append(item.word)
return ans[::-1]
def main():
sol = Solution()
print(sol.topKFrequent(["i", "love", "leetcode", "i", "love", "coding"],
3))
print(sol.topKFrequent(["aaa", "aa", "a"],
2))
if __name__ == '__main__':
main()
|
75c1394e4ab6d415953bdaafa720f89eed67282b | Rhylan2333/Python35_work | /精品试卷 - 06/P301-2.py | 816 | 3.703125 | 4 | # 问题2模板:
# P301-2.py
# 请在.....处填写多行表达式或语句
# 可以修改其他代码
def display():
fi = open("address.txt", 'r')
content = fi.read()
print(content)
fi.close()
menu = ["1. 显示所有信息", "2. 追加信息", "3. 删除信息"]
flag = True
while flag:
for element in menu:
print(element)
ch = '' # 为了使非int输入也能运行后续if语块
try:
ch = int(input("请输入数字1-3选择功能:")) # 再次对ch赋值
flag = False # 跳出循环
except:
flag = True # 继续循环
if ch not in {1,2,3}: # 这里的if与except处于同一层次
print("请重新输入")
flag = True
elif ch == 1:
display()
elif ch == 2:
pass
elif ch == 3:
pass
|
ef50244f76b08ec1f6b7a95621badb904ab8f609 | PrateekCoder/Introduction-to-Python-For-Data-Science | /06_Controlflow_and_pandas/Pandas/script05.py | 759 | 3.953125 | 4 | '''
loc (2)
100xp
loc also allows you to select both rows and columns from a DataFrame. To experiment, try out the following commands in the IPython Shell.
cars.loc['IN', 'cars_per_cap']
cars.loc[['IN', 'RU'], 'cars_per_cap']
cars.loc[['IN', 'RU'], ['cars_per_cap', 'country']]
Instructions
Print out the drives_right value of the row corresponding to Morocco (its row label is MOR)
Print out a sub-DataFrame, containing the observations for Russia and Morocco and the columns country and drives_right.
'''
# Import cars data
import pandas as pd
cars = pd.read_csv('cars.csv', index_col = 0)
# Print out drives_right value of Morocco
print(cars.loc["MOR", "drives_right"])
# Print sub-DataFrame
print(cars.loc[["RU", "MOR"], ["country", "drives_right"]])
|
9c705473225e354dff912c9952ebafb0da2d16e6 | techkuz/PythonDataStructures | /week7 - tuples/sort_by_keys.py | 139 | 3.734375 | 4 | #1
d = {'a' : 10, 'b' : 1, 'c' : 22}
print (d.items())
t = sorted(d.items())
print (t)
for k, v in sorted(d.items()):
print (k, v) |
50f22144414a2e145aaf64e1d396275f20b2a7b3 | Danis98/AdventOfCode2018 | /day11/part1.py | 545 | 3.59375 | 4 | serial = int(open("day11.input", "r").read().rstrip())
def get_val(x, y):
rackID = x + 10
power = rackID * y
power += serial
power *= rackID
power = (power/100)%10
power -= 5
return power
def get_square(x, y):
return sum([get_val(x+i, y+j) for i in range(3) for j in range(3)])
best = (0, 0)
bestval = 0
for x in range(298):
for y in range(298):
val = get_square(x, y)
if val > bestval:
bestval = val
best = (x, y)
print("%d,%d -> %d" % (best[0], best[1], bestval))
|
0e34da0cbdd4333ecde35450ee99c2b50b4b1374 | ArthurFSantos/CursoemVideoPython | /Exercicios/ex014.py | 137 | 4.03125 | 4 | c = float(input('Informe a temperatura em °C: '))
f = 9 * c / 5 + 32
print('A tempteratura de {}°C corresponte a {}°F!'.format(c, f))
|
60d6178b19bb3864c70eecf705cce860999f502e | mitja-mandic/grid-peeling | /razredi.py | 2,145 | 3.84375 | 4 | import math
class Tocka:
def __init__(self, x, y):
self.x = x
self.y = y
def kot_med_dvema(self, other):
"""Kot med dvema točkama v radianih"""
if self.x != other.x:
return math.atan((self.y - other.y) / (self.x - other.x))
else:
return math.pi/2
#če je vektorski produkt pozitiven je kot med vektorjema manjši od Pi
#če je negativen je manjši od pi
#če je 0 sta vektorja kolinearna
def vektorski_produkt(self, other):
"""Vektorski produkt, kjer je tretja komponenta obeh vektorjev enaka nič (smo v ravnini)"""
return self.x * other.y - self.y * other.x
def razlika(self, other):
"""Razlika dveh točk"""
return Tocka(self.x - other.x, self.y - other.y)
def razdalja(self, other):
"""Kvadrat klasične razdalje med točkama"""
return (self.x - other.x) ** 2 + (self.y - other.y) ** 2
def kot_atan(self, other):
return math.atan2(self.y-other.y,self.x-other.x)
def __str__(self):
return '(' + str(self.x) + ', ' + str(self.y) + ')'
def __repr__(self):
return 'T(' + str(self.x) + ', ' + str(self.y) + ')'
def smer_razlike(p,q,r):
return p.razlika(q).vektorski_produkt(r.razlika(q))
def enakomerna_mreza(m,n):
"""Vrne mxn mrežo z enakomernimi razmiki
"""
return [Tocka(i,j) for i in range(m) for j in range(n)]
def naredi_potencno(m, n):
"""Mreža mxn, kjer se razmiki povečujejo eksponentno z osnovo 2.
"""
return [Tocka(2**i,2**j) for i in range(m) for j in range(n)]
def kvazi_cantor_mreza(n):
"""Mreža po vzoru literature. Vsaka naslednja ovojnica je dolžine 3 ** i, argument je največja potenca 3.
(vsaka stranica je točno trikrat daljša od prejšnje, zato Cantorjeva).
Na vsaki stranici imamo na koncu 2n točk, vseh vozlišč je torej 4 n ** 2.
"""
sez = [0,3]
for i in range(1,n):
nasl_dol = sez[0] - 3 ** i
nasl_gor = sez[-1] + 3 ** i
sez.append(nasl_gor)
sez = [nasl_dol] + sez
return [Tocka(i,j) for i in sez for j in sez] |
520304a278f36679c025faf57fe87bf8b6e72fab | sarthakydv/COL759---Cryptography | /Assn1/Functions.py | 6,659 | 3.84375 | 4 | # Functions
# Part 1 - Kasiski Method
def divisors(n): # Finds all divisors, except 1
divs = []
for i in range(2, n + 1):
if n % i == 0:
divs.append(i)
return divs
# Finds all repeating substrings, poplulates a list of all divisors of distances
# and returns sorted list of number of occurences in decreasing order
def countOcc(str):
divs = []
i = 0
while i < len(str) - 3:
length = 3
found = False
# subStr = s[i:i + length]
# if (len(subStr) < 3):
# break
j = i + 3
while j < len(str):
if str[i : i + length] == str[j : j + length]:
while str[i : i + length + 1] == str[j : j + length + 1]:
length = length + 1
# subStr = s[i:i + length]
distance = j - i
found = True
divs.extend(divisors(distance))
# print("%s\ti:%s\tj:%s\tdiff:%s\t\tDivisors:%s" %
# (subStr, i, j, diff, divisors(diff)))
# j = j + length
# else:
j = j + 1
if found:
break
i = i + 1
if found:
i = i + length - 1
# print(i)
# print(count)
d = {}
for i in divs:
if i in d:
d[i] = d[i] + 1
else:
d[i] = 1
final = sorted(d.items(), key=lambda x: x[1], reverse=True)
# print(final)
return final
# Part 2 - Index of Coincidence
# Choosing Threshold for IoC
THRESHOLD = 0.058
# Seperates ciphertext into n Caesar ciphers
def makeCaesarCipher(str, keySize):
l = []
for i in range(keySize):
tmp = str[i::keySize]
l.append(tmp)
# print(l)
return l
# Calculates IoC for given Caesar cipher
def IoCCalc(cipher):
if len(cipher) < 2:
return 0
dict = {}
for c in cipher:
if c in dict:
dict[c] += 1
else:
dict[c] = 1
val = 0
for c in dict.values():
val = val + c * (c - 1)
val = val / (len(cipher) * (len(cipher) - 1))
return val
# Finds the first key length from Kasiski Method that satisfies IoC criteria
def findKeyLength(Str, possibleKeyLengths):
for keyLength in possibleKeyLengths:
l = makeCaesarCipher(Str, keyLength)
IoC = 0
for j in l:
IoC = IoC + IoCCalc(j)
IoC = IoC / len(l)
# print(check)
if IoC > THRESHOLD:
return keyLength
# print('here')
# def findKeyLength():
# d = {}
# for i in res1:
# l = makeStrings(s, i)
# check = 0
# for j in l:
# check = check + IoCCalc(j)
# check = check / len(l)
# d[i] = check
# result = sorted(d.items(), key=lambda x: x[1], reverse=True)
# print(result)
# It is possible that a multiple of keyLength is found during greedy search in
# findKeyLength(), we find the smallest possible length by taking divisors here
def findOptimalKeyLength(Str, keyLength):
divs = divisors(keyLength)
divs = divs[:-1] # removing the original keyLength
for newKeyLength in divs:
l = makeCaesarCipher(Str, newKeyLength)
check = 0
for j in l:
check = check + IoCCalc(j)
check = check / len(l)
# print(check)
if check > THRESHOLD:
return newKeyLength
return keyLength
# Part 3 - Mutual Index of Coincidence
# Distribution of frequencies of the English alphabet
english_frequences = [
0.08167,
0.01492,
0.02782,
0.04253,
0.12702,
0.02228,
0.02015,
0.06094,
0.06966,
0.00153,
0.00772,
0.04025,
0.02406,
0.06749,
0.07507,
0.01929,
0.00095,
0.05987,
0.06327,
0.09056,
0.02758,
0.00978,
0.02360,
0.00150,
0.01974,
0.00074,
]
# tmp = sum(english_frequences)
# english_frequences = [i * 10000 / tmp for i in english_frequences]
# del tmp
# print(sum(english_frequences))
# print((english_frequences))
def shiftCipher(shift):
newFreq = []
for i in range(26):
newFreq.append(english_frequences[(i - shift + 26) % 26])
return newFreq
def MiCCalc(freq, shift, n):
val = 0
newFreq = shiftCipher(shift)
for i in range(26):
val += freq[i] * newFreq[i]
val /= n
# val = abs(val - 0.065)
# print(val * 100)
# print(val)
return val
def findNext(cipher):
dict = {}
for c in cipher:
if c in dict:
dict[c] += 1
else:
dict[c] = 1
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for c in ALPHABET:
if c not in dict:
dict[c] = 0
freq = sorted(dict.items(), key=lambda x: x[0])
# print("this")
# print(freq)
freq = [i[1] for i in freq]
# print(freq)
shift = 0
val = 0
d1 = {}
while shift < 26:
val = MiCCalc(freq, shift, len(cipher))
d1[shift] = val
shift = shift + 1
# print(len(d1))
d1 = sorted(d1.items(), key=lambda x: x[1], reverse=True)
# print(d1)
return chr(ord("A") + d1[0][0])
def findKey(Str, keyLength):
key = ""
for cipher in makeCaesarCipher(Str, keyLength):
key += findNext(cipher)
# print()
return key
def findNextK(cipher, K):
dict = {}
for c in cipher:
if c in dict:
dict[c] += 1
else:
dict[c] = 1
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for c in ALPHABET:
if c not in dict:
dict[c] = 0
freq = sorted(dict.items(), key=lambda x: x[0])
# print("this")
# print(freq)
freq = [i[1] for i in freq]
# print(freq)
shift = 0
val = 0
d1 = {}
while shift < 26:
val = MiCCalc(freq, shift, len(cipher))
d1[shift] = val
shift = shift + 1
# print(len(d1))
d1 = sorted(d1.items(), key=lambda x: x[1], reverse=True)
out = []
for i in range(K):
out.append(chr(ord("A") + d1[i][0]))
return out
def topKEach(Str, keyLength, K):
key = ""
for cipher in makeCaesarCipher(Str, keyLength):
print(findNextK(cipher, K))
return key
def decipher(Str, key):
shift = []
for i in key:
shift.append(ord(i) - ord("A"))
lower = ord("A")
# print(lower)
# print(shift)
text = ""
for i in range(0, len(Str), len(key)):
for j in range(len(key)):
if i + j < len(Str):
ch = ord(Str[i + j]) - shift[j]
if ch < lower:
ch = ch + 26
text = text + chr(ch)
return text |
79258cf3229385b0c03dd8c4a4ef25a51764bd4a | C-CHS-TC1028-021-2113/FUNCIONES_PREDEFINAS | /assignments/17RazonAurea/src/exercise.py | 281 | 3.75 | 4 | # Coloca aquí la librería de matemáticas
def main():
#escribe tu código abajo de esta línea
#phi = () / 2
#f = ("Número: ")
#k = int(("Decimales a mostrar: "))
#resultado = round( , )
#print("Razón áurea: ")
if __name__ == '__main__':
main()
|
6f77f5a73db723c1377eb8278e48ea23945eae03 | nthakkar/logit_regression | /nigeria/code/load_data.py | 2,489 | 3.6875 | 4 | '''Functions and tools for loading and preprocessing the data.
The functions take the data from the .csv file and manipulate it as a pandas dataframe and as
a numpy array.'''
from __future__ import print_function
import numpy as np
import pandas as pd
def ReadHeader(fname='_data/headers.csv'):
'''Read the header file, output is a dictionary which maps column ID to content description.'''
header = {}
## Loop through the file
skip = set([0,1])
header_file = open(fname,'r')
for i,line in enumerate(header_file):
## Skip lines in set skip
if i in skip:
continue
## Otherwise, parse the line
l = line.split(',')
## And store it in the dictionary
header[l[0].strip().lower()] = l[1]
header_file.close()
## two entries are missing from the header.csv file.
## Here, I put in filler for those two to avoid issues later.
header['var1'] = 'var1'
header['caseid'] = 'case id'
return header
def ReadData(fname='_data/data.csv'):
'''Function to read the data. Output is a pandas dataframe'''
## Start by constructing the headers for the pandas data frame
## Open the file, read the first line, strip the \n and \r, and parse.
data = open(fname,'r')
columns = data.readline().rstrip().lower().split(',')
data.close()
## Now use pandas to handle the rest
df = pd.read_csv(fname,skiprows=0)
df.columns = columns
return df
def CleanData(df):
'''Perform some cleaning operations to make the data easier to work with.'''
## Compress the "i don't know" and "missing" categories
df['h8'].replace([8.,9.],np.nan,inplace=True)
df['h0'].replace([8.,9.],np.nan,inplace=True)
df['h9'].replace([8.,9.],np.nan,inplace=True)
## Make all the known ones equal
df['h8'].replace([1.,2.,3.],1.,inplace=True)
df['h0'].replace([1.,2.,3.],1.,inplace=True)
df['h9'].replace([1.,2.,3.],1.,inplace=True)
def LoadData(dataset='_data/data.csv',header_file='_data/headers.csv',resample=False):
'''Wrapper for the functions above.
The resample option uses the statistical weights in column v005 and samples (with replacement) a
fraction of the data provided by the user.'''
header = ReadHeader(header_file)
df = ReadData(dataset)
## Resample using the weights column
if resample:
df = df.sample(frac=resample,replace=True,weights=df['v005'])
## Simplify the vaccine columns of interest.
CleanData(df)
return header, df
if __name__ == "__main__":
df = ReadData()
#print df.isnull().sum()['hw1']
hist = df['hw1'].value_counts()
|
d8bf8623f9e4a58288909e1f05a7e172aea6e5a3 | iamserda/cuny-ttp-algo-summer2021 | /roseWong/assignments/slidingwindow/lc53/lc53.py | 2,017 | 4.03125 | 4 | # Problem Statement #
# Given an array of positive numbers and a positive number ‘k,’ find the maximum sum of any contiguous subarray of size ‘k’.
# Personal note - "Diary" - I am able to understand and explain the code after
# Melissa walked us through a solution. Here I "copy" the code by typing it in per class'
# instructions. I "translated" it to Python, which I am very rusty at.
#import numpy as np
def max_sub_array_of_size_k(k, arr):
maxSum = 0
windowSum = 0
windowStart = 0
windowEnd = 0
for windowEnd in range(len(arr)):
windowSum = windowSum + arr[windowEnd] # this adds the next element in the array
# slide the window when we hit the required size of k
if windowEnd >= k-1:
maxSum = max(maxSum, windowSum)
# remove the element that is being dropped from the next sum
windowSum = windowSum - arr[windowStart]
windowStart = windowStart + 1
return maxSum
def main():
print("Maximum sum of a subarray of size K: " + str(max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])))
print("Maximum sum of a subarray of size K: " + str(max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])))
main()
# bruteforce/naive approach
# -----
# def max_sub_array_of_size_k(k, arr):
# max_sum = 0
# window_sum = 0
# for i in range(len(arr) - k + 1):
# window_sum = 0
# for j in range(i, i+k):
# window_sum += arr[j]
# max_sum = max(max_sum, window_sum)
# return max_sum
# better approach
# -----
# def max_sub_array_of_size_k(k, arr):
# max_sum , window_sum = 0, 0
# window_start = 0
# for window_end in range(len(arr)):
# # add the next element
# window_sum += arr[window_end]
# # slide the window, we don't need to slide if we've not hit the required window size of 'k'
# if window_end >= k-1:
# max_sum = max(max_sum, window_sum)
# # subtract the element going out
# window_sum -= arr[window_start]
# # slide the window ahead
# window_start += 1
# return max_sum
|
58400455a1d233e0e4e54f85b411fb88129e3563 | sharmasourab93/PythonDesignPatterns | /design_patterns/behavioural_design_pattern/template/template_pattern_example.py | 1,604 | 4.21875 | 4 | """
Python
Don't Repeat Yourself principle violated.
"""
class Bus(object):
def __init__(self, destination):
self._destination = destination
def bus_trip(self):
self.start_diesel()
self.leave_terminal()
self.drive_to_destination()
self.arrive_at_destination()
def start_diesel(self):
print("Starting the Cummins Diesel Engine")
def leave_terminal(self):
print("Leaving Terminal")
def drive_to_destination(self):
print("Driving ...")
def arrive_at_destination(self):
print("Arriving at " + self._destination)
class Airplane(object):
def __init__(self, destination):
self._destination = destination
def plane_trip(self):
self.start_gas_turbines()
self.leave_terminal()
self.fly_to_destination()
self.land_at_destination()
def start_gas_turbines(self):
print("Starting the Rolls-Royce gas-turbine engines")
def leave_terminal(self):
print("Taxing to the runway")
print("Taking off")
def fly_to_destination(self):
print("Flying...")
def land_at_destination(self):
print("Landing at" + self._destination)
def take_bus(destination):
print("Taking the bus to " + destination + "==>")
bus = Bus(destination)
bus.bus_trip()
def take_plane(destination):
print("Flying to " + destination + "==>")
plane = Airplane(destination)
plane.plane_trip()
if __name__ == '__main__':
take_bus('New York')
take_plane('Amsterdam')
|
937905ae16a62a384c7312c050e0a966509d913a | y56/proving-ground | /py-dict-learn/tmp00.py | 411 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 15 03:43:16 2019
@author: y56
"""
r1dict = {1:'I',10:'X',100:'D'}
r5dict = {1:'V',10:'L',100:'M'}
for d in [1,10,100]: # d is for decimal base
r1 = r1dict[d] # roman digit 1
r5 = r5dict[d] # roman digit 5
myDict = {1*d:r1, 2*d:r1*2,3*d:r1*3, 4*d:r1+r5, 5*d:r5,6*d:r5+r1, 7*d:r5+r1*2, 8*d:r5+r1*3, 9*d:r1+r5}
print(myDict) |
3bc0312c42f36cbba156447fc4d7aaaa10cebdd1 | pawelszablowski/Python | /EduInf_waw/2.Liczby_Podzielne.py | 573 | 3.6875 | 4 | #W przedziale <a, b> liczb całkowitych należy wyszukać wszystkie liczby
# podzielne przez jedną z liczb z zadanego zbioru P.
a = int(input("Podaj początek zakresu: "))
b = int(input("\nPodaj koniec zakresu: "))
n = int(input("\nPodaj liczbę podzielników: "))
i = 0
j = 1
p = []
while i <= n:
p.append(i)
print(p[i],end=" ")
i +=1
print("\n")
i = 1
while i <= b:
while j <= n:
if (i % p[j]) == 0:
print("Liczba ",i,"dzieli się przez ",p[j])
print("Test github")
break
j += 1
i += 1 |
dfbc7df85fae70721c6d1faff8a038814715f467 | Kotaro-Sekine/hippocampus | /Fruits_and_vegetables.py | 3,683 | 3.734375 | 4 | #!/usr/bin/env python
# coding: utf-8
# In[1]:
import numpy as np
class hebb:
memory = []
memory_size = 0
def __init__(self, size):
self.memory_size = size
self.memory = np.reshape([0]*size**2, (size, size))
def learn(self, activity):
if self.memory_size != len(activity):
return False
for y in range(self.memory_size):
for x in range(self.memory_size):
if x == y:
self.memory[x,y] = 0
elif activity[x] == 1 and activity[y] == 1:
self.memory[x,y] += 1
elif activity[x] == -1 and activity[y] == -1:
pass #このケースはpassでなく+1とすることも多々(今回は神経回路のモデル化を意識してpassにした)
else:
self.memory[x,y] -= 1
#print(self.memory)#途中経過表示
return True
def remember(self, activity):
if self.memory_size != len(activity):
return False
activity = np.reshape(activity, (self.memory_size, 1))
reminder = np.dot(self.memory,activity)
#print(reminder) #途中経過
######################閾値設定(option)#########################################
#for i in range(self.memory_size):
# if reminder[i]>3:
# pass
# else: #閾値を下回ったら負に(活性なしと判断)
# reminder[i]=-abs(reminder[i]
######################################################################
reminder2 = np.reshape(reminder / abs(reminder), (1, self.memory_size)).flatten()
reminder2[np.isnan(reminder2)] = -1
reminder3 = [int(s) for s in reminder2]
return reminder3
# In[2]:
def learn(m):
if h.learn(m):
print("I learn",m)
else:
print("I can't learn",m)
def remember(question):
answer = h.remember(question)
if any(answer):
if answer==[1,-1,1,-1]:
print("apple")
elif answer==[1,-1,-1,1]:
print("tomato")
elif answer==[-1,1,1,-1]:
print("banana")
else:
print("I can not answer")
else:
print("I can not answer")
##activity[0]=red,[1]=yellow,[2]=fruit,[3]=vegetable##
def keyword(k):
if k=="apple":
return [1,-1,1,-1]
elif k=="tomato":
return [1,-1,-1,1]
elif k=="banana":
return [-1,1,1,-1]
elif k=="red":#個々の数値は要検討
return [1,-1,0,0]
elif k=="yellow":
return [-1,1,0,0]
elif k=="fruit":
return [0,0,1,-1]
elif k=="vegetable":
return [0,0,-1,1]
else:
print("I can not remember this")
h = hebb(4) #the number of neurons
#########################
print("Counts")
n=int(input()) #何回学習・思いだす作業を行うか The total number of tasks of "learn" and "remember"
for i in range(n):
print("0=learn,1=remember")
a=int(input()) #0=learn,1=remember
if a==0:
b=input() #input fruits/vegetables
if b=="apple" or "tomato" or "banana":
learn(keyword(b))
else:
print("I can not remeber this")
else:
b=input() #input keyword
remember(keyword(b))
#########################
#重み行列,入力配列を事前決定する場合は上の##内をコメントアウトし,こっちを使う
#If you don't want to use "input", you can use this.
#learn(keyword("apple"))
#learn(keyword("apple"))
#learn(keyword("tomato"))
#learn(keyword("apple"))
#remember(keyword("red"))
#remember(keyword("yellow"))
#########################
|
9829a596af82c41ed457a59a4010953b64802cdc | kunalkumar37/allpython---Copy | /boolean.py | 911 | 3.84375 | 4 | #boolean represnet one of two values::
#true false
print(bool("hello"))
print(bool(14))
class myclass():
def __len__(self):
return 0
myobj=myclass()
print(bool(myobj))
def myfunction():
return True
print(myfunction())
def myfunction():
return True
if myfunction():
print("yes")
else:
print("no")
#isinstance() function which can be uesd ot determine if an objedt is of certain type
x=200
print(isinstance(x,int))
print(10+5)
print(10//5)
print(10/5)
#membership operator
#in returns True if a sequence with the specified value is present in the object
#not in returns true if a sequence woth the spefified value is not present in the object
#<< Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off
#>> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off |
d0e5e798674bb7395cb00caa997b548b1160f5cd | xwzl/python | /python/src/com/python/learn/container/SetOperate.py | 6,744 | 3.828125 | 4 | import time
# Python set 集合最常用的操作是向集合中添加元素、删除元素,以及集合之间做交集,并集、差集等运算。
#
# 向 set 集合中添加元素
#
# set 集合中添加元素,可以使用 set 类型提供的 add() 方法实现,该方法的语法格式为:
#
# setName.add(element)
#
# 其中,setName 表示要添加元素的集合,element 表示要添加的元素内容。
#
# 需要注意的是,使用 add() 方法添加的元素,只能是数字、字符串、元组或者布尔类型(True 和 False)值,不能添加列表、字典、集
# 合这类可变的数据,否则 Python 解释器会报 TypeError 错误
a = {1, 2, 3}
a.add((1, 2))
print(a)
# a.add([1, 2])
# print(a)
dicts = {"java": 1, "go": 2}
print("java" not in dicts)
# 上面程序中,由于集合中的元素 1 已被删除,因此当再次尝试使用 remove() 方法删除时,会引发 KeyError 错误。
#
# 如果我们不想在删除失败时令解释器提示 KeyError 错误,还可以使用 discard() 方法,此方法和 remove() 方法的用法完全相同,唯一的
# 区别就是,当删除集合中元素失败时,此方法不会抛出任何错误。
print("set 删除元素有两个方法,一个是 remove 方法,如果元素不在集合集中报错, 相反的是 discard() 删除元素,元素不存不会报错")
numberSet = {1, 2, 3, 4, 5, 6, 7}
numberSet.discard(2)
numberSet.discard(2)
# numberSet.remove(2) # 元素不存报错
# Python set集合做交集、并集、差集运算
#
# 集合最常做的操作就是进行交集、并集、差集以及对称差集运算
# 交集 & 并集 | 差集 - 对称差集 ^
dataSet = {1, 3, 5}
dataSet1 = {5, 7, 9}
print(dataSet & dataSet1) # 交集 5
print(dataSet1 | dataSet) # 交集 1 3 5 7 9
print(dataSet - dataSet1) # 差集 1 3
print(dataSet1 - dataSet) # 差集 1 3
print(dataSet ^ dataSet1) # 对称差集
print("\nset 常用方法\n")
# add 方法
dataSet2 = {1, 2}
dataSet2.add(3)
print("dataSet2:", dataSet2)
dataSet2.clear()
print("dataSet2元素 已清空", dataSet2)
dataSet2 = {1, 2, 3}
dataSet3 = {3, 4, 5}
diff = dataSet2.difference(dataSet3)
print("difference 方法 dataSet2 中有而 dataSet3 没有的元素复制给 diff:", diff)
dataSet2.difference_update(dataSet3)
print("difference_update 方法删除 dataSet2 与 dataSet3 相同的元素:", dataSet2)
dataSet2.discard(2) # 删除元素 2,不存在也不报错
dataSet2 = {1, 2, 3}
intersection = dataSet2.intersection(dataSet3)
print("intersection 方法把 dataSet2 与 dataSet3 相同的元素赋值给 intersection:", intersection)
dataSet2.intersection_update(dataSet3)
print("intersection_update 方法把 dataSet2 与 dataSet3 相同的元素赋值给 dataSet2:", dataSet2)
dataSet2 = {1, 2, 3}
print("判断是否有交集", dataSet2.isdisjoint(dataSet3))
dataSet4 = {1, 2}
print("判断是否是子集:", dataSet4.issubset(dataSet2)) # True
print("判断是否是父集:", dataSet4.issuperset(dataSet2)) # False
print("排除相同的元素,并返回", dataSet2.symmetric_difference(dataSet3))
dataSet2.symmetric_difference_update(dataSet3)
print("删除相同的元素并赋值 dataSet2", dataSet2)
dataSet2 = {1, 2, 3}
print("union 并集:", dataSet2.union(dataSet3))
updateSet = {1, 2}
print(", update 用于将列表或者集合中元素添加到 set 集合中")
updateSet.update([1, 2, 3, 4])
print(updateSet)
# frozenset 是 set 的不可变版本,因此 set 集合中所有能改变集合本身的方法(如 add、remove、discard、xxx_update 等),frozenset 都不支持;
# set 集合中不改变集合本身的方法,fronzenset 都支持。
#
# 在交互式解释器中输入 dir(frozenset) 命令来查看 frozenset 集合的全部方法,可以看到如下输出结果:
#
# >>> dir(frozenset)
# ['copy', 'difference', 'intersection', 'isdisjoint', 'issubset', 'issuperset', 'symmetric_difference', 'union']
#
# 很明显,frozenset 的这些方法和 set 集合同名方法的功能完全相同。
#
# frozenset 的作用主要有两点:
#
# 当集合元素不需要改变时,使用 frozenset 代替 set 更安全。
# 当某些 API 需要不可变对象时,必须用 frozenset 代替set。比如 dict 的 key 必须是不可变对象,因此只能用 frozenset;再比如 set 本身的集合元
# 素必须是不可变的,因此 set 不能包含 set,set 只能包含 frozenset。
s = set()
# 创建 frozenset 不可变集合,使用 frozenset() 函数
frozen_s = frozenset('Kotlin')
# 为set集合添加frozenset
s.add(frozen_s)
print('s集合的元素:', s)
sub_s = {'Python'}
# 为set集合添加普通set集合,程序报错
# s.add(sub_s)
def find_product_price(products, product_id):
for id, price in products:
if id == product_id:
return price
return None
# 在上面程序的基础上,如果列表有 n 个元素,因为查找的过程需要遍历列表,那么最坏情况下的时间复杂度就为 O(n)。即使先对列表进行排序,再使
# 用二分查找算法,也需要 O(logn) 的时间复杂度,更何况列表的排序还需要 O(nLogN) 的时间。
#
# 但如果用字典来存储这些数据,那么查找就会非常便捷高效,只需 O(1) 的时间复杂度就可以完成,因为可以直接通过键的哈希值,找到其对应的值,而
# 不需要对字典做遍历操作,实现代码如下:
products = [
(111, 100),
(222, 30),
(333, 150)
]
print('The price of product 222 is {}'.format(find_product_price(products, 222)))
print('The price of product 222 is {}'.format(products[222]))
# 统计时间需要用到 time 模块中的函数,了解即可
def find_unique_price_using_list(products):
unique_price_list = []
for _, price in products: # A
if price not in unique_price_list: # B
unique_price_list.append(price)
return len(unique_price_list)
ids = [x for x in range(0, 100000)]
price = [x for x in range(200000, 300000)]
products = list(zip(ids, price))
# 计算列表版本的时间
start_using_list = time.perf_counter()
find_unique_price_using_list(products)
end_using_list = time.perf_counter()
print("time elapse using list: {}".format(end_using_list - start_using_list))
# 使用集合完成同样的工作
def find_unique_price_using_set(products):
unique_price_set = set()
for _, price in products:
unique_price_set.add(price)
return len(unique_price_set)
# 计算集合版本的时间
start_using_set = time.perf_counter()
find_unique_price_using_set(products)
end_using_set = time.perf_counter()
print("time elapse using set: {}".format(end_using_set - start_using_set))
|
bcc4db183fbcb4ac3f48f122f7e88e7bc4e28bf2 | MateuszJarosinski/ListaZaliczeniowaDSWPodstawyProgramowania | /2.py | 810 | 3.578125 | 4 | """
ubezpieczenie emerytalne: 9,76% * kwota brutto
składka rentowa: 6,5% * kwota brutto
składka wypadkowa: 1,67 * kwota brutto
fundusz pracy: 2,45% * kwota brutto
skłądka na Fundusz Gwarantowanych Świadczeń Pracowniczych: 0.10% * kwota brutto
+ pensja praownika brutto
"""
def employerCosts(kwotaBrutto):
ubezpieczenieEmerytalne = 0.0976 * kwotaBrutto
skladkaRentowa = 0.065 * kwotaBrutto
skladkaWypadkowa = 0.0167 * kwotaBrutto
funduszPracy = 0.0245 * kwotaBrutto
FGSP = 0.001 * kwotaBrutto
totalCost = ubezpieczenieEmerytalne + skladkaRentowa + skladkaWypadkowa + funduszPracy + FGSP + kwotaBrutto
return totalCost
brutto = float(input("Podaj kowtę prutto pracownika: "))
print("Aby zatrudnić pracownika musisz łącznie wydać ", employerCosts(brutto), "zł.") |
7f454e4cbb12313ad62e26fe64a599b522367c50 | carlosalf9/InvestigacionPatrones | /patron adapter python/main.py | 416 | 3.984375 | 4 | """ main method """ if name == "main":
"""list to store objects"""
objects = []
motorCycle = MotorCycle()
objects.append(Adapter(motorCycle, wheels = motorCycle.TwoWheeler))
truck = Truck()
objects.append(Adapter(truck, wheels = truck.EightWheeler))
car = Car()
objects.append(Adapter(car, wheels = car.FourWheeler))
for obj in objects:
print("A {0} is a {1} vehicle".format(obj.name, obj.wheels())) |
f9fe70e9a9bc55774c0413ce1887d45d677bfd4f | nishaagrawal16/Datastructure | /leetcode/medium/3_longest_substring_without_repeating_chars_solution_1_n^3.py | 839 | 3.84375 | 4 | """
https://leetcode.com/problems/longest-substring-without-repeating-characters/
Complexity
----------
O(n^3)
"""
class Solution:
def lengthOfLongestSubstring(self, s):
if len(s) == 1:
return 1
nonRepeating = []
result = []
for i in range(len(s)):
for j in range(i, len(s)):
if s[j] not in nonRepeating:
nonRepeating.append(s[j])
else:
result.append(''.join(nonRepeating))
nonRepeating = []
break
val = ''
for item in result:
if len(val) < len(item):
val = item
return len(val)
def main():
s = Solution()
input = "abcabcbb"
print('input = ', input)
output = s.lengthOfLongestSubstring(input)
print('Output : ', output)
if __name__ == '__main__':
main()
# Output:
#---------
# input = abcabcbb
# Output : 3
|
26d83ed4129b7e64dfa0cf5fbb84f4440c8ee177 | Aiden1997/Tkinter | /checkbutton.py | 784 | 3.5625 | 4 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
import tkinter as tk
window = tk.Tk()
window.title('Choice')
window.geometry('1080x720')
l = tk.Label(window,bg='yellow',width=20,text='empty')
l.pack()
def print_selection():
if(var1.get()==1)&(var2.get()==0):
l.config(text='I love Python')
elif(var1.get()==0)&(var2.get()==1):
l.config(text='I love C++')
elif(var1.get()==1)&(var2.get()==1):
l.config(text='I love both')
else:
l.config(text='I don\'t like either')
var1 = tk.IntVar()
var2 = tk.IntVar()
c1 = tk.Checkbutton(window,text='Python',variable=var1,onvalue=1,
offvalue=0,command = print_selection)
c2 = tk.Checkbutton(window,text='C++',variable=var2,onvalue=1,
offvalue=0,command = print_selection)
c1.pack()
c2.pack()
window.mainloop()
|
6e0bba0728418408f211ed4ad20abb5a2c0899f5 | Hgser/NURBS-Python | /geomdl/_tessellate.py | 6,552 | 3.578125 | 4 | """
.. module:: _tessellate
:platform: Unix, Windows
:synopsis: Helper functions and algorithms for tessellation operations
.. moduleauthor:: Onur Rauf Bingol <orbingol@gmail.com>
"""
from . import elements
from . import utilities
from . import ray
# Initialize an empty __all__ for controlling imports
__all__ = []
def is_left(point0, point1, point2):
""" Tests if a point is Left|On|Right of an infinite line.
Ported from the C++ version: on http://geomalgorithms.com/a03-_inclusion.html
:param point0: Point P0
:param point1: Point P1
:param point2: Point P2
:return:
>0 for P2 left of the line through P0 and P1
=0 for P2 on the line
<0 for P2 right of the line
"""
return ((point1[0] - point0[0]) * (point2[1] - point0[1])) - ((point2[0] - point0[0]) * (point1[1] - point0[1]))
def wn_poly(point, vertices):
""" Winding number test for a point in a polygon.
Ported from the C++ version: http://geomalgorithms.com/a03-_inclusion.html
:param point: point to be tested
:type point: list, tuple
:param vertices: vertex points of a polygon vertices[n+1] with vertices[n] = vertices[0]
:type vertices: list, tuple
:return: True if the point is inside the input polygon, False otherwise
:rtype: bool
"""
wn = 0 # the winding number counter
v_size = len(vertices) - 1
# loop through all edges of the polygon
for i in range(v_size): # edge from V[i] to V[i+1]
if vertices[i][1] <= point[1]: # start y <= P.y
if vertices[i + 1][1] > point[1]: # an upward crossing
if is_left(vertices[i], vertices[i + 1], point) > 0: # P left of edge
wn += 1 # have a valid up intersect
else: # start y > P.y (no test needed)
if vertices[i + 1][1] <= point[1]: # a downward crossing
if is_left(vertices[i], vertices[i + 1], point) < 0: # P right of edge
wn -= 1 # have a valid down intersect
# return wn
return bool(wn)
def surface_trim_tessellate(v1, v2, v3, v4, vidx, tidx, trims, tessellate_args):
""" Trimmed surface tessellation algorithm.
:param v1: vertex 1
:type v1: Vertex
:param v2: vertex 2
:type v2: Vertex
:param v3: vertex 3
:type v3: Vertex
:param v4: vertex 4
:type v4: Vertex
:param vidx: vertex numbering start value
:type vidx: int
:param tidx: triangle numbering start value
:type tidx: int
:param trims: trim curves
:type trims: list, tuple
:param tessellate_args: tessellation arguments
:type tessellate_args: list, tuple
:return: lists of vertex and triangle objects in (vertex_list, triangle_list) format
:type: tuple
"""
# Tolerance value
tol = 10e-8
# Check if all vertices are inside the trim, and if so, don't generate a triangle
vertices = [v1, v2, v3, v4]
for idx, vertex in enumerate(vertices):
for trim_curve in trims:
# Check if the vertex is inside the trimmed region
is_inside_trim = wn_poly(vertex.uv, trim_curve.evalpts)
if is_inside_trim:
vertex.inside = True
vertices_inside = [v1.inside, v2.inside, v3.inside, v4.inside]
if all(vertices_inside):
return [], []
# # Generate triangles
# return [], utilities.polygon_triangulate(tidx, v1, v2, v3, v4)
# Generate edges as rays
edge1 = ray.Ray(v1.uv, v2.uv)
edge2 = ray.Ray(v2.uv, v3.uv)
edge3 = ray.Ray(v3.uv, v4.uv)
edge4 = ray.Ray(v4.uv, v1.uv)
# Put all edge rays to a list
edges = [edge1, edge2, edge3, edge4]
# List of intersections
intersections = []
# Loop all trim curves
for trim in trims:
pts = trim.evalpts
for idx in range(len(pts) - 1):
# Generate a ray from trim curve's evaluated points
trim_ray = ray.Ray(pts[idx], pts[idx + 1])
# Intersection test of the trim curve's ray with all edges
for idx2 in range(len(edges)):
t1, t2, status = ray.intersect(edges[idx2], trim_ray)
if status == ray.RayIntersection.INTERSECT:
if 0.0 - tol < t1 < 1.0 + tol and 0.0 - tol < t2 < 1.0 + tol:
intersections.append([idx2, t1, edges[idx2].eval(t=t1)])
# Add first vertex to the end of the list
vertices.append(v1)
# Local vertex numbering index
nvi = 0
# Process vertices and intersections
tris_vertices = []
verts = []
for idx in range(0, len(vertices) - 1):
# If two consecutively-ordered vertices are inside the trim, there should be no intersection
if vertices[idx].inside and vertices[idx + 1].inside:
continue
# If current vertex is not inside the trim, add it to the vertex list
if not vertices[idx].inside:
tris_vertices.append(vertices[idx])
# If next vertex is inside the trim, there might be an intersection
if (not vertices[idx].inside and vertices[idx + 1].inside) or \
(vertices[idx].inside and not vertices[idx + 1].inside):
# Try to find all intersections (multiple intersections are possible)
isects = []
for isect in intersections:
if isect[0] == idx:
isects.append(isect)
# Find minimum t value and therefore minimum uv value of the intersection
t_min = 1.0
uv_min = ()
for isect in isects:
if isect[1] < t_min:
t_min = isect[1]
uv_min = isect[2]
# Create a vertex with the minimum uv value
vert = elements.Vertex()
vert.id = vidx + nvi
vert.uv = uv_min
# Add to lists
tris_vertices.append(vert)
verts.append(vert)
# Increment local vertex numbering index
nvi += 1
# Triangulate vertices
tris = utilities.polygon_triangulate(tidx, *tris_vertices)
# Check again if the barycentric coordinates of the triangles are inside
for idx in range(len(tris)):
tri_center = utilities.triangle_center(tris[idx], uv=True)
for trim in trims:
if wn_poly(tri_center, trim.evalpts):
tris[idx].inside = True
# Extract triangles which are not inside the trim
tris_final = []
for tri in tris:
if not tri.inside:
tris_final.append(tri)
return verts, tris_final
|
872173a798f0085282921907b91bad088ef29798 | NadjB/Juice_SCM_GSE | /juice_scm_gse/analysis/fft.py | 2,083 | 3.65625 | 4 |
import numpy as np
def __fact(window):
"""Computes the amplitude conpensation factor to apply to a FFT for the given window.
Just equivalent to 1/RMS(window).
Args:
window ( iterable object): The windows to analyse.
Returns:
float: The compensation factor.
"""
return 1./np.sqrt(np.mean(np.square(window)))
def fft(waveform, sampling_frequency=1., window=None, remove_mean=True):
"""Compute the FFT of the given signal wf and return result in a fashion way.
Args:
wf ( iterable object): The time domain signal on which you want to compute FFT.
fs (Optional[float]): Sampling frequency of wf, used for frequency vector normalization.
window ( Optional[iterable object]): The window to apply.
removeMean (Optional[bool]): Set to True if you want to remove mean on signal befor
computing FFT.
Returns:
dict: The FFT result simplified and stored in a dict. The FFT result is trucated from F=0 to
F=Fs/2 and amplitude is normalized to its real value and in case of windowing, the
window correction factor is applied.
keys ( strings ):
f ( numpy array of float ): Frequency vector normalized to given "fs" frequency
mod ( numpy array of float ): Amplitude vector divided by len(wf) and corrected if a
window is applied.
phi ( numpy array of float ): Phase vector.
"""
scale_factor = 1./len(waveform)
if remove_mean:
waveform = waveform - np.mean(waveform)
if not window is None:
waveform = waveform*window
scale_factor = scale_factor *__fact(window)
spectrum = np.fft.fft(waveform) *scale_factor
frequency = np.fft.fftfreq(len(spectrum), 1/sampling_frequency)
frequency[int(len(frequency)/2)] = abs(frequency[int(len(frequency)/2)])
return {"f":frequency[0:int(len(frequency)/2)+1],
"mod":abs(spectrum[0:int(len(spectrum)/2)+1]),
"phi":np.angle(spectrum[0:int(len(spectrum)/2)+1], False)}
|
86e6b610c4c0013e13b21b1e8061de5cf846a5d9 | MSaaad/Basic-python-programs | /Sum of natural numbers.py | 539 | 4.3125 | 4 | #python program to find sum of natural numbers
num=1
while True: #As long as the condition is true
num=int(input('Enter the number you want for the sum:'))
if num<0:
print('Negative numbers are not Natural numbers')
break
elif num==0:
print('0 is not a natural number')
break
sum=0
count=0 #USING COUNTER VARIABLE
while count<num:
count=count+1
sum=sum+count #ADDING IN COUNTER VARIABLE
print('The sum of first',num,'natural number is',sum)
|
14686fb68d17cef8f860c2b533e940dfee4fe91a | us19861229c/Meu-aprendizado-Python | /CeV - Gustavo Guanabara/exerc030.py | 211 | 4 | 4 | #030: ler um numero e dizer se é par ou impar
num = int(input("Escolha um numero: "))
if num % 2 == 0 :
print("este numero é PAR")
else:
print("este numero é IMPAR")
print("obrigada por participar!") |
128886d186124f6fe81347a427b77b24c9c078ef | MrBoas/PLC | /SPLN/aulas_kiko/aula2/ex3.py | 564 | 4.28125 | 4 | #!/usr/bin/python3
#Função que recebe nome de ficheiro e imprime linhas em ordem inversa
## Normal
def reversePrint (file):
for line in reversed(open(file).readlines()):
# print (line, end='') #termina com nada
print (line.rstrip()) #remove \n a direita (e espaço vazio?)
# print (line) #termina com um \n
print(" >> Normal: ")
reversePrint("test_file.txt")
## Oneline
def reversePrintOneline (file):
[print(i, end='') for i in (reversed(open(file).readlines()))]
print(" >> Oneline: ")
reversePrintOneline("test_file.txt")
|
1c2742943251d0467da95fac73f0b5a68691c180 | megarazor/INIAD_3 | /Exercise4B/Week123/sum_between.py | 193 | 3.84375 | 4 | def sum_between(x, y):
if x > y:
tmp= x
x= y
y= tmp
sum= 0
for i in range(x, (y + 1)):
sum+= i
return sum
print(sum_between(10, 12))
|
0a2aa7b199fae04a10ee91835cdba5e027d6eef2 | jiluhu/dirtysalt.github.io | /codes/contest/leetcode/most-frequent-subtree-sum.py | 1,008 | 3.703125 | 4 | #!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import defaultdict
class Solution:
def findFrequentTreeSum(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
counter = defaultdict(int)
def visit(root):
if root is None:
return 0
res = root.val
if root.left:
c = visit(root.left)
res += c
if root.right:
c = visit(root.right)
res += c
counter[res] += 1
return res
if root is None:
return []
visit(root)
res = list(counter.items())
res.sort(key=lambda x: -x[1])
freq = res[0][1]
res = [x[0] for x in res if x[1] == freq]
return res
|
59cde930fc9d4eaab3601eac9af6fd027822b26c | kallyrhodes/LIS4930 | /Module #5.1.py | 158 | 3.75 | 4 | def insert_sting_middle(str, word):
length=len(str)//2
s=str[:length] + word + str[length:]
return s
print(insert_sting_middle('[[]]', 'Python'))
|
d245de137f14278a6698ee9e6ea002d00388223c | sshekhar1094/python_automations | /wikipedia.py | 1,269 | 3.875 | 4 | #!usr/bin/python
# Python script to take in query and read out summary of corresponding wikipedia article
# Uses google search intead of wiki search as google gives the most relevant article
# External modules: requests, bs4, gtts
import os
import sys
import requests
from bs4 import * #web scraping
from gtts import gTTS as speech #text to speech
def main():
if(len(sys.argv) == 1): #checking if cmd argument given
query = input("Enter search item:")
query = query.replace(' ', '+')
else:
query = '+'.join(sys.argv[1:]) #walmart labs = walmart+labs
link = 'https://www.google.co.in/search?q=wikipedia+' + query #google search
data = requests.get(link)
soup = BeautifulSoup(data.text, "html.parser")
link = 'https://www.google.co.in' + soup.find('div', {'class':'g'}).h3.a.get('href') #link of 1st item
data = requests.get(link) #wikipedia page
soup = BeautifulSoup(data.text, "html.parser")
summary = soup.find('div', {'id':'mw-content-text'}).p.text #get the 1st para
print(summary)
tts = speech(summary, lang='en') #save summary as mp3
tts.save('wiki.mp3')
os.system('mpg321 wiki.mp3')
os.remove('wiki.mp3')
if __name__ == "__main__": main()
|
807194153dec6564c674e511f2ce051ccd47159f | enmorse/PythonCrashCourse2ndEdition.4-6.OddNumbers.py | /Main.py | 236 | 4.28125 | 4 | # Use the third argument of the range() function to
# make a list of the odd numbers from 1 to 20. Use a
# for loo to print each number.
odd_numbers = []
for value in range(1, 20, 2):
odd_numbers.append(value)
print(odd_numbers)
|
14b27cfc1baa0848ab1b293207520abb9ec0c24d | Madhivarman/DataStructures | /leetcodeProblems/minimumCostsPerTickets.py | 1,269 | 3.875 | 4 | """
In a country popular for train travel, you have planned some train travelling one year in advance. The days of the year that you will travel is given as an array days. Each day is an integer from 1 to 365.
Train tickets are sold in 3 different ways:
a 1-day pass is sold for costs[0] dollars;
a 7-day pass is sold for costs[1] dollars;
a 30-day pass is sold for costs[2] dollars.
The passes allow that many days of consecutive travel. For example, if we get a 7-day pass on day 2, then we can travel for 7 days: day 2, 3, 4, 5, 6, 7, and 8.
Return the minimum number of dollars you need to travel every day in the given list of days.
"""
from collections import Counter
class Solution:
def mincostTickets(self, days: List[int], costs: List[int]) -> int:
last_day = days[-1]
day = Counter(days)
dp = [0 for x in range(last_day+1)]
for i in range(last_day+1):
if i not in day:
dp[i] = dp[i-1]
else:
one = dp[max(0, i-1)] + costs[0]
seven = dp[max(0, i-7)] + costs[1]
thirty = dp[max(0, i - 30)] + costs[2]
dp[i] = min(one, seven, thirty)
return dp[-1]
|
bb13cbc6977ff93b41d2d98c1466df29dc3e9f54 | rifatmondol/Python-Exercises | /073 - [O.O] Índices.py | 452 | 3.6875 | 4 | #073 - Write a Python program to find a pair of elements (indices of the two numbers) from a given
#array whose sum equals a specific target number.
class Indice:
def soma(self, nums, alvo):
dicNum = {}
for i, num in enumerate(nums):
if alvo - num in dicNum:
return (dicNum[alvo-num] + 1, i+1)
dicNum[num] = i
print('Índice 1: %d, Índice 2: %d' % Indice().soma((10,20,10,40,50,60,70),50)) |
71ff0be003016cbc2b3377e5e84bbe3f37b6258b | drishtipatwa/guessgame | /guessinggame.py | 1,817 | 3.859375 | 4 | from tkinter import *
import random as r
win = Tk()
f = ("Algerian",16)
win.title("Guessing Game")
num = StringVar()
l1 = Label(win, font= f,text = 'Enter your guess:')
en = Entry(win,font = f,width=4,textvariable=num)
l1.grid(column=0,row=1)
en.grid(column = 1, row = 1)
l2 = Label(win, font = f,text = 'Won / Lose',fg = 'red')
n = r.randint(1000,9999)
guesses = 0
temp = n
def click():
global l3, b1, b2, l2
l2.configure(text = "Play Again")
l3.configure(text = "")
b1.destroy()
b2.destroy()
n = r.randint(1000,9999)
global guesses
guesses = 0
global temp
temp = n
def closee():
res = "Thank you for playing"
l2.configure(text = res)
global b1,b2,bt, en
b1.destroy()
b2.destroy()
bt.destroy()
en.destroy()
res=" "
l1.configure(text = res)
l3.configure(text = res)
win.after(5000, lambda: win.destroy())
def clicked():
global guesses
guesses += 1
x = num.get()
global n
global temp
n = temp
y=''
if x==str(n):
res = 'Won in '+str(guesses)+ ' Guesses'
l2.configure(text = res)
global l3, b1, b2
l3 = Label(win, font = f, text= " Do you wanna continue?")
b1 = Button(win, text = 'yes', command = click)
b2 = Button(win, text = 'no', command= closee)
l3.grid(row=5, column=0)
b1.grid(row=5, column =1)
b2.grid(row=5, column = 2)
else:
c =0
if len(x)==4:
y = str(x)
m = str(n)
for i in range(4):
if y[i]==m[i]:
c+=1
res = str(c) +" points. Try again"
l2.configure(text = res)
else:
res='Enter 4 digit number'
l2.configure(text=res)
bt = Button(win, text = 'Check', command = clicked)
l3 = Label(win, font = f, text= " Do you wanna continue?")
b1 = Button(win, text = 'yes', command = click)
b2 = Button(win, text = 'no', command= closee)
l2.grid(row = 6, column = 1)
bt.grid(row =4, column = 1)
win.geometry('600x200')
win.mainloop()
|
7a3164827afabe4c29af630777a7e665ef88f8a3 | ryedunn/Password-Generator | /registration.py | 5,390 | 3.515625 | 4 | import tkinter as tk
def main(parent):
parent = tk.Frame(parent)
Register(parent)
parent.mainloop()
return None
class Register:
def __init__(self, parent, *args, **kwargs):
self.parent = parent
self.parent = tk.Toplevel()
self.parent.title("Registration Form")
self.parent.geometry("425x300")
self.firstname = tk.StringVar()
self.lastname = tk.StringVar()
self.username = tk.StringVar()
self.password = tk.StringVar()
self.verifypass = tk.StringVar()
self.dob = tk.StringVar()
tk.Label(self.parent, text="Please enter details below:").pack()
# Main Frame
frame_Main = tk.Frame(self.parent)
frame_Main.pack()
# User Details Frame
frame_user = tk.LabelFrame(
frame_Main,
text="User Details",
)
frame_user.grid(
pady=5,
padx=5,
)
# First Name Label
tk.Label(frame_user, text="First Name:").grid(
row=0,
column=0,
sticky=tk.E,
pady=5,
)
# First Name Textbox
self.entry_firstName = tk.Entry(
frame_user,
textvariable=self.firstname,
width=10,
)
self.entry_firstName.grid(
row=0,
column=1,
sticky=tk.W,
padx=5,
pady=5,
)
# Last Name Label
tk.Label(frame_user, text="Last Name:").grid(
row=0,
column=2,
sticky=tk.E,
pady=5,
)
# Last Name Textbox
self.entry_lastName = tk.Entry(
frame_user,
textvariable=self.lastname,
width=10,
)
self.entry_lastName.grid(
row=0,
column=3,
sticky=tk.W,
padx=5,
pady=5,
)
# DOB Label
tk.Label(frame_user, text="DOB:").grid(
row=1,
column=0,
padx=5,
pady=5,
)
# DOB Textbox
self.entry_DOB = tk.Entry(
frame_user,
textvariable=self.dob,
width=10,
)
self.entry_DOB.grid(row=1, column=1)
# Account Frame
frame_acct = tk.LabelFrame(
frame_Main,
text="Account Information",
)
frame_acct.grid(
row=2,
column=0,
columnspan=4,
pady=5,
padx=5,
)
# Username Label
tk.Label(frame_acct, text="Username:").grid(
row=0,
column=0,
padx=5,
pady=5,
)
# Username Textbox
self.entry_username = tk.Entry(
frame_acct,
textvariable=self.username,
width=10,
)
self.entry_username.grid(row=0, column=1)
# Password Label
tk.Label(frame_acct, text="Password:").grid(
row=1,
column=0,
padx=5,
pady=5,
)
# Password Textbox
self.entry_password = tk.Entry(
frame_acct,
textvariable=self.password,
show="*",
width=10,
)
self.entry_password.grid(
row=1,
column=1,
padx=5,
pady=5,
)
# Verify Password Label
tk.Label(frame_acct, text="Verify Password:").grid(
row=1,
column=2,
padx=5,
pady=5,
)
# Verify Password Textbox
self.entry_verifypass = tk.Entry(
frame_acct,
textvariable=self.verifypass,
show="*",
width=10,
)
self.entry_verifypass.grid(
row=1,
column=3,
padx=5,
pady=5,
)
# Button Frame
frame_button = tk.Frame(frame_Main)
frame_button.grid(pady=5)
# Register Button
btn_register = tk.Button(
frame_button,
text="Register",
width=10,
bd=3,
# command=register_user,
)
btn_register.grid(
row=0,
column=0,
padx=5,
pady=5,
)
# Clear all Textboxes
btn_clear = tk.Button(
frame_button,
text="Clear",
width=10,
bd=3,
command=self.clear_form,
)
btn_clear.grid(
row=0,
column=1,
padx=5,
pady=5,
)
def register(self):
pass
def register_user():
# username_info = username.get()
# password_info = password.get()
# file = open(".pfdoc", "w")
# file.write(username_info)
# file.write(password_info)
# file.close()
# entry_username.delete(0, tk.END)
# entry_password.delete(0, tk.END)
pass
def clear_form(self):
self.entry_firstName.delete(0, tk.END)
self.entry_lastName.delete(0, tk.END)
self.entry_password.delete(0, tk.END)
self.entry_verifypass.delete(0, tk.END)
self.entry_username.delete(0, tk.END)
self.entry_DOB.delete(0, tk.END)
# e.DOB.set("mm/dd/yy")
|
b2c4bb3420c54e65d601c16f3bc3e130372ae0de | nfarnan/cs001X_examples | /functions/TH/04_main.py | 655 | 4.15625 | 4 | def main():
# get weight from the user
weight = float(input("How heavy is the package to ship (lbs)? "))
if weight <= 0:
print("Invalid weight (you jerk)")
total = None
elif weight <= 2:
# flat rate of $5
total = 5
# between 2 and 6 lbs:
elif weight <= 6:
# $5 + $1.50 per lb over 2
total = 5 + 1.5 * (weight - 2)
# between 6 and 10 lbs:
elif weight <= 10:
# $11 + $1.25 per lb over 6
total = 11 + 1.25 * (weight - 6)
# over 10 lbs:
else:
# $16 + $1 per lb over 10
total = 16 + (weight - 10)
if total != None:
# output total cost to user:
print("It will cost $", format(total, ".2f"), " to ship", sep="")
main()
|
2a0d1c7081a02071ee439ab64493cc4594bc4db3 | Sonu-soni/Python-Tutorial | /Projectf/tut2.py | 250 | 4.03125 | 4 | #If else
x=int(input('Enter a your Age\n'))
if(x>18 and x<25):
print("You are eligible")
elif (x>18 and x<25):
print("Adult")
elif(x>18 and x<50):
print("Gents")
elif(x>18 and x<75):
print("Citizen")
else:
print('Senior citizen')
|
8fc5099ea34c6585151bd65a7bc18f516c7107ff | mbadayil/Ilm | /rangeSumquery.py | 193 | 3.5625 | 4 | l1=[-2, 0, 3, -5, 2, -1]
def sumRange(array1, i, j):
"""
:type i: int
:type j: int
:rtype: int
"""
return sum(array1[i:j+1])
print(sumRange(l1, 0, 5))
|
b2e85ec22e5c7f6b98a3cc521c85a3ec5dd0a9ea | ScienceOxford/pyconuk-2018 | /kitty/CHASSIS_receiver.py | 2,565 | 3.5 | 4 | from microbit import *
import radio
# Please tag us if used!
# We'd love to see what you make:
# @ScienceOxford
'''
A1A-B1B are the four pins of the motor driver.
A1A/B are for one motor, B1A/B are for the other motor
Define which motor driver pin is connected to which micro:bit pin
'''
AIA = pin14
AIB = pin13
BIA = pin12
BIB = pin15
on = 0
off = 1
'''
Because of the way the motor driver works - 1/high is OFF and 0/low is ON.
Define which pins are high/low for each direction.
'''
def stop():
AIA.write_digital(off)
AIB.write_digital(off)
BIA.write_digital(off)
BIB.write_digital(off)
display.show(Image.HAPPY)
def forward():
AIA.write_digital(on)
AIB.write_digital(off)
BIA.write_digital(on)
BIB.write_digital(off)
display.show(Image.ARROW_N)
def backward():
AIA.write_digital(off)
AIB.write_digital(on)
BIA.write_digital(off)
BIB.write_digital(on)
display.show(Image.ARROW_S)
def left_turn():
AIA.write_digital(off)
AIB.write_digital(on)
BIA.write_digital(on)
BIB.write_digital(off)
display.show(Image.ARROW_W)
def right_turn():
AIA.write_digital(on)
AIB.write_digital(off)
BIA.write_digital(off)
BIB.write_digital(on)
display.show(Image.ARROW_E)
def spin():
left_turn()
sleep(700)
stop()
sleep(300)
right_turn()
sleep(700)
stop()
sleep(300)
'''
Assign each of the above functions to a specific message string.
'''
def direction_command():
if command == "forward":
forward()
elif command == "backward":
backward()
elif command == "left":
left_turn()
elif command == "right":
right_turn()
elif command == "stop":
stop()
elif command == "spin":
spin()
else:
display.show("!")
'''
Start conditions:
Turn radio on and to channel 12 (to stop interference)
The channel can be between 0 and 100, and will need to be unique to me!
Define the time_off variable to enable shutoff when no signal received.
'''
radio.on()
radio.config(channel=12)
time_off = 0
'''
Main program:
Check for latest message.
If that message is one of the sent strings, run the associated direction function.
If there is no message received, increase the time_off variable for 10 cycles, then turn off.
'''
while True:
command = radio.receive()
while command is not None:
direction_command()
command = radio.receive()
time_off = 0
if command is None:
time_off += 1
if time_off >= 10:
stop()
|
3a3ef762fc6a5bc1a75da40ae7bd1148497e9a3a | boknowswiki/mytraning | /lintcode/python/1436_flipping_an_image.py | 716 | 3.75 | 4 | #!/usr/bin/python -t
class Solution:
"""
@param A: a matrix
@return: the resulting image
"""
def flipAndInvertImage(self, A):
# Write your code here
if not A or not A[0]:
return A
m = len(A)
n = len(A[0])
for i in range(m):
self.reverse(A[i])
for i in range(m):
for j in range(n):
A[i][j] ^= 1
return A
def reverse(self, a):
l = 0
r = len(a)-1
while l < r:
a[l], a[r] = a[r], a[l]
l += 1
r -= 1
return
|
6ce7e5288054f69ee88237a1813bcfe2ddaee375 | irukae/minecraft_ai | /Code_001.py | 2,566 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Nov 16 19:12:23 2020
@author: Guillaume
"""
import pyautogui
import time
import pydirectinput
import os
os.chdir('D:\Projets\Minecraft')
#screenWidth, screenHeight = pyautogui.size() # Returns two integers, the width and height of the screen. (The primary monitor, in multi-monitor setups.)
#currentMouseX, currentMouseY = pyautogui.position() # Returns two integers, the x and y of the mouse cursor's current position.#
#pyautogui.moveTo(100, 150) # Move the mouse to the x, y coordinates 100, 150.
#pyautogui.click() # Click the mouse at its current location.
#pyautogui.click(200, 220) # Click the mouse at the x, y coordinates 200, 220.
#pyautogui.move(0, 100) # Move mouse 10 pixels down, that is, move the mouse relative to its current position.
##pyautogui.doubleClick() # Double click the mouse at the
#pyautogui.moveTo(500, 500, duration=2, tween=pyautogui.easeInOutQuad) # Use tweening/easing function to move mouse over 2 seconds.
#pyautogui.write('Hello world!', interval=0.25) # Type with quarter-second pause in between each key.
#pyautogui.press('esc') # Simulate pressing the Escape key.
#pyautogui.keyDown('shift')
#pyautogui.write(['left', 'left', 'left', 'left', 'left', 'left'])
#pyautogui.keyUp('shift')
#pyautogui.hotkey('ctrl', 'c')
def my_func():
time.sleep(5)
print("Hey")
my_func()
def move_mouse(x,y):
currentMouseX, currentMouseY = pyautogui.position() # Returns two integers, the x and y of the mouse cursor's current position.
pyautogui.moveTo(currentMouseX + x, currentMouseY + y, duration=0.1, tween=pyautogui.easeInOutQuad) # Use tweening/easing function to move mouse over 2 seconds.
def move_w():
pyautogui.keyDown('w')
time.sleep(3)
pyautogui.keyUp('w')
time.sleep(3)
pyautogui.press('w')
time.sleep(3)
move_mouse(0,20)
move_mouse(20,20)
move_mouse(20,0)
time.sleep(3)
pydirectinput.keyDown('w')
time.sleep(0.5)
pydirectinput.keyUp('w')
move_w()
print('sup1')
time_start = time.time()
im1 = pyautogui.screenshot(region=(0,40, 950,470))
time_end = time.time()
print(time_end - time_start, 'seconds elapsed')
print('sup2')
for pos in pyautogui.locateAllOnScreen('Couleurs\grass.png'):
print(pos)
list(pyautogui.locateAllOnScreen('Couleurs\grass.png'))
time_start = time.time()
region_game = (0,40, 950,470)
test = pyautogui.locateOnScreen('Couleurs\grass.png', region= region_game)
time_end = time.time()
print(time_end - time_start, 'seconds elapsed')
|
84685d919840eb41efcafacbc1071cb36215fbd4 | lillyluo1995/aoc2020 | /aoc/d05/main.py | 2,330 | 4.03125 | 4 | from typing import IO
import math
def calc_num(code, low, high):
'''given a binary seat code and a total number of seats, calc
the correct seat for this'''
# check that it corresponds....need to add 1 bc 0 index
assert math.pow(2, len(code)) == (high-low+1)
if len(code) == 1:
if code in ['B', 'R']:
return high
return low
if code[0] in ['B', 'R']:
return calc_num(code[1:], low+(high-low+1)/2, high)
return calc_num(code[1:], low, high-(high-low+1)/2)
def calc_seat_id(code, num_rows, num_cols):
'''given the string code, calculate what the seat id is '''
row_code = code[0:int(math.log2(num_rows))]
col_code = code[-int(math.log2(num_cols)):]
row_num = calc_num(row_code, 0, num_rows-1)
col_num = calc_num(col_code, 0, num_cols-1)
return row_num*8+col_num
def p_1(input_file: IO,
debug=False): # pylint: disable=unused-argument
'''find the highest seat id in the given list of seats'''
codes = [line.rstrip('\n') for line in input_file]
# sort the codes. B = higher so ok to sort by ascending since B < F
# we multiply the first number by 8 so the impact of the first 7 chars
# will be larger than any impact the last 3 can have
codes.sort()
return calc_seat_id(codes[0], 128, 8)
def p_2(input_file: IO,
debug=False): # pylint: disable=unused-argument
'''now find my seat. the flight is full except front/back'''
num_rows = 128
num_cols = 8
codes = [line.rstrip('\n') for line in input_file]
codes.sort()
# ok now i need to find my seat. it's not hte first or last row....
# so first i need to find the code that denotes the first row
# and then find the code that denotes the last row
max_row = calc_num(codes[0][0:int(math.log2(num_rows))], 0, num_rows-1)
min_row = calc_num(codes[-1][0:int(math.log2(num_rows))], 0, num_rows-1)
# the lower bound for my seat is the last seat in the first row
# and the upper bound for my seat is the first seat in the last row
min_seat = int(max([min_row*8+i for i in range(7)]))
max_seat = int(min([max_row*8+i for i in range(7)]))
seat_codes = {calc_seat_id(x, num_rows, num_cols) for x in codes}
all_seats = set(range(min_seat, max_seat))
return all_seats - seat_codes
|
6c1b92fd810bb846c9beec2abef5d337e83cfd75 | iAbhishek91/algorithm | /basics/13_tuples.py | 506 | 3.828125 | 4 | # they are very similar to list
# key differences or unique features of tuples are:
# - they are immutable, (no addition, del or update of elements from tuples).
# - Its mostly used to store fixed data that never gonna change.
# they are another type of data structure available in Python
# they are represented by first bracket "("
coordinates = (100, 101)
print(coordinates)
print(coordinates[0])
print(len(coordinates)) # find the length of the array
print(coordinates.index(100))
print(coordinates) |
721477843134986d4017d3dfb31bef34d54be979 | dthinkcs/ps | /old/recDP/13-waterArea/sol.py | 2,601 | 3.9375 | 4 |
Don't show this again.
Questions List
C++
Go
Java
Javascript
Python
Theme:
algoexpert
algoexpert
blackboard
cobalt
lucario
midnight
night
oceanic-next
rubyblue
white
Keymaps:
default
default
emacs
vim
00:00
×Don't forget to scroll to the bottom of the page for the video explanation!
Question:_
No changes made.
Water Area
You are given an array of integers. Each non-zero integer represents the height of a pillar of width 1. Imagine water being poured over all of the pillars and return the surface area of the water trapped between the pillars viewed from the front. Note that spilled water should be ignored. Refer to the first minute of the video explanation below for a visual example.
Sample input: [0, 8, 0, 0, 5, 0, 0, 10, 0, 0, 1, 1, 0, 3]
Sample output: 48
Input:Your Solution
Our Solution
No changes made.
Run Code
1
# Copyright © 2019 AlgoExpert, LLC. All rights reserved.
2
3
# O(n) time | O(n) space
4
def waterArea(heights):
5
maxes = [0 for x in heights]
6
leftMax = 0
7
for i in range(len(heights)):
8
height = heights[i]
9
maxes[i] = leftMax
10
leftMax = max(leftMax, height)
11
rightMax = 0
12
for i in reversed(range(len(heights))):
13
height = heights[i]
14
minHeight = min(rightMax, maxes[i])
15
if height < minHeight:
16
maxes[i] = minHeight - height
17
else:
18
maxes[i] = 0
19
rightMax = max(rightMax, height)
20
return sum(maxes)
21
Help:Hide
Show
Hint #1Hint #2Hint #3Optimal Space & Time Complexity
In order to calculate the amount of water above a single point in the input array, you must know the height of the tallest pillar to its left and the height of the tallest pillar to its right.
Output:Custom Output
Raw Output
Run your code when you feel ready.
Tests:Our Tests
Your Tests
Hide
Show
No changes made.
1
import program
2
import unittest
3
4
5
class TestProgram(unittest.TestCase):
6
7
def test_case_1(self):
8
self.assertEqual(program.waterArea([]), 0)
9
10
def test_case_2(self):
11
self.assertEqual(program.waterArea([0, 0, 0, 0, 0]), 0)
12
13
def test_case_3(self):
14
self.assertEqual(program.waterArea([0, 1, 0, 0, 0]), 0)
15
16
def test_case_4(self):
17
self.assertEqual(program.waterArea([0, 1, 1, 0, 0]), 0)
18
19
def test_case_5(self):
Video ExplanationGo to Conceptual OverviewGo to Code WalkthroughQuestions List
Copyright © 2019 AlgoExpert, LLC. All rights reserved.
Become An Affiliate
Contact Us
FAQ
Legal Stuff
Privacy Policy
|
f6c5e328e5b949ec7ffe1220fad91508bb59391a | mnauman-tamu/ENGR-102 | /part1.py | 2,098 | 4.09375 | 4 | # Program for Plotting Functions
#
# Plots a given function, first and second derivatives, and min/maxes
#
# Alexander M Bogdan
# Patrick Zhong
# Muhammad Nauman
# Daniel Huck
# November 19, 2018
# ENGR 102-213
#
# Lab 12 Activity 1 - Program for Plotting Functions
from scipy.misc import *
import numpy as np
import matplotlib.pyplot as plot
dx = 0.5
def funcDer(x, func):
"""
Returns value of numerically calculated derivative of func at x
"""
return derivative(func, x, dx)
def funcDer2(x, func):
"""
Returns value of numerically calculated second derivative of func at x
"""
return derivative(funcDer, x, dx, n=1, args=[func])
def run(func, funcD, funcD2, xL, xR):
"""
Draws func (function), funcD (derivative) and funcD@ (second derivative) in the given bounds (xL - xR)
If funcD is None (not provided) it is calculated with funcDer
If funcD2 is None (not provided) it is calculated with funcDer2
"""
xV = np.linspace(xL, xR, 200)
fV = np.fromiter((func(xi) for xi in xV), xV.dtype, count=len(xV))
if funcD is None:
fV_D = np.fromiter((funcDer(xi, func) for xi in xV), xV.dtype, count=len(xV))
else:
fV_D = np.fromiter((funcD(xi) for xi in xV), xV.dtype, count=len(xV))
if funcD2 is None:
fV_D2 = np.fromiter((funcDer2(xi, func) for xi in xV), xV.dtype, count=len(xV))
else:
fV_D2 = np.fromiter((funcD2(xi) for xi in xV), xV.dtype, count=len(xV))
critsX = []
critsY = []
prevSign = -2
for i in range(1, len(xV) - 1):
yL = fV[i - 1]
yM = fV[i]
yR = fV[i + 1]
if (yL > yM and yR > yM) or (yL < yM and yR < yM):
critsX.append(xV[i])
critsY.append(fV[i])
plot.scatter(xV, fV, color="#0064FF", s=1.5)
plot.scatter(xV, fV_D, color="orange", s=1.5)
plot.scatter(xV, fV_D2, color="#ff5050", s=1.5)
plot.scatter(critsX, critsY, color="black", s=16)
plot.grid(True)
plot.show()
if __name__ == "__main__":
run(
lambda x: 3 * x ** 2 + 2 * x + 1,
lambda x: 6 * x + 2,
lambda x: 6, -6, 6)
|
96d44108fdbf50e952d6d46b6d5c3761f28fb3e5 | masaya1123/PublicRepository | /notbose10_final/app.py | 28,195 | 3.53125 | 4 | import sqlite3
# Flaskからimportしてflaskを使えるようにする
from flask import Flask, session, render_template, request, redirect
import datetime
import json
# appという名前でFlaskアプリを作っていく!
app = Flask(__name__)
# シークレットキーの設定 sessionを使えるようにする
app.secret_key = "sunabaco"
# ルートの挙動調べる
@app.route("/")
def top_html():
return render_template("top.html")
# 新規登録
@app.route("/signup", methods=["GET"])
def signup_get():
# データベースと合わせる
# if "user_id" in session:
# return redirect("/main")
# else:
return render_template("signup.html")
@app.route("/signup", methods=["POST"])
def signup_post():
# if "user_id" in session:
# return redirect("/main")
# else:
# 入力フォームから値を取ってくる
name = request.form.get("name")
password = request.form.get("password")
email = request.form.get("email")
conn = sqlite3.connect("notbose.db")
c = conn.cursor()
c.execute("insert into user values(null,?,?,?)",
(name, email, password))
conn.commit()
c.execute("select userid from user where email=? and password=?",
(email, password))
# もってきたデータを入れるための変数
user_id = c.fetchone()
c.close()
print(user_id)
session["user_id"] = user_id[0]
return render_template("/add_newhabits.html")
# ログイン
@app.route("/login", methods=["GET"])
def login_get():
if "user_id" in session:
return redirect("/main")
else:
return render_template("login.html")
@app.route("/login", methods=["POST"])
def login_post():
# login.htmlに入力した名前とパスワードを取ってくる
email = request.form.get("email")
password = request.form.get("password")
# データベースに接続
conn = sqlite3.connect("notbose.db")
c = conn.cursor()
# 名前、パスワードと一致するIDを取得
c.execute("select userid from user where email=? and password=?",
(email, password))
# もってきたデータを入れるための変数
user_id = c.fetchone()
c.close()
print(user_id)
# IDが存在しなかった時
if user_id is None:
return render_template("login.html")
# 見つかった時はsessionを利用
else:
# fetchoneで取ってきたデータは(1,)となっているので、値だけを取り出す
session["user_id"] = user_id[0]
return redirect("/main")
# 習慣の追加add_newhabits
@app.route("/add_newhabits", methods=["GET"])
def add_newhabits_get():
# if "user_id" in session:
# return render_template("add_newhabits.html",)
# else:
# return redirect("/login")
return render_template("/add_newhabits.html")
@app.route("/add_newhabits", methods=["POST"])
def add_newhabits():
# if "user_id" in session:
#
# 入力フォームから値を取ってくる
user_id = session["user_id"]
task = request.form.get("task")
days = request.form.get("days")
conn = sqlite3.connect("notbose.db")
c = conn.cursor()
c.execute("insert into task (taskid,userid,task,days) values(null,?,?,?)",
(user_id, task, days))
#calendarテーブルに新しいtaskを追加する
c.execute("insert into calendar (taskid,day1,day2,day3,day4,day5,day6,day7,day8,day9,day10,day11,day12,day13,day14,day15,day16,day17,day18,day19,day20,day21,day22,day23,day24,day25,day26,day27,day28,day29,day30,day31) values(null,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)")
conn.commit()
c.close()
return redirect("/main")
@app.route("/edit/<int:id>")
def edit(id):
if "user_id" in session:
conn = sqlite3.connect("notbose.db")
c = conn.cursor()
c.execute("select task from task where taskid= ?", (id,))
task = c.fetchone()
c.close()
if task is not None:
# タプル(’を外すため・
task = task[0]
else:
return "タスクがありません"
item = {"id": taskid, "task": task}
return render_template("change_habits.html", task=item)
else:
return redirect("/main")
# 編集ボタンを押したら追加されてしまうのを、編集出来るようにする
# 新しくルートを作るaddのところを参考に
@app.route("/edit", methods=["POST"])
def edit_task():
user_id = session["user_id"]
task = request.form.get("task")
time = request.form.get("time")
days = request.form.get("days")
conn = sqlite3.connect("notbose.db")
c = conn.cursor()
c.execute("insert into task (taskid,userid,task,time,days) values(null,?,?,?,?)",
(user_id, task, time, days))
conn.commit()
c.close()
return redirect("/main")
@app.route("/main")
def main_task():
# user_idがsessionに入っているかどうか
if "user_id" in session:
# sessionからIDを取ってくる
user_id = session["user_id"]
conn = sqlite3.connect("notbose.db")
c = conn.cursor()
# ユーザーの名前を表示する
c.execute("select name from user where userid=?", (user_id,))
user_info = c.fetchone()
print(user_info)
# 現在のタスクを表示
c.execute(
"select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
print(task_now)
# user_idが登録しているタスクで終了しているものを取る
c.execute(
"select taskid,task,days from task where userid = ? and end=1", (user_id,))
task_list = []
# 値を入れるコード fetchallをrow に入れるのよ!データがある分だけ繰り返しますよ!
for row in c.fetchall():
task_list.append({"id": row[0], "task": row[1], "days": row[2]})
#ここにカレンダーのコードを挿入
# c.execute("select taskid from task where userid=?", (user_id,))
# task_now = c.fetchone()
c.execute('SELECT day1 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success1=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day2 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success2=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day3 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success3=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day4 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success4=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day5 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success5=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day6 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success6=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day7 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success7=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day8 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success8=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day9 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success9=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day10 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success10=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day11 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success11=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day12 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success12=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day13 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success13=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day14 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success14=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day15 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success15=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day16 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success16=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day17 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success17=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day18 FROM calendar where taskid = ?',(task_now[0],))#列名の頭に数字は使えない
succeess_failed=c.fetchone()[0]
conn.commit()
c.execute('SELECT day19 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success19=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day20 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success20=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day21 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success21=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day22 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success22=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day23 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success23=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day24 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success24=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day25 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success25=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day26 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success26=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day27 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success27=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day28 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success28=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day29 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success29=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day30 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success30=c.fetchone()[0]
print(task_now[0])
c.execute('SELECT day31 FROM calendar where taskid = ?',(task_now[0],))#これを31日分コピペ
success31=c.fetchone()[0]
print(task_now[0])
#ここにカレンダーのコードを挿入
#これを1~31日までコピペしてそれぞれ別の変数で定義
c.close()
print(task_list)
return render_template("/main.html", task_list=task_list, user_info=user_info, task_now=task_now, success1 = success1, success2 = success2, success3 = success3, success4 = success4, success5 = success5, success6 = success6, success7 = success7, success8 = success8, success9 = success9, success10 = success10, success11 = success11, success12 = success12, success13 = success13, success14 = success14, success15 = success15, success16 = success16, success17 = success17, succeess_failed = succeess_failed, success19 = success19, success20 = success20, success21 = success21, success22 = success22, success23 = success23, success24 = success24, success25 = success25, success26 = success26, success27 = success27, success28 = success28, success29 = success29, success30 = success30, success31 = success31,)
else:
return redirect("/login")
#青山追加
# これをコピペで1~31日まで作る
# サイトからdbに成果を反映するコード
now = datetime.datetime.now()
today='day'+str(now.day)
# today='day2'#後で消す
@app.route("/succeess", methods=["POST"])
def succeess():
if "user_id" in session:
if today == "day1":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day1 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day2":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day2 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day3":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day3 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day4":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day4 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day5":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day5 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day6":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day6 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day7":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day7 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day8":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day8 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day9":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day9 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day10":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day10 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day11":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day11 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day12":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day12 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day13":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day13 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day14":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day14 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day15":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day15 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day16":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day16 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day17":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day17 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day18":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
# c.execute("select taskid from calendar")
c.execute('update calendar set day18 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
#else ifで1~31日まで作成
elif today == "day19":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day19 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day20":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day20 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day21":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day21 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day22":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day22 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day23":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day23 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day24":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day24 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day25":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day25 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day26":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day26 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day27":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day27 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day28":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day28 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day29":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day29 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day30":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day30 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
elif today == "day31":
user_id = session["user_id"]
conn = sqlite3.connect('notbose.db')
c = conn.cursor()
c.execute("select taskid,task,time,days from task where userid=? and end is null order by taskid", (user_id,))
task_now = c.fetchone()
c.execute('update calendar set day31 = 1 where taskid = ?',(task_now[0],))
conn.commit()
conn.close()
else:
return render_template('login.html')
else:
return render_template("login.html")
return redirect("/main")
#青山追加
@app.route("/del/<int:id>")
def delete_task(id):
if "user_id" in session:
conn = sqlite3.connect("notbose.db")
c = conn.cursor()
# dbを削除する時
c.execute("delete from task where taskid=?", (id,))
# dbの書き換えをしたので、ライトチェンジズする
conn.commit()
c.close()
return redirect("/add_newhabits")
else:
return redirect("/login")
@app.route("/end/<int:id>")
def end_task(id):
if "user_id" in session:
conn = sqlite3.connect("notbose.db")
c = conn.cursor()
# dbのendカラムに1を入れる
c.execute("update task set end=1 where taskid=?", (id,))
# dbの書き換えをしたので、ライトチェンジズする
conn.commit()
c.close()
return redirect("/add_newhabits")
else:
return redirect("/login")
@app.route("/logout")
# sessionの中の値を出す(空っぽにする)=ログアウト
def logout():
session.pop("user_id", None)
return redirect("/")
@app.errorhandler(404)
def page_not_found(error):
return render_template('page_not_found.html'), 404
if __name__ == "__main__":
app.run(debug=True)
|
9904272efe1e47d4332e94fbb952c2951e1ba73e | skeerth1/Python-basics | /Functions.py | 376 | 3.921875 | 4 | # functions - starts with def
def print_max(a,b):
if a>b:
print('a is maximun')
elif a==b:
print('a is equal to b')
else:
print('b is maximum')
# directly pass the literal values
print_max(3,4)
x = 5
y = 7
# pass variables as arguments
print_max(x,y)
def sayHello(name='Sam'):
print(f'Hello {name}')
sayHello()
|
84e879ee20d5eaad43c34e35dc9712c87173368c | sgichuki/TidyTuesday-Py | /2021-08-24/lemurs.py | 1,046 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Fri Sep 17 13:21:42 2021
@author: warau
"""
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
#load data
lemurs = (
pd.read_csv("https://raw.githubusercontent.com/rfordatascience/tidytuesday/master/data/2021/2021-08-24/lemur_data.csv",encoding= 'unicode_escape'))
taxonomic_code = pd.read_csv("taxonomic_code.csv", encoding = 'Latin1')
#convert column names to lower case
taxonomic_code.columns = taxonomic_code.columns.str.lower()
#merge data frames to associate species name to taxon code
newlemurs = pd.merge(taxonomic_code, lemurs, on="taxon")
longevity = newlemurs[['common name','age_at_death_y']].groupby('common name').median()
longevity_sorted = longevity.sort_values('age_at_death_y')
#longevity.columns = longevity.columns.droplevel(0)
longevity_sorted.plot(kind='barh',color = ['green'],legend = False)
plt.title("Lemur longevity: median age at death by species")
plt.ylabel(" ")
plt.xlabel("Median age at death")
|
931c8c2b81f6fff19a9459d32f57529ea1c2e753 | kidoyen/Repository | /Project2/Versions/Version0/accessories_final.py | 18,464 | 3.796875 | 4 | from math import e, pi, cos, sin, sqrt, atan
from pygame import *
FPS=40 # Frames per second game will run at
screenwidth=500
screenheight=850
dt_strd=1/float(FPS) # time constant used in physics calculations
halfsinkwidth=80 # spacing of gap at bottom of screen (half this quantity is more convenient to work with)
randompos=50 # magnitude of randomness when choosing a random position
randomvel=300 # magnitude of randomness when choosing a random velocity
outline_thickness=1 # outline ball and flippers with 1 pixel of black
outline_color=(0,0,0)
# vector class converts a tuple into a vector with its head at the location of the tuple and tail at the origin
# used to keep track of position, velocity, acceleration, and used for collision detection
class vec(tuple):
def __add__(self,other):
return vec(x+y for x, y in zip(self,other))
def __mul__(self,c):
return vec(x*c for x in self)
def __rmul__(self,c):
return vec(x*c for x in self)
def __sub__(self,other):
return vec(x-y for x, y in zip(self,other))
def tup(self): # returns contents in tuple format
return (self[0],self[1])
def rtup(self): # rtup rounds the values to whole numbers first for display purposes
return (int(round(self[0])),int(round(self[1])))
def modulus(vec): # length of vector
return sqrt(vec[0]**2+vec[1]**2)
def modsq(vec): # square of length of vector
return (vec[0]**2+vec[1]**2)
def dist_between(first,second): # distance between two vectors
return modulus(first-second)
def unitv(angle_or_vec): # returns unit vector in direction of input vector or input angle
if type(angle_or_vec)==float:
return vec((cos(angle_or_vec),sin(angle_or_vec)))
else:
return angle_or_vec*(1/modulus(angle_or_vec))
def dot(self,other): # dot product
return (self[0]*other[0]+self[1]*other[1])
def cross(self,other): # signed magnitude of cross product (using right hand rule)
return(self[0]*other[1]-self[1]*other[0])
def unitperp(vector): # returns normalized vector perpendicular to input (using right hand rule)
return unitv(vec((-vector[1],vector[0])))
# ball constants
ball_rad=10
ball_mass=10
ball_charge=0
ball_bounce=0.7
ball_color=(155,155,155)
# ball class
class ball_obj:
def __init__(self,position,velocity,color=ball_color,radius=ball_rad,mass=ball_mass,charge=ball_charge,bounce=ball_bounce):
self.pos=vec(position) # position and velocity described with vectors
self.vel=vec(velocity)
self.col=color
self.rad=radius # how wide the balls will be drawn
self.mass=mass # mass of the ball
self.charge=charge # electric charge of the ball
self.bounce=bounce # describes how much velocity is preserved during collision
# forcefield class holds a function that accepts the state of the game as input
# and outputs the vector acceleration experienced by the ball
class force_field():
def __init__(self,function):
self.force=function
def grav(gamestate): # default gravity makes all objects accelerate at the same rate
g=500
return vec((0,g))
# border constants
borwi=20 # how wide to draw the borders
bordercolor=(0,0,255) # borders will be blue
# border class to define the objects that will serve as boundaries to the game
class Border():
def __init__(self,shape='rect',vertices=(),collision_info=[]):
self.shape=shape # default shape is a rectangle but other polygons can be implemented
self.vertices=vertices # tuple holding tuples describing the location of vertices
self.col=bordercolor
self.collision_info=collision_info # holds vectors describing the actual collision surfaces (more about this later in collision detection part)
# function that creates a list containing the default borders at the start of the game
def initializeBorder(borwi=borwi):
output=[]
vertices=((0,0),(borwi,screenheight)) # only two points needed to define a rectangle in pygame
collision_for_left=[[vec((borwi,0)),vec((0,screenheight))]]
leftside=Border('rect',vertices,collision_for_left) # this will be the vertical border on the left of the screen
output.append(leftside)
vertices=((screenwidth-borwi,0),(screenwidth,screenheight))
collision_for_right=[[vec((screenwidth-borwi,screenheight)),vec((0,-screenheight))]]
rightside=Border('rect',vertices,collision_for_right) # border on the right
output.append(rightside)
vertices=((0,0),(screenwidth,borwi))
collision_for_top=[[vec((screenwidth,borwi)),vec((-screenwidth,0))]]
topside=Border('rect',vertices,collision_for_top) # border on the ceiling
output.append(topside)
vertices=((0,screenheight-borwi),(screenwidth,screenheight))
collision_for_bottom=[[vec((0,screenheight-borwi)),vec((screenwidth,0))]]
bottomside=Border('rect',vertices,collision_for_bottom) # border on the bottom that was useful for early debugging
output.append(bottomside) # but is no longer needed due to the sink at the bottom of the screen
bottom_left_corner=(0,screenheight) # define the vertices of the left slope
bottom_right_corner=(int(screenwidth/2)-halfsinkwidth,screenheight)
top_corner=(0,int(screenheight/2))
vertices=(bottom_left_corner,bottom_right_corner,top_corner)
collision_for_left_slope=[[vec(top_corner),vec((int(screenwidth/2)-halfsinkwidth,int(screenheight/2)))]]
leftslope=Border('tri',vertices,collision_for_left_slope) # slopes are triangles
#output.append(leftslope)
bottom_right_corner=(screenwidth,screenheight) # vertices of right slope
bottom_left_corner=(int(screenwidth/2)+halfsinkwidth,screenheight)
top_corner=(screenwidth,int(screenheight/2))
vertices=(bottom_right_corner,bottom_left_corner,top_corner)
collision_for_right_slope=[[vec(bottom_left_corner),vec((int(screenwidth/2)-halfsinkwidth,-int(screenheight/2)))]]
rightslope=Border('tri',vertices,collision_for_right_slope)
#output.append(rightslope)
return output
# function to detect and resolve collisions between one border and one ball
def collision_detect_resolve(border,ball):
if border.collision_info: # first checks to see that collision information is defined
for bord_location in border.collision_info: # loops over all the sets of data for collision. All the borders in this version are effectively half-planes
# and so only need one set of data, but the capability for multifaced surfaces is there
ball_rel_pos=ball.pos-bord_location[0] # first vector in list is the actual location of the border so the position of the ball relative
# to the border can be calculated
bord_rel_pos=bord_location[1] # second vector in the list holds the border surface
dist=cross(ball_rel_pos,bord_rel_pos)/modulus(bord_rel_pos)-ball.rad # the cross product essentially calculated the distance between the center of the ball
# and the ray containing the surface, along the perpendicular. Then the radius of the ball is factored in
# to correct for the treatment of the ball as a point
if dist<0:
parallel_comp=dot(bord_rel_pos,ball_rel_pos)/modsq(bord_rel_pos) # the distance being negative doesn't necessarily indicate a collision
if parallel_comp>0 and parallel_comp<1: # this dot product calculates how far the ball is parallel to the surface,
# if this quantity is >0 or <1 then there is a collision
direction=unitperp(bord_rel_pos) # this is the direction of the "force" applied by the border.
ball.pos+=direction*dist # the position of the ball is offset so that it is no longer intersecting the border.
new_vel=ball.vel-2*direction*dot(ball.vel,direction)*ball.bounce # the velocity of the ball is offset such that the component perpendicular to the border
ball.vel=new_vel # is reversed, but is slower than before due to energy dissipation
# creates a range of floats from initial to final (inclusive), with number of elements equal to length
def my_range(initial,end,length):
output=[]
increment=float((end-initial))/(length-1)
for i in range(length):
output.append(initial+i*increment)
return output
# flipper constants
flipper_increment=pi/10 # how much to rotate the flipper per update
flippercolor=(155,155,155)
axis_rad=20 # radius of the circle surrounding where the flipper pivots
end_rad=11 # radius of the circle at the end of the flipper
f_length=120 # length from center of axis circle to center of end circle
num_increments=6 # how many different angles the flippers can have
extra_bounce=1.2 # how much extra bounce to impart (otherwise the ball would always lose energy from collisions from walls)
# flippers used to hit the ball (see drawing on design documents)
class flipper():
def __init__(self,axis_pos,axis_rad,length=f_length,end_rad=end_rad,angle_range=[0],key=None):
self.axis_pos=axis_pos # vector describing center of the axis circle
self.axis_rad=axis_rad
self.length=length
self.end_rad=end_rad
self.angle_index=0 # describes the angle the flipper is at from the list of angles in range
self.range=angle_range
self.key=key # key to press to move flipper
self.alpha=atan(float(axis_rad-end_rad)/length) # describes slope between surface tangent to circles and the line connecting the centers of the circles
# function that creates a list of default flippers at the start of the game
def initializeFlippers():
output=[]
left_axis=vec((screenwidth/3-halfsinkwidth,screenheight*3/4))
left_range=my_range(pi/8,-pi/8,num_increments) # max angle will be 45 degrees relative to the horizontal and the resting angle is -45 degrees
left_key=K_v # use the K key to control this flipper
leftflipper=flipper(left_axis,axis_rad,f_length,end_rad,left_range,left_key)
output.append(leftflipper)
right_axis=vec((screenwidth*2/3+halfsinkwidth,screenheight*3/4))
right_range=my_range(-pi/8,pi/8,num_increments) # range is reversed because right flipper has opposite orientation than left flipper
right_key=K_m
rightflipper=flipper(right_axis,axis_rad,-f_length,end_rad,right_range,right_key) # length is made negative for the same reason
output.append(rightflipper)
return output
# updates position of flipper
def update_flipper(flipper, keys_down):
if keys_down[flipper.key]: # if the correct key is pressed
if flipper.angle_index<num_increments-1: # and the angle isn't at its maximum
flipper.angle_index+=1 # the flipper will rotate upwards.
elif flipper.angle_index>0: # if the key is not pressed and the angle isn't at its maximimum
flipper.angle_index-=1 # the flipper will rotate back downwards.
# this function handles the math to accurately draw the flipper
def draw_flipper(flipper,screen):
axis_pos=flipper.axis_pos
angle=flipper.range[flipper.angle_index]
end_pos=axis_pos+flipper.length*unitv(angle)
axis_offset=flipper.axis_rad*unitv(angle+pi/2)
axis_topvert=axis_pos+axis_offset
axis_bottomvert=axis_pos-axis_offset
end_offset=flipper.end_rad*unitv(angle+pi/2)
end_topvert=end_pos-end_offset
end_bottomvert=end_pos+end_offset
vertices=(axis_topvert.rtup(),axis_bottomvert.rtup(),end_topvert.rtup(),end_bottomvert.rtup()) # describes the non-circle body of the flipper
draw.polygon(screen,flippercolor,vertices) # draws body
draw.polygon(screen,outline_color,vertices,outline_thickness) # and outlines it.
draw.circle(screen,flippercolor,axis_pos.rtup(),flipper.axis_rad) # draws axis circle
draw.circle(screen,outline_color,axis_pos.rtup(),flipper.axis_rad,outline_thickness)
draw.circle(screen,flippercolor,end_pos.rtup(),flipper.end_rad) # draws end circle
draw.circle(screen,outline_color,end_pos.rtup(),flipper.end_rad,outline_thickness)
# handles the collisions between a ball and a flipper
def collision_flipper(flipper,ball): # uses similar method as the borders
angle=flipper.range[flipper.angle_index]
top_displacement=flipper.axis_pos+flipper.axis_rad*unitv(angle+pi/2)
bottom_displacement=flipper.axis_pos+flipper.axis_rad*unitv(angle-pi/2)
top_surface=flipper.length*unitv(angle-flipper.alpha)
bottom_surface=flipper.length*unitv(angle+flipper.alpha)
ball_rel_pos=ball.pos-top_displacement
dist=cross(ball_rel_pos,top_surface)/modulus(top_surface)-ball.rad
if dist<0 and dist>2*flipper.end_rad: # gives the top of the flipper some width
parallel_comp=dot(top_surface,ball_rel_pos)/modsq(top_surface)
if parallel_comp>0 and parallel_comp<1:
direction=unitperp(top_surface)
ball.pos+=direction*dist
new_vel=ball.vel-2*direction*dot(ball.vel,direction)*(extra_bounce+ball.bounce+abs(dist)/15)*0.5 # gives the ball some extra velocity, incorporating extra bounce,
ball.vel=new_vel # regular bounce, and the distance of intersection
ball_rel_pos=ball.pos-bottom_displacement
dist=cross(ball_rel_pos,bottom_surface)/modulus(bottom_surface)
if abs(dist)<ball.rad: # bottom of the flipper is considered as a thin line
parallel_comp=dot(bottom_surface,ball_rel_pos)/modsq(bottom_surface)
if parallel_comp>0 and parallel_comp<1:
direction=unitperp(bottom_surface)
ball.pos+=direction*dist
new_vel=ball.vel-2*direction*dot(ball.vel,direction)*(extra_bounce+ball.bounce+abs(dist)/15)*0.5
ball.vel=new_vel
axis_to_ball=flipper.axis_pos-ball.pos
distance=modulus(axis_to_ball)-ball.rad-flipper.axis_rad
if distance<0:
direction=unitv(axis_to_ball)
ball.pos+=direction*distance
new_vel=ball.vel-direction*dot(ball.vel,direction)*(extra_bounce+ball.bounce)
ball.vel=new_vel
end_to_ball=flipper.axis_pos+flipper.length*unitv(angle)-ball.pos
distance=modulus(end_to_ball)-ball.rad-flipper.end_rad
if distance<0:
direction=unitv(axis_to_ball)
ball.pos+=direction*distance
new_vel=ball.vel-direction*dot(ball.vel,direction)*(extra_bounce+ball.bounce)
ball.vel=new_vel
# if the ball enters a "sink" object, it will be lost
class sink():
def __init__(self,shape='rect',location=(0,screenheight-borwi,screenwidth,screenheight),color=(0,0,0)):
self.shape=shape # shape supports rectangles and circles
self.dimensions= (shape!='rect') and location or Rect(location) # dimensions will be handled depending on if it is a rectangle or not
self.color=color
# method which checks if the ball is inside the sink
def is_in_sink(self,ball):
if self.shape=='rect':
return self.dimensions.collidepoint(ball.pos.rtup()) # checks if the center of the ball is inside the rectangle
if self.shape=='circ':
return modulus(ball.pos-self.dimensions[0])<self.dimensions[1] # checks if the center of the ball is inside the circle
else:
return False # other shapes not supported yet
# initializes the default sink at the bottom of the screen
def initializeSinks():
output=[]
bottom_sink=sink(location=(0,screenheight-2*borwi,screenwidth,screenheight))
output.append(bottom_sink)
return output
# checks to see if a given ball is in any of the sinks, if so it returns True
def remove_ball(ball,sinks):
for sink in sinks:
if sink.is_in_sink(ball):
return True
return False
|
4b78c16e930c1c1abaaca88ffbb76ecdcbc98454 | andreioprisan/AI | /HW3/Problem 2/problem2_DecisionTree.py | 1,781 | 3.671875 | 4 | # Braden Katzman - bmk2137
# Columbia University
# Artificial Intelligence Summer 2016
# HW3 - Question 2
# Description:
# Decision Tree classifier with param option max_depth
from sklearn import tree
from sklearn.cross_validation import cross_val_score
from sklearn.metrics import accuracy_score
# Builds and returns a decision tree classifier given parameter max_depth
def decisionTree(max_depth):
print "\nbuilding decision tree classifier with max_depth={max_depth}".format(max_depth=max_depth)
dt = tree.DecisionTreeClassifier(max_depth=max_depth)
return dt
# Trains and returns a trained SVM given parameters SVM, support vector (training), and y (labels)
def trainDT(dt, sv, y):
print "\ntraining Logistic Regression Classifier"
# cross validate 5 times
scores = cross_val_score(dt, sv, y, cv=5)
print scores # NEED TO REPORT THIS IN THE WRITE UP
# fit the data to the labels
dt.fit(sv, y)
return dt
# Tests a Decision Tree Classifier on testing data and returns the prediction labels given parameters dt and v (testing data vector)
def runDT(dt, v):
print "\npredicting labels with Logistic Regression Classifier"
predictions = dt.predict(v)
return predictions
# runs cross validation and optimizes for different c
def runCVAndOptimize(sv, y, x_test, y_true):
print "\nrunning cross validation and optimizing"
max_depth = [1., 2., 3., 4., 5., 6., 7., 8., 9., 10.]
# for each c value
for i in range(10):
print 'Decision Tree max_depth=' + repr(max_depth[i])
dt = decisionTree(max_depth[i])
trainDT(dt, sv, y)
accuracyTest(dt, "Decision Tree", x_test, y_true)
# makes predictions and prints the accuracies for the various SVMs
def accuracyTest(dt, type_, x_test, y_true):
print type_ + " accuracy: " + repr(accuracy_score(y_true, runDT(dt, x_test))) |
4e68bbd2abf13d31f8297d4899d3554a581c3d9d | Mirannam/while_for | /task7.py | 302 | 3.875 | 4 | names = ('Максат','Лязат','Данияр','Айбек','Атай','Салават','Адинай','Жоомарт','Алымбек','Эрмек','Дастан','Бекмамат','Аслан',)
names1 = []
for i in range(1,13,2):
names1.append(names[i])
names1= set(names1)
print(names1)
|
7de5f90f71e3925b6f031374ceade16dcab7aa98 | zeel1234/mypython | /ma007/Practical 9/Personclass.py | 2,580 | 3.75 | 4 | class Person:
def __init__(self,nm = "",gen = "",bdat = 1996):
self.name = nm;
self.bdate = bdat;
self.gender = gen;
def set(self,nm = "",gen = "",bdat = 1996):
self.name = nm;
self.bdate = bdat;
self.gender = gen;
def get(self):
return (self.name,self.gen,self.bdate)
def show(self):
print("Name : ",self.name)
print("Birth date : ",self.bdate)
print("Gender : ",self.gender)
#
class Student(Person):
def __init__(self,nm = "",gen="",bdat = 1996,sem = 0,py_mark = 0,j_mark = 0,php_mark = 0):
self.semester = sem;
self.py_marks = py_mark;
self.j_marks = j_mark;
self.php_marks = php_mark;
super().__init__(nm,gen,bdat)
def set(self,nm = "",gen = "",bdat = 1996,sem = 0,py_mark = 0,j_mark = 0,php_mark = 0):
self.semester = sem;
self.py_marks = py_mark;
self.j_marks = j_mark;
self.php_marks = php_mark;
super().set(nm,gen,bdat)
def get(self):
super().get()
return (sem,py_mark,j_mark,php_mark)
def calc_total(self):
Total = self.py_marks + self.j_marks + self.php_marks;
return Total;
def calc_per(self):
Percentage = self.calc_total()//3
return Percentage
def calc_grade(self):
percent = self.calc_per()
if percent >= 90 :
Grade = "A";
elif percent >= 70 and percent <90:
Grade = "B";
elif percent >=50 and percent <70:
Grade = "C";
else:
Grade = "Fail";
return Grade;
def show(self):
print("semester : ",self.semester)
print("Total : ",self.calc_total())
print("Percentage : ",self.calc_per())
print("Grade : ",self.calc_grade())
super().show()
#
s1 = Student()
st_name = input("Enter name : ")
st_birthdate = int(input("enter birthdate : "))
st_gender = input("enter gender : ")
st_sem = int(input("enter semester : "))
st_python = int(input("enter python marks : "))
st_java = int(input("enter java marks : "))
st_php = int(input("enter php marks : "))
s1.set(st_name,st_birthdate,st_gender,st_sem,st_python,st_java,st_php);
s1.show();
class Employee:
def __init__(self,nm = "",gen="",bdat = 1996,basic_sal=0,da=0.5,hra=0.5,total_sal=0):
self.basic_salary = basic_sal
self.da = da;
self.hra = hra;
self.total_sal = total_sal
super().__init__(nm,gen,bdat)
|
85aefd0c245c502db7c5bf62bdfdb62084e84bd4 | salemgyn/python-3montes | /3montes.py | 5,774 | 3.59375 | 4 | #coding: utf-8
#! /usr/bin/env python
#
#Autor: Melky-Salém <msalem@globo.com>
#Descrição: 3 montes(ainda não descobri o nome) é um jogo de lógica
# a regra é, voce deve escolher um monte e tirar quantas
# peças quizer, desde 1 até todas, com isso em jogo até
# dois montes vão sumir, quem pegar a ultima peça ganha
from random import randint
import sys
import time
class tresMontes(object):
debug = False
montes = range(3) # define montes
qtd = [0,0,0]
jogaPlayer1 = True # define de quem é a vez da jogada
KAnalises = 0
Analises = 0
def __init__(self,qtd=[10,15,20]): # define 10,15,20 como valores iniciais ou então
self.montes[0] = qtd[0] # os parametros que foram passados
self.montes[1] = qtd[1]
self.montes[2] = qtd[2]
self.qtd = qtd
jogaPlayer1 = True
if len(sys.argv) > 1:
if sys.argv[1] == 'debug':
debug = True
def reseta(self):
self.__init__(self.qtd)
def acabou(self):
if self.montes[0]+self.montes[1]+self.montes[2] == 0:
return True
return False
def acaba(self,jogo):
if jogo[0]+jogo[1]+jogo[2] == 0:
return True
return False
def tira(self,monte,qtd):
if self.montes[monte] >= qtd:
self.montes[monte] -= qtd
return True
else:
return False
def imprime(self):
if self.montes[0] > 0: print 'Monte 1:','o'*self.montes[0]
if self.montes[1] > 0: print 'Monte 2:','o'*self.montes[1]
if self.montes[2] > 0: print 'Monte 3:','o'*self.montes[2]
def move_ai(self):
atual = list(self.montes)
if atual[0]+atual[1]+atual[2]<=10:
nega = self.negamax(atual,1,10)
melhor = [nega[1],nega[2]]
else:
if len(self.nao_vazios(atual)) == 3:
opcoes = self.deixa_diferente(atual)
melhor = opcoes[randint(1,len(opcoes))]
else:
melhor = self.deixa_igual(atual)
self.debuga('\r'*10+'Analises: '+str(self.Analises))
self.KAnalises = 0
self.Analises = 0
return melhor
def nao_vazios(self,atual):
nao_vazios = []
if atual[0] > 0: nao_vazios.append(0)
if atual[1] > 0: nao_vazios.append(1)
if atual[2] > 0: nao_vazios.append(2)
return nao_vazios
def debuga(self,texto):
if self.debug: print texto
def deixa_diferente(self,jogo):
opcoes = []
for i in range(3):
for j in range(1,jogo[i]+1):
jogo[i] -= j
if jogo[self.outros_dois(i)[0]] != jogo[i] and jogo[self.outros_dois(i)[1]] != jogo[i]:
opcoes.append([i,j])
jogo[i] += j
return opcoes
def deixa_igual(self,jogo):
if jogo[self.nao_vazios(jogo)[0]] > jogo[self.nao_vazios(jogo)[1]]: return self.nao_vazios(jogo)[0],jogo[self.nao_vazios(jogo)[0]]-jogo[self.nao_vazios(jogo)[1]]
elif jogo[self.nao_vazios(jogo)[1]] > jogo[self.nao_vazios(jogo)[0]]: return self.nao_vazios(jogo)[1],jogo[self.nao_vazios(jogo)[1]]-jogo[self.nao_vazios(jogo)[0]]
else: return self.nao_vazios(jogo)[0],jogo[self.nao_vazios(jogo)[0]]
def outros_dois(self,monte):
if monte == 0: return 1,2
if monte == 1: return 0,2
if monte == 2: return 0,1
def negamax(self,atual,jogador,profundidade):
self.Analises += 1
adversario = 1 if jogador == 2 else 1
if self.acaba(atual) or profundidade == 0:
self.debuga(str(profundidade)+' : acabou com pc') if jogador == 1 else self.debuga(str(profundidade)+': acabou com player')
if jogador:
return 1,None,None
else:
return -1,None,None
else:
value = -100
bestValue = -100
bestMont = -1
bestQtd = -10
for i in self.nao_vazios(atual):
for j in range(1,atual[i]+1):
atual[i] -= j
self.debuga(str(profundidade)+' : pc') if jogador == 1 else self.debuga(str(profundidade)+' : player')
self.debuga(str(profundidade)+' : testando monte '+str(i+1)+' quant '+str(j))
if atual[0] > 0: self.debuga(str(profundidade)+' : Monte 1: '+'o'*atual[0])
if atual[1] > 0: self.debuga(str(profundidade)+' : Monte 1: '+'o'*atual[1])
if atual[2] > 0: self.debuga(str(profundidade)+' : Monte 1: '+'o'*atual[2])
value = -self.negamax(atual,adversario,profundidade-1)[0]
self.debuga(str(profundidade)+' : valor '+str(value))
if value > bestValue:
self.debuga(str(profundidade)+' : melhor agora eh '+str(value)+' '+str(i)+' '+str(j))
bestValue = value
bestMont = i
bestQtd = j
atual[i] += j
self.debuga('\n')
self.debuga(str(profundidade)+' : '+str(jogador)+' '+str(bestValue)+' '+str(bestMont)+' '+str(bestQtd))
return bestValue,bestMont,bestQtd
def inicia(self):
print 'Jogo dos 3 Montes(Ainda não sei o nome)'
print '*'*80
print '**','Regra: O jogo e jogado entre duas pessoas, onde cada um deve selecionar um **'
print '**',' monte e tirar quantas pecas quiser, quem pegar a ultima peça perde **'
print '*'*80
print '**','Pressione CTRL+C para sair do jogo **'
print '*'*80
while True:
while not self.acabou():
self.imprime()
if self.jogaPlayer1:
print 'Eh a vez de PC jogar.'
move_pc = self.move_ai()
print 'PC do monte',move_pc[0]+1,'tirarei',move_pc[1]
time.sleep(2)
self.tira(move_pc[0],move_pc[1])
self.jogaPlayer1 = False
else:
print 'Eh a vez de Player jogar.'
monte = 0
while monte not in [1,2,3] or self.montes[monte-1] <= 0:
try:
monte = int(raw_input('Escolha um dos Montes: '))
except(ValueError,TypeError):
pass
qtd = 0
while qtd not in range(1,self.montes[monte-1]+1):
try:
qtd = int(raw_input('Escolha a quantidade (entre 1 e '+str(self.montes[monte-1])+'): '))
except(ValueError,TypeError):
pass
self.tira(monte-1,qtd)
self.jogaPlayer1 = True
vencedor = 'Player' if not self.jogaPlayer1 else 'PC'
print vencedor,'foi o vencedor.'
raw_input()
self.reseta()
tresmontes = tresMontes([10,20,30])
tresmontes.inicia() |
d5202858c2b27c4e45c4066f373bd4c2dc65f04e | sabzi1984/Intro-to-Algorithms | /Dijkstra with heapq.py | 1,579 | 3.5625 | 4 | import heapq
def val(pair): return pair[0]
def id(pair): return pair[1]
def dijkstra_heapq(G,v):
heap = [ [0, v] ]
dist_so_far = {v:[0, v]}
final_dist = {}
while len(final_dist) < len(G):
while True:
w = heapq.heappop(heap)
node = id(w)
dist = val(w)
if node != 'REMOVED':
del dist_so_far[node]
break
final_dist[node] = dist
for x in G[node]:
if x not in final_dist:
new_dist = dist + G[node][x]
new_entry = [new_dist, x]
if x not in dist_so_far:
dist_so_far[x] = new_entry
heapq.heappush(heap, new_entry)
elif new_dist < val(dist_so_far[x]):
dist_so_far[x][1] = "REMOVED"
dist_so_far[x] = new_entry
heapq.heappush(heap, new_entry)
return final_dist
def make_link(G, node1, node2, w):
if node1 not in G:
G[node1] = {}
if node2 not in G[node1]:
(G[node1])[node2] = 0
(G[node1])[node2] += w
if node2 not in G:
G[node2] = {}
if node1 not in G[node2]:
(G[node2])[node1] = 0
(G[node2])[node1] += w
return G
(a,b,c,d,e,f,g) = ('A', 'B', 'C', 'D', 'E', 'F', 'G')
triples = ((a,c,3),(c,b,10),(a,b,15),(d,b,9),(a,d,4),(d,f,7),(d,e,3),
(e,g,1),(e,f,5),(f,g,2),(b,f,1))
G = {}
for (i,j,k) in triples:
make_link(G, i, j, k)
dist=dijkstra_heapq(G, a)
print(dist[e])
print(dist['E'])
|
a6d3d5804930d20e5a9688dc546a083bd10cb9f9 | shenjinrong0901/python_work | /学习阶段历程/homework5.2.py | 520 | 3.609375 | 4 | car='subaru'
print("Is car='subaru'? I predict Ture.")
print(car=='subaru')
print("Is car='audi'? I predict False.")
print(car=="bmw")
print("\n")
name='harden'
print("Is the most value player in NBA harden? I predict Ture.")
print(name=='harden')
print("Is the most value player in NBA james? I predict False.")
print(name=='james')
print("\n")
city='shanghai'
print("Is beijing my favourite city? I don't think so.")
print(city=='beijing')
print("Is shanghai my faourite city? I do think so.")
print(city=='shanghai')
|
8aeb9bf06e38802a130c2c4b2b69a01e4e80adaa | Iiridayn/sample | /Coderbyte/42-NumberSearch.py | 454 | 3.890625 | 4 | # Challenge: sum single digit numbers in string / by # letters (not chars). 10 points, 8 mins
# I didn't know about sum(array) yet
def NumberSearch(str):
nums = filter(lambda c: c.isdigit(), str)
letters = filter(lambda c: c.isalpha(), str)
sum = 0
for x in nums:
sum += int(x)
return int(round(float(sum)/len(letters)))
# keep this function call here
# to see how to enter arguments in Python scroll down
print NumberSearch(raw_input())
|
ec980ca61ac6441501bc3d4f1a4753313f758279 | leeson9394/learngit | /Reverse_number_v2.py | 320 | 3.609375 | 4 | import sys
input_num=input("Enter an integer N that 1 <= N <= 1000000000: ")
if 1 <= input_num <= 1000000000
bin_input=[int(i) for i in str(bin(input_num))[2:]]
bin_input.reverse()
bin_output=int(''.join(map(str,bin_input)),2)
print "Output integer: ",bin_output
else:
print "Input number not in range" |
5335785ca1e92d1b5fdc31818659c42fc8223918 | gaohaoning/leetcode_datastructure_algorithm | /LeetCode/Tree/98.py | 4,494 | 4.15625 | 4 | #!/usr/bin/env python
# coding:utf-8
"""
98. 验证二叉搜索树
给定一个二叉树,判断其是否是一个有效的二叉搜索树。
假设一个二叉搜索树具有如下特征:
节点的左子树只包含小于当前节点的数。
节点的右子树只包含大于当前节点的数。
所有左子树和右子树自身必须也是二叉搜索树。
示例 1:
输入:
2
/ \
1 3
输出: true
示例 2:
输入:
5
/ \
1 4
/ \
3 6
输出: false
解释: 输入为: [5,1,4,null,null,3,6]。
根节点的值为 5 ,但是其右子节点值为 4 。
"""
# ================================================================================
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
"""
方法1:中序遍历后排序(效率较低)
"""
class Solution(object):
def inorder(self, root):
"""
中序遍历
"""
if root is None:
return []
return self.inorder(root.left) + [root.val] + self.inorder(root.right)
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
inorder = self.inorder(root)
# print inorder
# print list(sorted(inorder))
# print inorder == sorted(inorder)
# print inorder == list(sorted(inorder))
# print inorder == list(sorted(set(inorder)))
# return inorder == list(sorted(inorder))
# 此处需要处理成 set,因为BST要求孩子节点跟父节点的关系必须是小于和大于,不允许有等于的情况。
# set 可以将值相等的节点去重
return inorder == list(sorted(set(inorder)))
# ================================================================================
"""
方法2:
递归判断
注意:
BST 要求根节点左/右子树所有节点的值小于/大于根节点的值,
所以逐个节点遍历时只比较每个根节点和左右孩子节点是不够的!
必须通过极限值加以检查!
例如:
10
/ \
5 15
/ \
6 20
Complexity Analysis
Time complexity : O(N) since we visit each node exactly once.
Space complexity : O(N) since we keep up to the entire tree.
"""
class Solution(object):
def isValid(self, node, vmin, vmax):
# 注意 节点值可能为零,所以用作判断时不能直接用来做 bool 型判断,必须用 x is not None
if vmin is not None and vmin >= node.val:
return False
if vmax is not None and vmax <= node.val:
return False
ret_left = self.isValid(node.left, vmin, node.val) if node.left else True
ret_right = self.isValid(node.right, node.val, vmax) if node.right else True
return ret_left and ret_right
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
return self.isValid(root, None, None)
# ================================================================================
"""
方法3:
Iteration
The above recursion could be converted into iteration, with the help of stack.
DFS would be better than BFS since it works faster here.
"""
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root is None:
return True
stack = [(root, None, None), ]
while stack:
node, low, high = stack.pop()
if node.left:
if node.left.val >= node.val:
return False
if low and node.left.val <= low:
return False
stack.append((node.left, low, node.val))
if node.right:
if node.right.val <= node.val:
return False
if high and node.right.val >= high:
return False
stack.append((node.right, node.val, high))
return True
# ================================================================================
# ================================================================================
root = TreeNode(1)
right = TreeNode(1)
root.right = right
so = Solution()
print so.isValidBST(root)
|
6b7d9a33a03f003c8d368cedafbc906efba81e6f | chacham/learn-algorithm | /acmicpc.net/10866/10866.py | 2,287 | 3.65625 | 4 | class deque:
def __init__(self, size):
self._start = 0
self._end = 0
self._size = 0
self._maxSize = size
self._deque = [None] * size
def push_front(self, item):
if self._size >= self._maxSize:
return
self._deque[self._start] = item
self._start -= 1
if self._start < 0:
self._start += self._maxSize
self._size += 1
def pop_front(self):
if self._size <= 0:
return -1
self._start += 1
if self._start >= self._maxSize:
self._start -= self._maxSize
self._size -= 1
return self._deque[self._start]
def push_back(self, item):
if self._size >= self._maxSize:
return
self._end += 1
if self._end >= self._maxSize:
self._end -= self._maxSize
self._deque[self._end] = item
self._size += 1
def pop_back(self):
if self._size <= 0:
return -1
ret = self._deque[self._end]
self._end -= 1
if self._end < 0:
self._end += self._maxSize
self._size -= 1
return ret
def size(self):
return self._size
def empty(self):
return True if self._size == 0 else False
def front(self):
if self._size <= 0:
return -1
tmp = self._start + 1
if tmp >= self._maxSize:
tmp -= self._maxSize
return self._deque[tmp]
def back(self):
if self._size <= 0:
return -1
return self._deque[self._end]
if __name__ == "__main__":
N = int(input())
mydeq = deque(N)
for n in range(N):
op = input().split()
#print(mydeq._deque)
if op[0] == "push_front":
mydeq.push_front(op[1])
elif op[0] == "push_back":
mydeq.push_back(op[1])
elif op[0] == "pop_front":
print(mydeq.pop_front())
elif op[0] == "pop_back":
print(mydeq.pop_back())
elif op[0] == "size":
print(mydeq.size())
elif op[0] == "empty":
print(1 if mydeq.empty() else 0)
elif op[0] == "front":
print(mydeq.front())
elif op[0] == "back":
print(mydeq.back()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.