text
stringlengths 37
1.41M
|
---|
def len(iterable):
return sum(1 for x in iterable)
def count(iterable, element):
return sum(1 for x in iterable if x == element)
def count_if(iterable, predicate):
return sum(1 for x in iterable if predicate(x))
|
import os,sys
a = 5
b = 3
st = "a > b" if a > b else "a < b"
print(st)
print("a > b") if a > b else print("a < b")
c = 6
d = 6
print("c > d") if c > d else (print("c < d") if c < d else print("c == d"))
#st = print("crazyit"); x = 20 if a > b else ""
st = x = 20; print("crazyit") if a > b else ""
print(st)
print(x)
st = 20, print("crazyit") if a > b else ""
print(st[0])
print(st[1])
a_tuple = ("tuple...",)
b_tuple = ("str...")
print(type(a_tuple))
print(type(b_tuple))
a = {1, "c", 1, (1, 2, 3),"c"}
for ele in a:
print(ele, end=" ")
print("")
str1 = "人生苦短,我用Python" #utf-8汉字和标点符号占三个字节,英文字符占1个字节
print(len(str1.encode()))
print(len(str1.encode("gbk"))) #gbk汉字和标点符号占2个字节, 英文占1个字节
data = [5,8,4,1]
for i in range(len(data) - 1):
for j in range(len(data) - i - 1):
if(data[j] > data[j+1]):
data[j], data[j+1] = data[j+1], data[j]
print("排序后:", data)
###列表,元祖,字典,集合推导式
dictdemo = {"1":1, "2":2, "3":3}
newdemo1 = {x for x , y in dictdemo.items() if y >= 2}
print(newdemo1)
newdemo2 = {x for x in dictdemo.values() if x >= 2}
print(newdemo2)
newdemo3 = {x for x in dictdemo.keys()}
print(newdemo3)
reverse_demo = {v:k for k,v in dictdemo.items()}
print(reverse_demo)
## zip() 函数
books = ["java讲义", "python讲义", "c讲义"]
prices = [30,60]
for book, price in zip(books, prices):
print("{0}的价格是:{1}".format(book, price))
## sorted()
a = [20, 30, -1.2, 3.5, 90]
sorted_list = sorted(a)
print(sorted_list)
sorted_list = sorted(a, reverse=True)
print(sorted_list)
b = ["f","cra","sd","dfsdfds","1d"]
sorted_list = sorted(b, key=len) #key=len,根据字符串长度进行从小到大排序
print(sorted_list)
sorted_list = sorted(b, key=len, reverse=True) #key=len,根据字符串长度进行从小到大排序,再倒排
print(sorted_list)
## reversed()
c = ["a",20,"fkit",1]
reversed_list = [x for x in reversed(c)]
print(reversed_list)
############################################################################################
import traceback
## try except else finally
def foo():
fis = None
try:
fis = open("a.txt")
except ValueError:
print("数值错误")
except ArithmeticError:
print("算数错误")
except OSError as e:
print(e.strerror)
return #执行return语句后仍然会执行下面的finally块代码
#os._exit(1) #退出python解释器, 则不会执行下面的finally块代码
except Exception as e:
print("未知异常")
print(e.args) #访问异常的错误编号和详细信息
print(e.errno) #访问异常的错误编号
print(e.strerror) #访问异常的详细信息
except :#不带任何参数的except必须放到最后一个
print(sys.exc_info()) #返回type, value, traceback
traceback.print_tb(sys.exc_info()[2]) #输出信息中包含了更多的异常信息,包括文件名、抛出异常的代码所在的行数、抛出异常的具体代码
traceback.print_exc() #捕捉异常,并将异常传播信息输出控制台
traceback.print_exc(file=open('log.txt', 'a')) #捕捉异常,并将异常传播信息输出指定文件中
else:
print("没有出现异常,程序正常执行...")
finally:
print("资源回收块")
if fis is not None:
try:
fis.close()
except OSError as ioe:
print(ise.strerror)
print("执行finally块里的资源回收!")
foo()
## raise 手动抛出一个异常
def f01():
try:
mtd(8)
except Exception as e:
print("程序出现异常:", e)
#mtd(3) #若不捕获程序抛出的异常,会导致程序终止
def mtd(a):
if a < 5:
raise
if a > 6:
raise ValueError("a的值大于0, 不符合要求")
f01()
### 自定义异常类
class SelfExceptionError(Exception):
print("自定义异常类!")
try:
raise SelfExceptionError()
except SelfExceptionError:
print("自定义的异常")
class InputError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return ("{} is invalid input.".format(self.value))
try:
raise InputError(1)
except InputError as err:
print("error: {}".format(err))
import logging
#DEBUG, INFO, WARNING, ERROR, CRITICAL
logging.disable(logging.WARNING) #禁止该级别以及更低级别的所有日志消息
logging.basicConfig(level=logging.DEBUG, format="%(asctime)s-%(levelname)s - %(message)s")
logging.debug("Start of program.")
logging.info("Start of program.")
logging.warning("Start of program.")
logging.error("Start of program.")
logging.critical("Start of program.")
#将日志信息追加写入到文件,既能使屏幕保持干净,又能保存信息
logging.basicConfig(filename="logging.txt", level=logging.DEBUG, format="%(asctime)s-%(levelname)s - %(message)s")
############################################################################################
### super()
class Employee: #新式类,所有类都隐式继承object类
#class Employee(object): #与上一行代码效果相同,object 作为所有基类的祖先
def __init__(self, salary):
self.salary = salary
def work(self):
print("普通员工正在写代码, 工资是:", self.salary)
class Customer(object): #新式类,所有类都隐式继承object类
def __init__(self, favorite, address):
self.favorite = favorite
self.address = address
def info(self):
print("我是一个顾客,我的爱好是%s, 地址是%s" %(self.favorite, self.address))
class Manager(Employee, Customer):
def __init__(self, salary, favorite, address):
super().__init__(salary)
#super(Manager, self).__init__(salary) #与上一行代码效果相同
Customer.__init__(self, favorite, address)
print("--Manager 的构造方法--")
m = Manager(25000, "IT产品", "广州")
m.work()
m.info()
###super()
class Animal(object):
def __init__(self, name):
self.name = name
def greet(self):
print("Hello I am %s." % self.name)
class Dog(Animal):
def __init__(self, name):
super().__init__(name)
def greet(self):
super().greet()
dog = Dog("dog")
dog.greet()
|
import numpy as np
import matplotlib.pyplot as plt
mean_values = [1, 2, 3]
variance = [0.1, 0.25, 0.5]
bar_label = ["bar1","bar2","bar3"]
x_pos = list(range(len(bar_label)))
#将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。
"""
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 返回一个对象
>>> zipped
zip object at 0x103abc288>
>>> list(zipped) # list() 转换为列表
[(1, 4), (2, 5), (3, 6)]
>>>max_z = max(zipped) #out:
(3, 6)
>>>x, y = max_z #out: 3, 6
"""
#画误差棒 draw deviation bar
plt.bar(x_pos, mean_values, yerr=variance, alpha=0.3)
max_y = max(zip(mean_values, variance))
plt.ylim([0, max_y[0]+max_y[1]*1.2]) # 设置y轴范围 set the y-axis range
plt.ylabel("variable y")
#添加x轴对应坐标显示信息, add x axis corresponding coordinate display information
plt.xticks(x_pos, bar_label)
plt.show()
x1 = np.array([1, 2, 3])
x2 = np.array([2, 2, 3])
bar_label = ["bar1","bar2","bar3"]
fig = plt.figure(figsize= (8, 6)) #设置画图及其大小set the graph and its size(width, height)
y_pos = np.arange(len(x1)) #out: [0 1 2] matrix object
print(y_pos)
y_pos = [x for x in y_pos]
plt.barh(y_pos, x1, color="g", alpha=0.5)
plt.barh(y_pos, -x1, color="b", alpha=0.5)
plt.xlim(-max(x2) - 1, max(x1) + 1) # 设置x轴范围 set the x-axis range
plt.ylim( -1, max(x1) + 1)
plt.show()
green_data = [1, 2, 3]
blue_data = [3, 2, 1]
red_data = [2, 3, 3]
labels = ["group 1", "group 2", "group 3"]
pos = list(range(len(green_data))) #out: [0, 1, 2] list object
width = 0.2
fig, ax = plt.subplots(figsize=(8, 6))
plt.bar(pos, green_data, width, alpha=0.5, color="g", label=labels[0])
plt.bar([p+width for p in pos], blue_data, width, alpha=0.5, color="b", label=labels[1])
plt.bar([p+width*2 for p in pos], red_data, width, alpha=0.5, color="r", label=labels[2])
plt.show()
|
#!/usr/bin/env python
import random
from main import Sudoku
class Multiplayer_Sudoku(Sudoku):
def __init__(self, players, revealed=0):
super(Multiplayer_Sudoku, self).__init__()
self.players = players
self.mistakes = dict((x,0) for x in players)
self.cur_player = 0
self.known_data = list(False for x in range(len(self.data)))
for reveal in sorted(range(len(self.data)), key=lambda x: random.random())[:revealed]:
self.known_data[reveal] = True
def format(self):
self.data_bak = self.data
self.data = list(self.data[x] if self.known_data[x] else "?" for x in range(len(self.data)))
r = "Errors: %s\n\nCurrent Player: %s\n\n%s" % (self.mistakes, self.players[self.cur_player], super(Multiplayer_Sudoku, self).format())
self.data = self.data_bak
return r
def done(self):
return all(self.known_data)
def guess(self, row, col, val):
if val == self.data[col + row * self.size]:
self.known_data[col + row * self.size] = True
return True
return False
def unknown(self, row, col):
return not self.known_data[col + row * self.size]
def interactive(self):
while not self.done():
try:
print self.format()
row,col,val = (int(x) for x in raw_input("Please enter your seletion in the form 'row col val' where each is a number 1-9\n--->").split(' '))
assert 1 <= row and row <= 9
assert 1 <= col and col <= 9
assert 1 <= val and val <= 9
row -= 1
col -= 1
except KeyboardInterrupt:
print "\nbye!"
break
except:
raw_input("That isn't formatted like I expect.\n\n Say you want to put the number 1 in the first spot, try '1 1 1' (without quotes)\n\nPress enter to continue")
continue
if self.unknown(row, col):
if not self.guess(row, col, val):
raw_input("Wrong! <press enter to continue>")
self.mistakes[self.players[self.cur_player]] = self.mistakes[self.players[self.cur_player]] + 1
else:
raw_input("Correct! <press enter to continue>")
self.cur_player = (self.cur_player + 1) % len(self.players)
else:
raw_input("That square is already full. <press enter to continue")
print "\n" * 10
self.players.sort(key=lambda x: self.mistakes[x])
if len(self.players) == 1:
print "You Win!"
elif self.mistakes[self.players[0]] == self.mistakes[self.players[1]]:
print "Tie Game!"
else:
print "%s Wins!" % self.players[0]
print "Final score (mistakes):"
print "\n".join("%s: %d" % (x, self.mistakes[x]) for x in self.players)
if __name__ == '__main__':
names = []
while True:
name = raw_input("Please enter the name of player #%d <empty if done>: " % (len(names) + 1))
if not name:
if not names:
names = ["anonymous"]
break
names.append(name)
Multiplayer_Sudoku(names, 10).interactive()
|
# -*- coding: utf-8 -*-
print("Podaj wzrost w cm:")
wzrost = input()
print("Podaj wagę w kg:")
waga = input()
BMI = int(waga) / int(wzrost) ** 2
print ("Twoje BMI wynosi:", BMI)
|
#Zadanie 7.4
# -*- coding: utf8 -*-
numer = int(input("Podaj liczbę:\n"))
for n in range(1, 2):
if numer % 3 == 0:
print("Podana liczba jest wielokrotnością liczby 3")
elif numer % 4 == 0:
print("Liczba jest wielokrotnością liczby 4")
elif numer % 3 == 0 and numer % 4 == 0:
print("Podana liczba jest wielokrotnością liczby 3 i 4")
else:
print("Podana liczba nie jest wielokrotnością liczby 3 i 4")
|
#Zadanie 2.3 - KalkulatorZapotrzebowaniaKalorycznegoKOBIETA
# -*- coding: utf8 -*-
weight = float(input("Podaj proszę swoją wagę kg: "))
height = float(input("Podaj proszę swój wzrost w cm: "))
age = int(input("Podaj proszę swój wiek: "))
S = -161
PPM = 10 * weight + 6.25 * height + 5 * age + S
print("Twoje dzienne zapotrzebowanie kaloryczne wynosi:", PPM * 1.6, "kcal")
|
#Zadanie 6.2
# -*- coding: utf8 -*-
print("Podaj wagę w kg: ")
weight = float(input())
print("Podaj wzrost w cm: ")
height = float(input())/100
BMI = weight / (height ** 2)
print("Twoje bmi wynosi:", round(BMI, 2))
if (BMI < 18.5):
print("Niedowaga")
elif (18.5 <= BMI < 24):
print("Waga prawidłowa")
elif (24 <= BMI < 26.5):
print("Lekka nadwaga")
else:
print("Nadwaga")
if (30 >= BMI > 35):
print("Otyłość I stopnia")
elif (35 >= BMI > 40):
print("Otyłość II stopnia")
else:
print("Otyłość III stopnia")
|
"""
pyfsm - Python Finite State Machine
===================================
A simple Python finite state machine implementation.
pyfsm is based on various states contained within a task.
The task can be retrieved using L{pyfsm.task_registry.get_task}.
Use the L{pyfsm.Registry} object as the central L{pyfsm.task_registry}.
Everything in pyfsm is used as a decorator. For example, to declare
a new state, use the following:
>>> @state('task_name')
... def state_name(tsk): # tsk is the task object
... ...
To specify transitions, use the L{pyfsm.transition} decorator.
>>> @transition(key, 'next_state'):
... def state_name(tsk):
... ...
Multiple transitions can be chained onto a single state. The function
will be called when the state is entered. In addition, you can specify
callbacks and exit handlers for a specific task. For example, to
perform an event when the value '1' is sent, you could do...
>>> def state_name(tsk):
... @tsk.callback(1)
... def print_one(event):
... print event
To add an exit handler, use L{task.atexit}.
>>> def state_name(tsk):
... @tsk.atexit
... def goodbye(self): # self is a task object
... print 'goodbye'
To start a task, grab the task from the registry and call L{pyfsm.task.start}.
>>> task1 = pyfsm.Registry.get_task('task1')
>>> task1.start('start_state') # start the state machine
>>> task1.send(1) # send 1 as the event to the state machine
>>> task1.send(2) # send 2
>>> ...
Sending immutable values, while it can be useful, doesn't always work.
pyfsm allows you to specify a handler for retrieving the key
used when processing events. These keys can be set on two levels.
- Specific task
- Task registry
These are processed, in order. If neither of these works, then the
default handler is used (which just uses the object identity).
For example, to set a custom key retrieval on the task level:
>>> def key_retrieve(event):
... return event.type # type is the variable we want to use as the key
>>> pyfsm.Registry.set_retrieval_func(key_retrieve, 'task1')
To set a key retrieval for the system as a whole, use the same function
but leave out the string specifying the task name.
"""
# Copyright (c) 2011, Jonathan Sternberg All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials
# provided with the distribution.
# * Neither the name of pyfsm nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
__author__ = 'Jonathan Sternberg'
__copyright__ = 'Copyright 2011'
__credits__ = ['Jonathan Sternberg']
__license__ = 'New BSD'
__version__ = '1.0'
__maintainer__ = 'Jonathan Sternberg'
__email__ = '[email protected]'
__status__ = 'Development'
class task_registry(object):
"""
Keeps track of the tasks that have been declared.
This object should not be created by the user, but should
instead reference the L{pyfsm.Registry} value instead.
Tasks are added to the L{pyfsm.Registry} automatically
and can be retrieved with with L{get_task}.
"""
def __init__(self):
self.tasks = {}
self.getattr = None
def set_retrieval_func(self, getter, task_name = None):
"""
Sets a function to be used to retrieve the key from an
event on the task level.
If a task_name is given, then this will assign the key
retrieval function to only that specific task.
@param getter: Retrieval function.
@type getter: C{function}
@param task_name: Task to attach this retrieval function to.
@type task_name: C{str}
"""
if task_name:
tsk = self.get_task(task_name)
tsk.getattr = getter
else:
self.getattr = getter
def get_retrieval_func(self, task_name = None):
"""
Gets the key retrieval function.
If a task name is given, then this return a tuple
with the task's retrieval function as the first element
and the registry's retrieval function as the second element.
@param task_name: Task name to get key retrieval function from.
@type task_name: C{str}
@returns: Key retrieval function for a task/task registry.
@rtype: C{(function, function)} or C{function}
"""
if task_name:
tsk = self.get_task(task_name)
return tsk.getter, self.getter
else:
return self.getter
def get_task(self, name):
"""
Recovers a named task.
@param name: Task name.
@type name: C{str}
@note: If the task does not exist yet, this will create it.
Tasks are made automatically when using the L{pyfsm.state}
decorator.
"""
return self.tasks.setdefault(name, task(name))
"""
Registry where all tasks are stored.
Tasks are made through teh L{pyfsm.state} decorator automatically.
They are stored inside of the L{pyfsm.Registry} object for later
retrieval.
"""
Registry = task_registry()
class task(object):
"""
Denotes a task of operation.
Tasks contain a set of states and transitions. To add a state
to a task, use the L{pyfsm.state} decorator and give the
task name as the parameter.
"""
warn_msg = 'warning: multiple instances of state %s in task %s'
def __init__(self, name):
self.name = name
self.current_state = None
self.states = {}
self.getattr = None
self._locals = {}
self._globals = {}
self.callbacks = {}
self.exit = []
class callback(object):
def __init__(callback, key):
self.key = key
def __call__(callback, func):
if not self.callbacks.has_key(self.key):
self.callbacks[self.key] = []
self.callbacks[self.key].append(func)
return func
self.callback = callback
def atexit(self, func):
"""
Register a function to be called upon exiting the current state.
@param func: exit handler.
@type func: C{function}
@note: The list of exit function clears itself after they are called.
"""
assert self.current_state, 'state machine is not running'
self.exit.append(func)
return func
def start(self, name):
"""
Starts the task with the given state name.
@param name: state name.
@type name: C{str}
"""
for x in self.exit:
x(self)
self.current_state = self.states[name]
self.callbacks = {}
self.exit = []
self._locals = {}
self.current_state.enter(self)
def send(self, event):
"""
Sends an event to this task.
It determines what key to use to identify the event by
calling the appropriate getattr function.
If any callbacks are registered for this event, then they are
invoked first.
If any transitions are registered for this event, a state transition
is invoked after completing the callbacks.
@param event: event to send to the state machine
"""
assert self.current_state, 'state machine is not running'
# recover the key for this event
for getattr in (self.getattr, Registry.getattr, lambda x: x):
try: key = getattr(event)
except: pass
else: break
# check callbacks first
callback = self.callbacks.get(key, [])
for x in callback:
x(event)
# if a transition exists, change the state
trans = self.current_state.transitions.get(key, None)
if trans:
self.start(trans)
def start2(self, name, obj):
"""
Starts the task with the given state name.
@param name: state name.
@param obj: data obj. for func.
@type name: C{str}
"""
for x in self.exit:
x(self, obj)
self.current_state = self.states[name]
self.callbacks = {}
self.exit = []
self._locals = {}
return self.current_state.enter2(self, obj)
#return None
# just set FSM action, not need realy do !
def send2(self, event, obj):
"""
Sends an event to this task.
It determines what key to use to identify the event by
calling the appropriate getattr function.
If any callbacks are registered for this event, then they are
invoked first.
If any transitions are registered for this event, a state transition
is invoked after completing the callbacks.
@param event: event to send to the state machine
@param obj: data obj. for func.
"""
assert self.current_state, 'state machine is not running'
# recover the key for this event
for getattr in (self.getattr, Registry.getattr, lambda x: x):
try: key = getattr(event)
except: pass
else: break
# check callbacks first
callback = self.callbacks.get(key, [])
for x in callback:
x(event, obj)
# if a transition exists, change the state
trans = self.current_state.transitions.get(key, None)
if trans:
return self.start2(trans ,obj)
else:
# when state transited, call old current_state func again!
return self.current_state.enter2(self, obj)
def add_state(self, name, state):
"""
Adds a state to this task.
@param name: name of the state.
@type name: C{str}
@param state: the state object created by the L{pyfsm.state} decorator.
@type state: L{pyfsm.state}
@note: This will not prevent multiple states from being
named the same thing, but it will attempt to warn you.
"""
if self.states.has_key(name):
print task.warn_msg % (name, self.name)
self.states[name] = state
def get_name(self):
"""
Retrieves the task name.
@returns: task name.
@rtype: C{str}
"""
return self.name
@property
def locals(self):
"""
Returns a dictionary of local variables.
@returns: local state variables.
@rtype: C{dict}
@note: Local variables are cleared every time a state transition
happens.
"""
return self._locals
@property
def globals(self):
"""
Returns a dictionary of global variables.
@returns: global state variables.
@rtype: C{dict}
@note: Global variables are kept for inter-state communication.
This does not alter the real globals table and is only "global"
to the specific task.
"""
return self._globals
class transition(object):
"""
Decorator to add a transition to a state.
Used on a function with the following:
>>> @transition(1, 'goodbye')
... def hello_state(tsk):
... ...
This will create a transition to the 'goodbye' state if the key '1' is
ever received.
@param key: event that triggers this transition.
@param value: the state to transition to when this transition is triggered.
@type value: C{str}
"""
def __init__(self, key, value):
self.key = key
self.value = value
def __call__(self, func):
trans = getattr(func, 'transitions', {})
trans[self.key] = self.value
setattr(func, 'transitions', trans)
return func
class state(object):
"""
Decorator to create a state.
A state is made with the following:
>>> @state('task_name')
... def print_hello(tsk):
... print 'hello, world'
This will register a state named 'print_hello' into the 'task_name'
task. This assigns 'print_hello' as a L{pyfsm.state} object
(it is not a function anymore).
This can (and should) be combined with the L{pyfsm.transition} decorator.
@param name: the task name this state should be added into.
@type name: C{str}
@note: State names are inferred by the function name.
"""
def __init__(self, name):
self.task = Registry.get_task(name)
self.transitions = {}
def __call__(self, func):
self.func = func
self.transitions.update(getattr(func, 'transitions', {}))
self.task.add_state(func.__name__, self)
return self
def enter(self, task):
"""
Entrance function to this state.
@param task: task this state is contained within
@type task: L{pyfsm.task}
"""
return self.func(task)
def enter2(self, task, obj):
"""
Entrance function to this state.
@param task: task this state is contained within
@param obj: data obj. for func.
@type task: L{pyfsm.task}
"""
return self.func(task, obj)
|
"""
Alocação de memória em Python -> este é um laboratório apenas conceitual -> Lembre-se => tupo em Python é objeto
OBS.: 1- Python inteligentemente reutiliza valores já alocados para novos valres, economizando espaço em memória
2- Não se esqueça que a RAM de seu computador está dividida em partes, a memória Stack e a memória Heap
3- Seu código é alocado na memória Heap e suas variáveis alocadas na memória Heap
4- O que acontece com dados da memória que não estão mais sendo referenciados? Estes dados estão soltos
5- Python por baixo dos panos ele cria uma referência para cada objeto criado e passa a gerenciar
quantos objetos apontam para a mesma referência. Quando um objeto foi utilizado e não mais faz referncia
à variável, Python decrementa o contador de referência e quando esse for zerado ele se encarrega da
limpeza da memória. Quando a referência de controle do núemro de objetos é zerada, o objeto recebe
o nome de Dead Object -> neste momento entra em ação o algoritmo de Garbage Colletor para
fazer a faxina na memória. Para Python esse algoritmo recebe o nome de Reference Counting.
EM PALAVRAS: - Métodos e variáveis são criadas na memória stack
- Os objtos e instâncias são criadas na memória heap
- Um novo stack é criado durante a invocação de uma função ou método
- Stacks são destruídas sempre que uma função ou método retorna o valor
- O algoritmo de Garbage Collector é um mecanismo para limpar dead objects
-------------------------------------------------------------------------------------
| Ambiente de trrabalho | Memória |
--------------------------------------------------------------------------------------
| x = 10 | x, y --> 10 |
| print(type(x)) <class 'int'> | |
| y = x | |
| if(id(x) == id(y)): | |
| print(f'x e y referenciam a mesma posição de memória |
| x = x + 1 | x --> 11; y --> 10 |
| z = 10 | x --> 11; y, z --> 10 |
| class Carro: | Carro |
| pass | |
| car = Carro() | car --> Carro |
--------------------------------------------------------------------------------------
"""
x = 10
print(f'O tipo de x é -> {type(x)}') # <class 'int'>
y = x
if id(x) == id(y): # x e y referenciam ao mesmo objeto
print(f'x e y referenciam ao mesmo objeto')
x = x + 1
if id(x) == id(y): # Agora x e y referenciam objetos diferentes, observe.
print(f'x e y referenciam ao mesmo objeto após atribuição de 1 em x?')
else:
print(f'Agora x e y referenciam objetos diferentes, observe.')
z = 10
if id(z) == id(y): # z e y referenciam ao mesmo objeto
print(f'z e y referenciam ao mesmo objeto')
else:
print(f'Agora z e y referenciam objetos diferentes, observe.')
class Carro:
pass
car = Carro()
def funcao2(x):
x = x + 1
print(f'O valor de x na funçao2 vale -> {x}') # O valor de x na funçao2 vale -> 11
return x
def funcao1(x):
x = x * 2
print(f'O valor de x na funçao1 vale -> {x}') # O valor de x na funçao1 vale -> 10
y = funcao2(x)
print(f'O valor de y na funçao1 vale -> {y}') # O valor de y na funçao2 vale -> 11
return x, y
y = 5
z = funcao1(y)
|
"""
Filter =>> sua funçao é filtrar dados de uma determinada coleção
- Assim como a função map(), a função filter() recebe dois parâmetros, sendo um uma função e o outro um iterável
- Cada valor do iterável será passado para a função que deverá retornar algum valor
- DICA: Como função trabalhe com lambdas
- ATENÇÃO: Assim como map() a função filter() ->> tem como retorno <class 'filter'> que
após seu uso uma vez estará VAZIA ->> Fique atento!!!
- A diferença entre map() e filter()
- map() => recebe dois argumentos, uma função e um iterável e retorna um objeto mapeado pela função
e faz isso para cada elemento do iter'vel
- filter() => recebe dois argumentos, uma função e um iterável e retorna um objeto filtrando apenas os elementos
de acordo com a função
NOTA: a diferença entre map() e filter() está no retorno da função que em filter() sempre retorno True ou False
"""
# Vamos fazer um import para dar suporte a este laboratório =>> Biblioteca para trabalhar com dados estatísticos
import statistics
# Exemplo 1
valores = 1, 2, 3, 4, 5, 6
print(f'Conhecendo a variável valores -> {valores}\nSeu tipo é -> {type(valores)}')
media = sum(valores) / len(valores)
print(f'A média de valores é -> {media}\nSeu tipo é -> {type(media)}')
# Nosso desafio é filtrar os dados para os valores que estão acima da média para os dados a seguir
dados = [1.3, 2.7, 0.8, 4.1, 4.3, -0.1]
# Calculando a média com a função mean() da biblioteca statistics
media = statistics.mean(dados)
# Note que o retorno de lambda é True ou False ->> sendo assim,no caso para True o valor do dado será passado para filter
res = filter(lambda valor: valor > media, dados)
print(f'Filtrando dados acima da média ->> {list(res)}\nO valor da média é -> {round(media, 2)}\n'
f'Seu tipo é -> {type(res)}')
print(f'Filtrando dados acima da média reimprimindo ->> {list(res)}\nO valor da média é -> {round(media, 2)}\n'
f'Seu tipo é -> {type(res)}') # Observe que o retorno será uma lista vazia
# Uma aplicação importante de filter() é na remoção de dados faltantes
paises = ['', 'Argentina', '', 'Brasil', 'Chile', '', 'Colombia', '', 'Equador', '', '', 'Venezuela']
print(f'A lista completa de paises ->> {paises}')
print(f'Filtrando com lambda dados faltantes ->> {list(filter(lambda dado: dado != "", paises))}')
# Solução mais adequada =>> use None
print(f'Filtrando com tipo None dados faltantes ->> {list(filter(None, paises))}')
# Exemplo mais complexo ->> note que temos uma lista na qual cada elemento é um dicionário chave/valor
usuarios = [
{'username': 'samuel', 'tweets': ['Eu adoro bolos', 'Eu adoro pizzas']},
{'username': 'carla', 'tweets': ['Eu amo meu gato']},
{'username': 'jeff', 'tweets': []},
{'username': 'bob123', 'tweets': []},
{'username': 'doggo', 'tweets': ['Eu gosto de cahorro', 'Vou sair hoje']},
{'username': 'gal', 'tweets': []},
]
print(f'Conhecendo os dados -> {usuarios}\nSeu tipo é -> {type(usuarios)}')
# Desafio =>> filtrar usuários que estão inativos no Twitter
# Forma 1 =>> observe e perceba as diferenças
inativos = list(filter(lambda user: len(user['tweets']) == 0, usuarios))
print(f'A relação de usuários inativos no tweeter forma 1 -> {inativos}')
# Forma 2 =>> observe e perceba as diferenças ->> repetindo os dados aqui para fins didáticos
usuarios_f2 = [
{'username': 'samuel', 'tweets': ['Eu adoro bolos', 'Eu adoro pizzas']},
{'username': 'carla', 'tweets': ['Eu amo meu gato']},
{'username': 'jeff', 'tweets': []},
{'username': 'bob123', 'tweets': []},
{'username': 'doggo', 'tweets': ['Eu gosto de cahorro', 'Vou sair hoje']},
{'username': 'gal', 'tweets': []},
]
inativos = list(filter(lambda user: not user['tweets'], usuarios_f2))
print(f'A relação de usuários inativos no tweeter forma 2 -> {inativos}')
# Combinando filter() e map()
nomes = ['Vanessa', 'Ana', 'Maria']
# Desafio =>> devemos criar uma lista contendo 'Sua instrutora é' + nome, desde que cada nome tenha menos de 5 caracteres
lista = list(map(lambda nome: f'Sua instrutora é {nome}', filter(lambda nome: len(nome) <= 5, nomes)))
print(f'O resultado do desafio é ->> {lista}')
|
"""
Tipos em Python na Prática -> deixando um pouco mais complexo
# Trabalhando com Type Hinting em tipos mais complexos -> olhando para as variáveis não para seu conteúdo
nomes: list = ['Ciencia', 'Dados']
versoes: tuple = (3, 5, 7)
opcoes: dict = {'ar': True, 'banco_couro': True}
valores: set = {3, 4, 5, 6}
print(f'Olhando para nossas variáveis tipadas listas -> {nomes}')
print(f'Olhando para nossas variáveis tipadas tuplas -> {versoes}')
print(f'Olhando para nossas variáveis tipadas dicionários -> {opcoes}')
print(f'Olhando para nossas variáveis tipadas set -> {valores}')
print(f'visualizando todos os tipos definidos -> {__annotations__}')
# {'nomes': <class 'list'>, 'versoes': <class 'tuple'>, 'opcoes': <class 'dict'>, 'valores': <class 'set'>}
-----------------------------------------------------------------------------
# Trabalhando com tipos mais complexos e agora olhando para seu conteúdo
from typing import Dict, List, Tuple, Set
nomes: List[str] = ['Ciencia', 'Dados']
versoes: Tuple[int, int, int] = (3, 5, 7)
opcoes: Dict[str, bool] = {'ar': True, 'banco_couro': True}
valores: Set[int] = {3, 4, 5, 6}
print(f'Olhando para nossas variáveis tipadas listas -> {nomes}')
print(f'Olhando para nossas variáveis tipadas tuplas -> {versoes}')
print(f'Olhando para nossas variáveis tipadas dicionários -> {opcoes}')
print(f'Olhando para nossas variáveis tipadas set -> {valores}')
print(f'visualizando todos os tipos definidos -> {__annotations__}')
# {'nomes': typing.List[str], 'versoes': typing.Tuple[int, int, int], 'opcoes': typing.Dict[str, bool],
# 'valores': typing.Set[int]}
----------------------------------------------------------------------------------------------------------
Acesse o site: https://www.alt-codes.net/suit-cards
- Vamos usar naipes preenchido como pretos
- Vamos usar naipes sem preenchimento como vermelhos
--------------------------------------------------------------------------------------------
# Testando o que temos até aqui
print(f'A constante NAIPES -> {NAIPES}') # ['♠', '♡', '♢', '♣']
print(f'A constante CARTAS -> {CARTAS}') # ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']
print(f'Criando nosso baralho -> {criar_baralho()}')
--------------------------------------------------------------------------------------------
# Testando o que temos até aqui -> criada a função distribuir_cartas
baralho = criar_baralho()
print(f'Chamando distribuir_cartas -> {distribuir_cartas(baralho)}')
"""
import random
# Note que constantes em Python devem ser escritas em maiúsculas
NAIPES = '♠ ♡ ♢ ♣'.split()
CARTAS = '2 3 4 5 6 7 8 9 10 J Q K A'.split()
def criar_baralho(aleatorio=False):
"""Cria um baralho com 52 cartas para jogar"""
baralho = [(n, c) for c in CARTAS for n in NAIPES]
if aleatorio:
random.shuffle(baralho)
return baralho
def distribuir_cartas(baralho):
"""Gerencia a mão de cartas de acordo com o baralho gerado"""
# Neste jogo teremos 4 jogadores
return baralho[0::4], baralho[1::4], baralho[2::4], baralho[3::4]
def jogar():
"""Inicia um jogo de cartas para 4 jogadores"""
cartas = criar_baralho(aleatorio=True)
jogadores = 'P1 P2 P3 P4'.split()
maos = {j: m for j, m in zip(jogadores, distribuir_cartas(cartas))}
for jogador, cartas in maos.items():
carta = ' '.join(f"{j}{c}" for (j, c) in cartas)
print(f'{jogador}: {carta}')
if __name__ == '__main__':
jogar()
|
"""
Módulos Customizados => como módulos Python nada mais são do que arquivos Python, então todos os arquivos criados
neste curso e os que venham a criar são também módulos Python prontos para serem utilizados
Como exemplo vamos chamar o lab27_funcoes_com_parametros para teste =>> OBSERVE
from lab27_funcoes_com_parametros import soma_impares
Os resultados estranhos são decorrentes do módulo Python lab27 que não deveria ter uma série de execuções e
Exemplos de utilizaçao. Deveria ter apenas e tão somente a definição das funções, ok ->> vale aqui o exemplo
lista = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
print(f'Chamando a função soma_impares() de lab27_funcoes_com_parametros -> {soma_impares(lista)}')
O erro a seguir é decorrente do fato de estarmos importando a soma_impares -> vamos corrigir esse problema
alerando o import, observe no próximo exemplo.
print(f'Chamando a outros elementos de lab27_funcoes_com_parametros -> {tupla}') # NameError: name 'tupla' is
not defined
Neste exemplo teremos acesso a tudo o que está definido em lab27_funcoes_com_parametros
import lab27_funcoes_com_parametros as lab27
Os resultados estranhos são decorrentes do módulo Python lab27 que não deveria ter uma série de execuções e
Exemplos de utilizaçao.
print(f'Acessando a tupla -> observe ->> {lab27.tupla}')
print(f'Chamando a função soma_impares() de lab27_funcoes_com_parametros -> {lab27.soma_impares(lab27.lista)}')
"""
# Vamos agora trabalhar com lab38_map
from lab38_map import cidades, c_para_f
print(f'Trabalhando com lab38_map ->> {list(map(c_para_f, cidades))}')
|
"""
Dictionary Comprehension ->> Se quisermos criar um dicionário fazemos => dicionario={'a': 1, 'b': 2, 'c': 3, 'd': 4}
Se quisermos criar uma lista fazemos => lista=[1, 2, 3, 4]
Se quisermos criar uma tupla fazemos => tupla=(1, 2, 3, 4) ou tupla = 1, 2, 3, 4
Se quisermos criar um set (conjunto) fazemos => conjunto={1, 2, 3, 4}
- Sintaxe Dictionary Comprehension =>> {chave:valor(operação) for valor in iterável}
- Iterável aqui é um discionário ->> para trabalhar com os outros iteráveis terá que utilizar chave/valor como
se fosse uma única variável divergindo na operação, portanto, fique atento, não existe dicionários com chaves
repetidas ->> confira no exemplo
"""
# Exemplos -> comprehension usando dicionários
numeros = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
# Queremos elevar ao quadrado os valores de dict
quadrado = {letra: valor ** 2 for letra, valor in numeros.items()}
print(f'Usando Comphehension in dict -> {quadrado}')
# Exemplos -> comprehension dicionários a partir de uma lista =>> observe como estamos trabalhando com chave/valor
numeros = [1, 2, 3, 4, 5]
cubo = {valor: valor ** 3 for valor in numeros}
print(f'Usando Comphehension in dict a partir de lista -> {cubo}')
# Exemplos -> comprehension dicionários a partir de uma tupla =>> observe como estamos trabalhando com chave/valor
numeros = (1, 2, 3, 4, 5)
cubo = {valor: valor ** 3 for valor in numeros}
print(f'Usando Comphehension in dict a partir de tupla -> {cubo}')
# Exemplos -> comprehension dicionários a partir de um conjunto =>> observe como estamos trabalhando com chave/valor
numeros = {1, 2, 3, 4, 5}
cubo = {valor: valor ** 3 for valor in numeros}
print(f'Usando Comphehension in dict a partir de conjunto -> {cubo}')
# Exemplos -> comprehension dicionários a partir de uma lista tendo valores repetidos =>> observe como estamos trabalhando com chave/valor e mais ainda, verifique o que acontece com os valores repetidos
numeros = [1, 2, 3, 4, 5, 4, 3, 2, 1] # Note a presença de valores repetidos
cubo = {valor: valor ** 3 for valor in numeros}
print(f'Usando Comphehension in dict a partir da lista -> {numeros}\nA partir de uma lista com valores repetidos -> {cubo}\nObserve o resultado das chaves')
# Exemplo -> complicando um pouco -> Veja como usar Dict Comprehension para gerar um dicionário a partir
# de uma string utilizada como chave e uma lista utilizada como valores
chaves = 'abcde'
valores = [1, 2, 3, 4, 5]
mistura = {chaves[i]: valores[i] for i in range(0, len(chaves))}
print(f'O Resultado dessa mistruar é -> {mistura}')
# Exemplo utilizando lógica condicional ->> neste dicionário a chave será o próprio valor da lista
# os valores serão par -> quando o número for par e ímpar -> quando o número for ímpar
numeros = [1, 2, 3, 4, 5, 6, 7, 8, 9]
res = {num: ('par' if not num % 2 else 'impar') for num in numeros}
print(f'O valor de dict comprehension com lógica condicional é -> {res}')
|
"""
Criando Loops =>> criando sua própria versão de loop
"""
# O que sabemos e praticamos ->> sabemos isso ...
for num in [1, 2, 3, 4, 5]: # iter([1, 2, 3, 4, 5])
print(f'Iterando na lista -> {num}') # next(num)
for letra in 'Python Ciência de Dados': # iter('Python Ciência de Dados')
print(f'Iterando na lista -> {letra}') # nest(letra)
# Criando um loop ->> observe como é simples criar um loop para imprimir um iterável
def meu_for(interavel):
it = iter(interavel)
while True:
try:
print(f'Meu for -> {next(it)}')
except StopIteration:
break
meu_for('Python')
numeros = [1, 2, 3, 4, 5, 6, 100, 200, 300]
print(f'\n')
meu_for(numeros)
|
"""
Listas Aninhadas (Nested Lists) ->> em Python não existem arrays =>> Python possui Listas
- Algumas linguagends de programação possuem uma estrutura de dados chamadas de arrays:
- Unidimensionais ->> (Arrays/Vetores)
- Multidimensionais ->> (matrizes)
"""
# Exemplos -> veja uma Matriz 3 x 3 a partir de listas aninhadas
listas = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(f'Trabalhando com listas aninhadas -> {listas}\nSeu tipo é -> {type(listas)}')
# Como podemos acessar dados em listas aninhadas -> observe a construção do exemplo, isso vale para
# listas com maior grau de complexidade =>> Lembrando que podemos utilizar índices negativos nas listas
print(f'Primeiro elemento da primeira linha -> {listas[0][0]}')
print(f'Segundo elemento da primeira linha -> {listas[0][1]}')
print(f'Terceiro elemento da primeira linha -> {listas[0][2]}')
print(f'Primeiro elemento da segunda linha -> {listas[1][0]}')
print(f'Segundo elemento da segunda linha -> {listas[1][1]}')
print(f'Terceiro elemento da segunda linha -> {listas[1][2]}')
print(f'Primeiro elemento da terceira linha -> {listas[2][0]}')
print(f'Segundo elemento da terceira linha -> {listas[2][1]}')
print(f'Terceiro elemento da terceira linha -> {listas[2][2]}')
# Iterando com loop em listas aninhadas
for lista in listas:
for num in lista:
print(f'Iteirando em lista aninhadas -> {num}')
# Usando list comphehension para imprimir todos -> observe a tupla com os índices das linhas
print(f'Usando list Comprehension -> {[numero for numero in enumerate(listas)]}')
print(f'Usando list Comprehension refatorado -> observe o uso da função print()')
[[print(valor) for valor in lista] for lista in listas]
# Outros exemplos -> gerando um tabuleiro #x3
print(f'Numa linha -> {[[numero for numero in range(1, 4)] for valor in range(1, 4)]}')
# Em mais de uma linha
tabuleiro = [[numero for numero in range(1, 4)] for valor in range(1, 4)]
print(f'Em mais de uma linha -> {tabuleiro}')
# Gerando resultados utilizando condicional -> escreve X se for par e 0 se for ímpar
resultado = [['X' if not numero % 2 else '0' for numero in range(1, 4)] for valor in range(1, 4)]
print(f'O resultado do jogo da velha é -> {resultado}')
# Gerando valores iniciais => inicilizando uma lista aninhada com List Comprehension "matriz 4x5"
print(f'Inicializando uma lista -> {[["*" for i in range(1, 6)] for j in range(1, 5)]}')
|
"""
Tipo float, decimal => casas decimais
Obs.: o separador de casas decimais na programação é o ponto (.) e não a vírgula (,)
Todas as operações realizadas com inteiros são possíveis com float
"""
# Errado do ponto de vista do float mas gera uma tupla
valor = 1, 44
print(valor)
print(type(valor)) # Será do tipo tupla
# Certo do ponto de vista float
valor = 1.44
print(valor)
print(type(valor)) # Será do tipo float
# É possível considerando uma tupla
valor1, valor2 = 1, 44
print(f"valor 1 será {valor1}")
print(f"valor 2 será {valor2}")
# Podemos converter um float para um int
# Obs.: Ao converter valores float para interiros, nós podemos perder precisão
res = int(valor)
print(f'O valor inteiro de valor é dado por res {res}')
print(f'O tipo de res é {type(res)}')
# Podemos trabalhar tranquilamente com números complexos => sendo todas as operações de complexos aceitas
x = 5 + 4j
print(f'O tipo de x é {type(x)}')
# Podemos converter de inteiro para float
num = 1_000_000
print(f'O tipo de num é {type(num)}')
print(f'Podemos converter para float usando o cast {type(float(num))} {float(num)}')
|
"""
Manipulando data e hora => eventualmente precisamos trabalhar com Data e Hora.
NOTA: Python nos ajuda, pois possui um método built-in (integrado) para se trabalhar
com data e hora chamado datetime
# Conhecendo o datetime - Primeiro, precisamos importá-lo
import datetime
print(f'Para conhecê-lo basta usarmos o comando dir -> {dir(datetime)}') # 'datetime' -> observe que dentro do
# módulo datetime existe também uma classe datetime
# Vamos conhecer os limites de datetime
print(f'Limite máximo de anos -> {datetime.MAXYEAR}')
print(f'Limite mínimo de anos -> {datetime.MINYEAR}')
# Neste exemplo vamos acessar a classe datetime e internamente o método now()
# datetime trabalha com os seguintes parâmetros ->> (year, month, day, hour, minute, second, microsecond)
print(f'O tempo exato em que estamos agora é -> {datetime.datetime.now()}') # 2020-10-03 21:21:40.325535
# Podemos ver a representação deste método, usaremos o já conhecido método repr
print(f'A representação do método acima é -> {repr(datetime.datetime.now())}')
# datetime.datetime(2020, 10, 3, 21, 24, 47, 503790)
# Podemos fazer um ajuste na data/hora e para isso usaremos o método replace()
inicio = datetime.datetime.now()
print(f'O valor de inicio é -> {inicio}') # 2020-10-03 21:29:52.689860
# Nosso objetivo é alterar o horário para: 22:0:0:0 -> Note que não estamos alterando a data
inicio = inicio.replace(hour=22, minute=0, second=0, microsecond=0)
print(f'O valor de inicio é alterado é -> {inicio}') # 2020-10-03 22:00:00
# Imagine uma situação na qual você precisa criar uma data e hora
import datetime
evento = datetime.datetime(2021, 1, 1, 0)
print(f'Qual é o tipo de evento? -> {type(evento)}') # <class 'datetime.datetime'>
print(f'E se o usuário te fornece essa data 31/8/2020 qual seu tipo? -> {type("31/8/2020")}') # <class 'str'>
print(f'Vamos testar se nossa agenda está legal -> {evento}')
# Mas então, como converter uma data fornecida pelo usuário em uma data Python, e assim, poder
# usar todos os recursos da linguagem para manipular essa data?
nascimento = input('Informe a data de seu nascimento dd/mm/yyyy: ')
print(f'Você nasceu em -> {nascimento} e seu tipo é {type(nascimento)}')
# Não queremos o tipo string queremos datetime, ok
nascimento = nascimento.split('/') # Com o split estamos separando pela / e
# criando uma lista de string separando pela barra
print(f'Após o uso do split. Você nasceu em -> {nascimento} e seu tipo é {type(nascimento)}')
# ['20', '08', '1976'] e seu tipo é <class 'list'>
# Vamos agora converter nossa lista de string em inteiros usando o cast int em datetime, observe:
nascimento = datetime.datetime(int(nascimento[2]), int(nascimento[1]), int(nascimento[0]))
print(f'Nascimento após a convesão -> {nascimento} e seu tipo é -> {type(nascimento)}')
# 1765-03-11 00:00:00 e seu tipo é -> <class 'datetime.datetime'>
"""
# Vamos agora fazer acesso individualizado para cada elemento de data e hora
import datetime
evento = datetime.datetime.now()
print(f'{evento.year}', end=' ')
print(f'{evento.month}', end=' ')
print(f'{evento.day}', end=' ')
print(f'{evento.hour}', end=' ')
print(f'{evento.minute}', end=' ')
print(f'{evento.second}', end=' ')
print(f'{evento.microsecond}', end=' ')
|
"""
Módulos Externos => são módulos que não são instalados previamente com a linguagem Python
Para instalar um módulo: pip install <nome_modulo>
Utilizamos o gerenciador de pacotes Python chamado Pip ->> Python Installer Package
Você pode conhecer todos os pacotes oficiais no site =>> https://pypi.org
Para conhecer todos os comandos pip, basta digitar pip no terminal: terminal>pip
Usage:
pip <command> [options]
Como exemplo vamos instalar o módulo externo Colorama: pip install colorama. O módulo externo
colorama é utilizado para a impressão de textos coloridos no terminal.
Para usar colorama é necessário fazer o import de init =>> from colorama inport init e executar a função init()
Num segundo exemplo vamos instalar o módulo externo fpdf2 =>> pip install fpdf2. Este módulo nos permite
converter para pdf de forma configurada e formatada para o formato .pdf. Para maiores detalhes de uso e
configuração deste módulo consulte ->> https://pypi.org/project/fpdf2/
Para usar este módulo externo devemos fazer o seguinte import ->> from fpdf import FPDF
"""
from fpdf import FPDF
from colorama import init, Fore, Style, Back
init()
# Exemplos do módulo Colorama
print(f'Teste colorama ->> {Fore.MAGENTA + "Python para Ciência de Dados"}')
print(f'Teste colorama ->> {Fore.RED + "Python para Ciência de Dados"}')
print(f'Teste colorama ->> {Fore.BLUE + "Python para Ciência de Dados"}')
print(f'O que fica após o uso do Fore ->> {"Olá Python"}') # Note que é preciso resetar as cores
print(f'Teste colorama ->> {Style.RESET_ALL + "Python para Ciência de Dados"}')
print(f'O que fica após o uso do Style.RESET_ALL ->> {"Olá Python"}') # Voltamos ao normal
print(f'Teste colorama ->> {Back.LIGHTBLACK_EX + "Python para Ciência de Dados"}')
print(f'O que fica após o uso do Back ->> {"Olá Python"}') # Note que é preciso resetar para que o fundo retorne
print(f'Teste colorama ->> {Style.RESET_ALL + "Python para Ciência de Dados"}')
print(f'O que fica após o uso do Style.RESET_ALL ->> {"Olá Python"}') # Voltamos ao normal
# Trabalhando com o módulo fpdf
title = '20000 Leagues Under the Seas'
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=15)
pdf.cell(200, 10, txt="Ola Mundo!!!", ln=1, align="C")
# Salvando como pdf
pdf.output("Gera_PDF")
|
"""
Módulos Builtin => são módulos integrados que já vem instalados no Python
Ao instalar Python os módulos builtin são instalados também, a única coisa é que eles não são carregados sem
que você demande explicitamente esse desejo.
Para conhecer um pouco sobre os módulos builtins digite dir(__builtins). Para uma lista completa e maiores
detalhes consulte: https://docs.python.org/3/py-modindex.html
ATENÇÃO: Utilizando alias (apelidos) para módulos/funções => recurso importante para codificação profissional
Exemplo: import random as rdm -> neste caso estamos definindo que o nome do módulo random
será ->> rdm =>> print(rdm.random())
Exemplo: from random import randint as rdi, random as rdm -> neste caso estamos definindo que
o nome da função randint será ->> rdi e oo nome da função random será ->> rdm
=>> print(rdi(5, 89)) =>> print(rdm())
Podemos importar todas as funções de um módulo utilizando *
Exemplo: from random import * -> importante embora o resultado da importação sejam todas as funções
do módulo random, seu efeito na codificação é importante, pois nesse caso, você não fica preso à
necessidade de utilizar o nome do módulo para chamar uma função, você poderá chamar a função diretamente
Exemplo: print(random()) -> e se o import fosse => import random -> print(random.random()) => você teria
que usar o nome do módulo antes do nome da função
Costumamos utilizar tuple para colocar múltiplos imports de um mesmo módulo e escrevemos um módulo por
linha, Exemplo: from random import (
random,
randint,
shuffle,
choice
)
"""
from random import (
random,
randint,
shuffle,
choice
)
print(f'Usando random() -> {random()}')
print(f'Usando randint() -> {randint(2, 8)}')
lista = ["A", "J", "Q", "K"]
print(f'A lista antes do shuffle era -> {lista}')
shuffle(lista)
print(f'Usando shuffle() -> {lista}')
print(f'Usando choice() -> {choice("Python")}')
|
"""
POO -> Classes ->> nada mais são do que modelos dos objetos do mundo real sendo representados computacionalmente
NOTAS: 1- Imagine que você queira fazer um sistema para automatizar o controle das lâmpadas
da casa/empresa. Existe o tipo lâmpada em Python???
2- Não existe, mas podemos criar uma classe lâmpadas ->> com isso poderemos modelar um
objeto do mundo real para o ambiente computacional
3- Classes podem conter:
- Atributos -> representam as características do objeto. Ou seja, pelos atributos
conseguimos representar computacionalmente os estrados de um objeto. No caso da lâmpada
possivelmente iriámos querer saber se a lâmpada é 110 ou 220 volts, se ela é branca,
vermelha ou outra cor, qual é a sua luminosidade, etc.
- Métodos -> são funções que representam os comportamentos do objeto. Ou seja, as ações que
este objeto pode realizar no seu sistema. No caso da lâmpada, por exemplo, um comportamento
comum que muito provavelmente iríamos querer representar no nosso sistema é o de ligar e
desligar a memsa (automatizando o processo liga/desliga).
4- Em Python, para definir uma classe utilizamos a palavra reservada class.
5- Utilizamos a palavra "pass" em Python quando temos um bloco de código que ainda não está
implementado.
6- Quando inicializamos nossas classes em Python utilizamos por convenção o nome com inicial
em maiúsculo. Se o nome for composto, utiliza-se as iniciais de ambas as palavras em maiúsculo
todas juntas (CamelCase).
7- Em computação não utilizamos: acentuação, caracteres especiais, espaços ou similares
para nomes de classes, atributos, métodos, arquivos, diretórios ...
8- Quando estamos planejando um software e definimos quais classes teremos que ter no sistema,
chamamos estes objetos que serão mapeados para classes como entidade.
"""
# A classe Lâmpada, classe ContaCorrente, classe Produto e classe Usuario
class Lampada:
pass
class ContaCorrente:
pass
class Produto:
pass
class Usuario:
pass
lamp = Lampada()
print(f'Observe que acabamos de criar o tipo lâmpada -> {type(lamp)}') # Tipo -> <class '__main__.Lampada'>
# Note que temos usado classes com certa frequência, veja o exemplo a seguir
valor = int('42') # Note que int é um cast para uma string '42'
print(f'Vamos observar mais de perto -> {help(int)}') # Dentre outras informações encontramos -> class int(object)
|
"""
Daniel Daugherty
Word Frequency Analysis
Analyzes the word frequencies in a book downloaded from
Project Gutenberg
"""
import string
def get_word_list(file_name):
""" Reads the specified project Gutenberg book. Header comments,
punctuation, and whitespace are stripped away. The function
returns a list of the words used in the book as a list.
All words are converted to lower case.
"""
# Opens the file and strips away the header comment
f = open(file_name, 'r')
lines = f.readlines()
curr_line = 0
while lines[curr_line].find('Chapter 1') == -1:
curr_line += 1
lines = lines[curr_line+1:]
# Removes the end comments of the text file
curr_line = len(lines) - 1
while lines[curr_line].find('End of Project Gutenberg') == -1:
curr_line -= 1
lines = lines[:curr_line-1]
# Formats all words into one big list and filters out chapter headers and empty lines
wordslist = []
for words in lines:
if words.split() != [] or words[:7] != "Chapter":
wordslist += words.lower().split()
# Removes all punctuation
final_list = []
for word in wordslist:
new_word = ""
for letter in word:
if letter in string.punctuation:
letter = ""
new_word += letter
if new_word != "":
final_list.append(new_word)
# Returns list of all words in the book
return final_list
def get_top_n_words(word_list, n):
""" Takes a list of words as input and returns a list of the n most frequently
occurring words ordered from most to least frequently occurring.
word_list: a list of words (assumed to all be in lower case with no
punctuation
n: the number of words to return
returns: a list of n most frequently occurring words ordered from most
frequently to least frequentlyoccurring
"""
# Creates a histogram of how often the same word appears in the book
word_histogram = dict()
for word in word_list:
word_histogram[word] = 1 + word_histogram.get(word, 0)
# Converts the dictionary into a tuple and sorts the tuple by the frequency of each word
word_tup = word_histogram.items()
word_tup = sorted(word_tup, key = lambda x : x[1], reverse = True)
# Creates a sorted list of the recurring words
res = []
for word, frequency in word_tup:
res.append(word)
# Returns the n most frequent words within the book
return res[:n]
if __name__ == '__main__':
words = get_word_list("Monte_Cristo.txt")
print get_top_n_words(words, 100)
|
import math as m
#bisection function, calculate any math system
def bisection(function, beginValue, endValue, errorRate, maxIteration):
index = 0
beginFunctionValue = function(beginValue)
while index < maxIteration:
middleValue = beginValue + (endValue - beginValue) / 2
middleFunctionValue = function(middleValue)
if(middleFunctionValue == 0 or abs(middleFunctionValue) < errorRate):
return middleValue
if(beginFunctionValue * middleFunctionValue > 0):
beginFunctionValue = middleFunctionValue
beginValue = middleValue
else:
endValue = middleValue
index += 1
raise Exception('not found with this iteration number')
print("exercice 2")
def e2(x):
return x**3 + 4*x**2 - 10
print(bisection(e2, 1, 2, 0.1, 500))
print("exercice 3")
print("a)")
def e3A(x):
return x - 2 ** (-x)
print(bisection(e3A, 0, 1, 0.001, 500))
print("b)")
def e3B(x):
return m.exp(x) - x**2 + 3*x - 2
print(bisection(e3B, 0, 1, 0.001, 500))
print("c)")
def e3C(x):
return 2*x*m.cos(2*x) - (x+1)**2
print(bisection(e3C, -3, -2, 0.001, 500))
print(bisection(e3C, -1, 0, 0.001, 500))
print("d)")
def e3D(x):
return x * m.cos(x) - 2*(x**2) + 3*x - 1
print(bisection(e3D, 0.2, 0.3, 0.001, 500))
print(bisection(e3D, 1.2, 1.3, 0.001, 500))
print("exercice 4")
try:
print(bisection(e3A, 0, 1, 0.001, 3))
except Exception as ex:
print("error in solution, not found values in this max iteration number")
try:
print(bisection(e3A, 0, 1, 0.001, 5))
except Exception as ex:
print("error in solution, not found values in this max iteration number")
try:
print(bisection(e3A, 0, 1, 0.001, 6))
except Exception as ex:
print("error in solution, not found values in this max iteration number")
try:
print(bisection(e3A, 0, 1, 0.001, 10))
except Exception as ex:
print("error in solution, not found values in this max iteration number")
|
"""
9-5 상속
https://youtu.be/kWiCuklohdY?t=14368
"""
# 일반 유닛
class Unit:
def __init__(self, name, hp):
self.name = name
self.hp = hp
# 공격 유닛
class AtttackUnit(Unit):
def __init__(self, name, hp, damage):
Unit.__init__(self, name, hp)
self.damage = damage
def attack(self, location):
print("{0} : {1} 방향으로 적군을 공격 합니다. [공격력 {2}]".format(self.name,location,self.damage))
def damaged(self, damage):
print("{0} : {1} 데미지를 입렀습니다.".format(self.name, damage))
self.hp -= damage
print("{0} : 현재 체력은 {1} 입니다.".format(self.name, self.hp))
if self.hp <=0:
print("{0} : 파괴되었습니다.".format(self.name))
# 메딕 : 의무병
# 파이어뱃 : 공격 유닛, 화염방사기.
firebat1 = AtttackUnit("파이어뱃", 50, 16)
firebat1.attack("5시")
# 공격 2번 받는다고 가정
firebat1.damaged(25)
firebat1.damaged(25)
|
from sys import maxsize
def solution(arr):
"""
Args:
arr (list): List of integers
Returns:
int: absolute value of the difference between the sum of first and the second parts of n
"""
max_sum = 0
for i in arr:
max_sum += i
min_difference = maxsize
sub_sum = 0
for i in range(0, len(arr) - 1):
sub_sum += arr[i]
difference = abs(max_sum - 2 * sub_sum)
if difference < min_difference:
min_difference = difference
return min_difference
assert solution([3, 1, 2, 4, 3]) == 1
assert solution([3, 1]) == 2
|
def caesar(stringer):
string = stringer.split()
out_str = ''
for i in string:
for j in i:
if j.isalpha():
out_str += sdvig(j, count_char(i))
else:
out_str += j
out_str += ' '
return out_str[:-1]
def sdvig(symb, num):
abc = 'abcdefghijklmnopqrstuvwxyz'
symb_index = abc.find(symb.lower())
if symb_index + num > 25:
if symb.lower() == symb:
return abc[symb_index + num - 26]
else:
return abc[symb_index + num - 26].upper()
else:
if symb.lower() == symb:
return abc[symb_index + num]
else:
return abc[symb_index + num].upper()
def count_char(x):
s = x.replace('"', '').replace(',', '').replace('!', '').replace('.', '')
return len(s)
text = input()
print(caesar(text))
|
"""
@author : CK =>[email protected]
@github : https://github.com/ck2605
@date : 13/03/2019
==============================STAIRCASE(#) PATTERN=====================================================================
IF ROW = 5
ANSWER(O/P):
#
# #
# # #
# # # #
# # # # #
"""
n = int(input("enter the row limit:"))
for i in range(n+1):
for j in range(i):
print("# ", end="")
print()
|
# Escrever um programa que leia duas matrizes A e B de uma dimensão com dez elementos. A matriz A deve aceitar apenas a entrada de valores divisíveis por 2 e 3, enquanto a matriz B deve aceitar apenas a entrada de valores múltiplos de 5. A entrada das matrizes deve ser validada pelo programa e não pelo usuário. Construir uma matriz C que seja o resultado da junção das matrizes A e B, de modo que contenha 20 elementos. Apresentar os elementos da matriz C.
def zeraIndice():
i = 0
A = []
B = []
C = []
for i in range(0, 10):
while(not(A[i] % 2 == 0) and not(A[i] % 3 ==0)):
A.append(int(input('Informe o {} valor do vetor A: '.format(i + 1))))
for i in range(0, 10):
while not(B[i] % 5 == 0):
B.append(int(input('Informe o {} valor do vetor B: '.format(i + 1))))
C = A + B
for i in range(0, 20):
print('C[{}] = {}'.format(C[i]))
|
# Ler dois valores para as variáveis A e B e efetuar a troca dos valores de forma que a variável A passe a possuir o valor da variável B e a variável B passe a possuir o valor da variável A. Apresentar os valores após a efetivação do processamento da troca.
A = input('valor de A: ')
B = input('Valor de B: ')
Aux = B
B = A
A = Aux
print(' Valor de A: {} \n Valor de B: {}'.format(A , B))
|
# Elaborar um programa que leia uma matriz A de uma dimensão com dez elementos inteiros. Construir uma matriz C de duas dimensões com três colunas, sendo a primeira coluna da matriz C formada pelos elementos da matriz A somados com 5, a segunda coluna seja formada pelo valor do cálculo da fatorial de cada elemento correspondente da matriz A, e a terceira e última coluna pelos quadrados dos elementos correspondentes da matriz A. Apresentar a matriz C
A = []
C= [[], [], []]
for i in range(10):
A.append(int(input('Informe um valor para matriz A: ')))
for i in range(1):
for j in range(10):
C[i].append(int(A[j] + 5))
for i in range(1, 2):
for j in range(10):
n = A[j]
result = 1
for x in range(1, n + 1):
result *= x
C[i].append(result)
for i in range(2, 3):
for j in range(10):
C[i].append(int(A[j] ** 2))
print('='*40)
for i in range(len(C)):
for j in range(7):
print('C[{}][{}] = {}'.format(i, j, C[i][j]))
|
# Realizar a leitura dos valores de quatro notas escolares bimestrais de um aluno representadas pelas variáveis N1, N2, N3 e N4. Calcular a média aritmética (variável MD) desse aluno e apresentar a mensagem "Aprovado" se a média obtida for maior ou igual a 5; caso contrário, apresentar a mensagem "Reprovado". Informar também, após a apresentação das mensagens, o valor da média obtida pelo aluno.
N1 = float(input('Infomorme a 1° Nota: '))
N2 = float(input('Infomorme a 2° Nota: '))
N3 = float(input('Infomorme a 3° Nota: '))
N4 = float(input('Infomorme a 4° Nota: '))
MD = (N1 + N2 + N3 + N4)/4
if MD >= 5:
print('Sua nota é {:.1f} | APROVADO'.format(MD))
else:
print('Sua nota é {:.1f} | REPROVADO'.format(MD))
|
# Elaborar um programa que leia duas matrizes A e B de duas dimensões com quatro linhas e cinco colunas.A matriz A deve ser formada por valores divisíveis por 3 e 4, enquanto a matriz B deve ser formada por valores divisíveis por 5 ou 6. As entradas dos valores nas matrizes devem ser validadas pelo programa e não pelo usuário. Construir e apresentar a matriz C de mesma dimensão e número de elementos que contenha a subtração dos elementos da matriz A em relação aos elementos da matriz B
A = [[], [], [], []]
B = [[], [], [], []]
B = [[], [], [], []]
for i in range(len(A)):
for j in range(5):
Aux = 1
while(not(Aux % 3 == 0) and not(Aux % 4 == 0)):
Aux = int(input('Informe um valor para a matriz A[{}][{}]: '.format(i, j)))
if(Aux % 2 == 1):
print('ERRO: Na matriz A só são aceitos numeros Divisieis por 3 e 4.')
A[i].append(Aux)
for i in range(len(B)):
for j in range(5):
Aux = 1
while(not(Aux % 5 == 0) and not(Aux % 6 == 0)):
Aux = int(input('Informe um valor para a matriz B[{}][{}]: '.format(i, j)))
if(Aux % 2 == 1):
print('ERRO: Na matriz A só são aceitos numeros Divisieis por 5 e 6.')
B[i].append(Aux)
for i in range(len(C)):
for j in range(5):
C[i].append(A[i][j] - B[i][j])
print('='*70)
for i in range(len(C)):
for j in range(5):
print(C[i][j])
|
# Elaborar um programa que leia uma matriz A do tipo vetor com 20 elementos inteiros. Construir uma matriz B do mesmo tipo e dimensão da matriz A, sendo cada elemento da matriz B o somatório de 1 até o valor do elemento correspondente armazenado na matriz A. Se o valor do elemento da matriz A[1] for 5, o elemento correspondente da matriz B[1] deve ser 15, pois o somatório do elemento da matriz A é 1 +2+3+4+5. Apresentar os elementos da matriz B.
A = []
B = []
for i in range(0, 20):
A.append(int(input('Informe {}° valor de A: '.format(i + 1))))
for i in range(0, 20):
soma = 0
cont = 1
for x in range(0, A[i]):
soma = soma + cont
cont = cont + 1
B.append(soma)
for i in range(0, 20):
print(B[i])
|
# Elaborar um programa que leia duas matrizes A e B de uma dimensão do tipo vetor com dez elementos inteiros cada. Construir uma matriz C de mesmo tipo e dimensão que seja formada pelo quadrado da soma dos elementos correspondentes nas matrizes A e B. Apresentar os elementos da matriz C.
A = []
B = []
C = []
for i in range(0, 10):
A.append(int(input('Informe o {}° valor de A: '.format(i + 1))))
for i in range(0, 10):
B.append(int(input('Informe o {}° valor de B: '.format(i + 1))))
for i in range(0, 10):
C.append((A[i] + B[i])**2)
for i in range(0, 10):
print('C[{}] = {}'.format(i + 1, C[i]))
|
# Elaborar um programa que leia uma matriz A do tipo vetor com 15 elementos inteiros. Construir uma matriz B de mesmo tipo, e cada elemento da matriz B deve ser o resultado da fatorial correspondente de cada elemento da matriz A. Apresentar as matrizes A e B.
A = []
B = []
for i in range(0, 15):
A.append(int(input('informe o {}° valor de A: '.format(i + 1))))
for i in range(0,15):
B.append(1)
for y in range(1, A[i]):
B[i] = B[i] * y
B.append(B[i])
print('_________________________________________')
for z in range(0, 15):
print('{}! é igual a {}'.format(A[z], B[z + 1]))
print('_________________________________________')
|
# Elaborar um programa que calcule uma raiz de base qualquer com índice qualquer.
base = float(input('informe o valor da base: '))
RaizQ = base **(1/2)
print('A Raiz Quadrada de {} é igual a {}'.format(base, RaizQ))
|
# Construir um programa que leia uma matriz A de uma dimensão do tipo vetor com 30 elementos do tipo inteiro.Ao final do programa, apresentar a quantidade de valores pares e ímpares existentes na referida matriz.
A = []
Par = 0
Impar = 0
for i in range(0, 30):
A.append(int(input('Informe o {}° valor do vetor A: '.format(i + 1))))
if(A[i] % 2 == 0):
Par = Par + 1
else:
Impar = Impar + 1
print('Há {} valores PARES e {} valores IMPARES'.format(Par, Impar))
|
# Elaborar um programa que calcule e apresente o valor do volume de uma caixa retangular, utilizando a fórmula VOLUME <- COMPRIMENTO* LARGURA* ALTURA.
comp = int(input('Informe o comprimento: '))
larg = int(input('Informe a largura: '))
alt = int(input('Informe a altura: '))
vol = comp * larg * alt
print('O volume da caixa é de {}'.format(vol))
|
# Efetuar a leitura de três valores inteiros desconhecidos representados pelas variáveis A, B e C. Somar os valores fornecidos e apresentar o resultado somente se for maior ou igual a 100.
A = int(input('Informe valor de A: '))
B = int(input('Informe valor de B: '))
C = int(input('Informe valor de C: '))
Soma = A + B + C
if Soma >= 100:
print(Soma)
|
# Elaborar um programa que leia uma matriz A do tipo real de duas dimensões com cinco linhas e cinco colunas. Apresentar o somatório dos elementos situados na diagonal principal (posições A[1, 1 ], A[2,2], A[3,3], A[4,4] e A[5,5]) da referida matriz.
A = [[], [], [], [], []]
for i in range(len(A)):
for j in range(5):
A[i].append(int(input('Informe um valor para a matriz A[{}][{}]: '.format(i, j))))
for i in range(len(A)):
for j in range(5):
if (i == j):
somat = 0
cont = 1
for x in range(0, A[i][j]):
somat = somat + cont
cont = cont + 1
A[i][j] = somat
for i in range(len(A)):
for j in range(5):
if (i == j):
print('A[{}][{}] = {}'.format(i, j, A[i][j]))
|
from util import isint
class Relocatable():
data = 1
main = 2
wk = 3
def __init__(self, tag, imm):
self.tag = tag
self.imm = imm
def __add__(self, x):
if not isint(x):
raise RuntimeError("cannot __add__ a {}".format(x))
return Relocatable(self.tag, self.imm + x)
def __sub__(self, x):
if not isint(x):
raise RuntimeError("cannot __sub__ a {}".format(x))
return Relocatable(self.tag, self.imm - x)
def __repr__(self):
return "Relocable<tag={}, imm=0x{:x}>".format(self.tag, self.imm)
data_base = Relocatable(Relocatable.data, 0)
main_base = Relocatable(Relocatable.main, 0)
wk_base = Relocatable(Relocatable.wk, 0)
|
#import math
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
#return(int(math.sqrt(x)))
i=0
if(i==0 and x==0):
return(0)
while(i<x):
i+=1
if(i*i==x):
return(i)
elif(i*i>x):
return(i-1)
|
class cargos:
secuenc=0
def __init__(self,des="Sin cargo"):
cargos.secuenc=cargos.secuenc+1
self.codigo=cargos.secuenc
self.descripcion=des
if __name__ == "__main__":
cargo1=cargos()
# cargo1.codigo=1
# cargo1.descrip="docente"
print(cargo1.codigo,cargo1.descripcion)
cargo2=cargos()
# cargo2.codigo=2
#cargo2.descripcion="director"
print(cargo2.codigo,cargo2.descripcion)
cargo3= cargos("analista")
print(cargo3.codigo,cargo3.descripcion)
# print(cargo.secuenc)
# print(cargo1.secuenc)
# print(cargo2.secuenc)
# print(cargo3.secuenc)
|
import sqlite3
import dateutil.parser
import datetime
import sys
def ValidateArgs():
if len(sys.argv) is not 3:
print("Usage: Python query.py start_date end_date")
startDate = ''
endDate = ''
try:
startDate = dateutil.parser.parse(sys.argv[1])
endDate = dateutil.parser.parse(sys.argv[2])
except:
print("One ore more invalid date strings.")
return (False, startDate, endDate)
return (True, startDate, endDate)
def GetStartDate(theDate):
# Helper function to get the monday before a given date
return theDate - datetime.timedelta(days=theDate.weekday())
def RunQuery(sDate, eDate):
print("count,week,workflow_state")
# Validate sDate starts a week and eDate ends a week
if not sDate.weekday() == 0:
sDate += datetime.timedelta(days=(7-sDate.weekday()))
if not eDate.weekday() == 0:
eDate -= datetime.timedelta(days=eDate.weekday())
# one query per week
currentDate = sDate
conn = sqlite3.connect('applicants.sqlite3')
curs = conn.cursor()
while(currentDate < eDate):
endOfWeek = currentDate + datetime.timedelta(days=7)
dates = (currentDate, endOfWeek)
curs.execute('''SELECT COUNT(created_at), workflow_state FROM applicants WHERE created_at >= ? AND created_at < ? GROUP BY workflow_state''', dates)
sqlResults = curs.fetchall()
for result in sqlResults:
print('{0},{1},{2}'.format(result[0], currentDate.date(), result[1]))
currentDate = endOfWeek
conn.close()
# One query, post processing in Python
# dates = (sDate,eDate)
#
# conn = sqlite3.connect('applicants.sqlite3')
# curs = conn.cursor()
# curs.execute('''SELECT workflow_state, created_at FROM applicants WHERE created_at >= ? AND created_at <= ?''', dates)
# sqlResults = curs.fetchall()
# conn.close()
#
# dateSets={}
# for result in sqlResults:
# try:
# dateGroup = GetStartDate(dateutil.parser.parse(result[1])).date()
# if(not dateGroup in dateSets):
# dateSets[dateGroup] = {}
# if(not result[0] in dateSets[dateGroup]):
# dateSets[dateGroup][result[0]] = 0
# dateSets[dateGroup][result[0]] += 1
# for weeksKey, weeksValue in dateSets.items():
# for workflowKey, workflowValue in weeksValue.items():
# print('{0}.{1}.{2}'.format(workflowValue, weeksKey, workflowKey))
if(__name__=='__main__'):
result = ValidateArgs()
if(result[0]):
RunQuery(result[1], result[2])
|
class Auto:
def __init__(self, model):
self.model = model
def stay(self):
return 'Stay'
def move(self):
return 'Move'
class Car(Auto):
def __init__(self, model, passengers_max):
super().__init__(model)
self.passengers_max = passengers_max
class Truck(Auto):
def __init__(self, model, carrying_capacity):
super().__init__(model)
self.carrying_capacity = carrying_capacity
self.cargo_weight = 0
def move(self):
if self.cargo_weight <= self.carrying_capacity:
return 'Move'
else:
return 'Overload'
def stay(self):
return 'Stay'
def increase_cargo_weight(self, weight):
self.cargo_weight += weight
def decrease_cargo_weight(self, weight):
self.cargo_weight -= weight
if __name__ == '__main__':
truck1 = Truck('model1', 1000)
print(truck1.move())
print(truck1.stay())
truck1.increase_cargo_weight(1100)
print(truck1.move())
truck1.decrease_cargo_weight(200)
print(truck1.move())
|
# Создать свою структуру данных Список, которая поддерживает
# индексацию. Методы pop, append, insert, remove, clear. Перегрузить
# операцию сложения для списков, которая возвращает новый расширенный
# объект.
class CustomList:
def __init__(self, *args):
self.my_custom_list = [*args]
def __str__(self):
return f'{self.my_custom_list}'
def __add__(self, other):
return CustomList(*self.my_custom_list + other.my_custom_list)
def get_list(self):
return self.my_custom_list
def append(self, value):
self.my_custom_list = self.my_custom_list + [value]
def pop(self, index=None):
if index is not None:
self.my_custom_list = self.my_custom_list[0:index] + self.my_custom_list[index + 1:len(self.my_custom_list)]
else:
self.my_custom_list = self.my_custom_list[0:-1]
def insert(self, index, element):
self.my_custom_list = self.my_custom_list[0:index] + \
[element] + \
self.my_custom_list[index:len(self.my_custom_list)]
def remove(self, element):
ind = self.my_custom_list.index(element)
self.my_custom_list = self.my_custom_list[0:ind] + self.my_custom_list[ind + 1:len(self.my_custom_list)]
def clear(self):
self.my_custom_list = []
if __name__ == '__main__':
list1 = CustomList(1, 2, 3)
list2 = CustomList(4, 5, 6)
list1.append(33)
list2.append(44)
print(list1, list2)
list1.pop()
list2.pop(2)
print(list1, list2)
list1.remove(3)
list2.remove(4)
print(list1, list2)
list1.insert(2, 23)
list2.insert(3, 32)
print(list1, list2)
print(list1 + list2)
|
import time
import concurrent.futures
from collections import deque
commonList = set()
q = deque()
def task(item):
"""
タスク
"""
global commonList
commonList.add((item.ID,sum(item.values)))
def main():
global q
global commonList
num_workers = None # os.cpu_count()
test_data_num = 5000000
print(f'Data set: {test_data_num}')
print(f'Max worker num: {num_workers}')
"""
テストデータをセットする
"""
set_data_start = time.time()
threadItem = set()
threadItem = [Job([1,2,3],0) for i in range(test_data_num)]
set_data_time = time.time() - set_data_start
print (f'Set test data elapsed_time:{format(set_data_time)} [sec]')
"""
Queueへテストデータを詰める
"""
queueing_start = time.time()
[q.append(item) for item in threadItem]
queueing_time = time.time() - queueing_start
print (f'Queueing elapsed_time:{format(queueing_time)} [sec]')
"""
処理開始
"""
process_start = time.time()
with concurrent.futures.ProcessPoolExecutor(max_workers=num_workers) as executor:
futures = [executor.map(task) for x in range(test_data_num)]
for future in concurrent.futures.as_completed(futures):
print(future.result())
process_time = time.time() - process_start
print (f'Process all data elapsed_time:{format(process_time)} [sec]')
class Job():
#xはリスト,yは書き込み先のリストのインデックス
def __init__(self,x,y):
self.values=x.copy()
self.ID=y
if __name__ == '__main__':
main()
|
# Implement atoi which converts a string to an integer.
# The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
# The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
# If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
# If no valid conversion could be performed, a zero value is returned.
def myAtoi(self, str: str) -> int:
intMax = 2**31-1
intMin = -2**31
data = str.strip();
numbers = "0123456789-+"
number = "0123456789"
minPlus = "-+"
sub = 0
if len(data)>0:
if data[0] not in numbers:
return sub
else:
return sub
if data[0] in minPlus and len(data) == 1:
return sub
if data[0] in minPlus and len(data) > 1 and data[1] not in number:
return sub
for i in range(1,len(data)-1):
if data[i] not in number:
data = data[0:i]
break
if data[len(data)-1] not in number:
data = data[0:-1]
sub = int(data)
return min(intMax, max(intMin, sub))
|
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: LARATWINS
#
# Created: 24/02/2018
# Copyright: (c) LARATWINS 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
pass
if __name__ == '__main__':
main()
age=int(input("Enter the age:"))
print("Whether the age is eligible for voting or not.")
if age==20:
print("eligible.")
else:
print("not eligible.")
|
#-------------------------------------------------------------------------------
# Name: module2
# Purpose:
#
# Author: student
#
# Created: 04/02/2018
# Copyright: (c) student 2018
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
pass
if __name__ == '__main__':
main()
print"Odd number:"
for x in range(1,20,2):
print(x)
print"Even number:"
for y in range(0,20,2):
print(y)
|
# /usr/bin/env python3
# -*- coding:utf-8 -*-
import math
print('理解呢大 %2d-%02d' %(3,1))
print('chygkkbiu %.2f' %3.1415926535)
def move(x, y, step, angle=0):
nx = x + step * math.cos(angle)
ny = y - step * math.sin(angle)
return nx, ny
print(move(10,12,5,math.pi/6))
def fact(n):
if n==1:
return 1
return n*fact(n-1)
print(fact(10))
|
import tkinter as tk
from tkinter import *
import os
def main_acc():
global main_screen
main_screen = Tk()
main_screen.geometry("300x260")
main_screen.title("Main")
Label(text="Login or Register", bg="#b1abf1", fg="white",
width="300", height="2", font=("Calibri", 13)).pack(padx=20, pady=23 )
Button(text="LOGIN", height="2", width="15", fg="#c0ecc0",command=login).pack(padx=1, pady=20)
Button(text="REGISTER", height="2", width="15",fg="#D8BFD8", command=register).pack(padx=1, pady=5)
main_screen.mainloop()
def register():
global register_screen
register_screen = Toplevel(main_screen)
register_screen.title("Register")
register_screen.geometry("320x350")
global username
global password
global username_entry
global password_entry
username = StringVar()
password = StringVar()
Label(register_screen, text="Enter Details Below to Login!",bg="#D8BFD8", fg="black",
width="300", height="2",font=("Calibri", 13)).pack(padx=20, pady=23 )
Label(register_screen, text="").pack()
unLabel = Label(register_screen, text="Username",fg="black", bg="#D8BFD8")
unLabel.pack(pady=5)
unEntry = Entry(register_screen, textvariable=username)
unEntry.pack()
passLabel = Label(register_screen, text="Password",fg="black" , bg="#D8BFD8")
passLabel.pack(pady=5)
passEntry = Entry(register_screen,textvariable=password, show='*')
passEntry.pack()
Label(register_screen, text="").pack()
Button(register_screen, text="Register", width=10, height=1, fg="black", command=register_user).pack()
def login():
global login_screen
login_screen = Toplevel(main_screen)
login_screen.title("Login")
login_screen.geometry("320x350")
Label(login_screen,text="Enter Details Below to Login!",bg="#c0ecc0", fg="black",
width="300", height="2",font=("Calibri", 13)).pack(padx=20, pady=23 )
Label(login_screen, text="").pack()
global username_verify
global password_verify
username_verify = StringVar()
password_verify = StringVar()
global username_login_entry
global password_login_entry
Label(login_screen, text="Username",fg="black", bg="#c0ecc0").pack()
username_login_entry = Entry(login_screen, textvariable=username_verify)
username_login_entry.pack(pady=5)
Label(login_screen, text="").pack()
Label(login_screen, text="Password",fg="black", bg="#c0ecc0").pack(pady=5)
password_login_entry = Entry(login_screen, textvariable=password_verify, show='*').pack()
Label(login_screen, text="").pack()
Button(login_screen, text="Login",width=10,fg="black" ,height=1, command=login_verify).pack()
def register_user():
username_info = username.get()
password_info = password.get()
file = open(username_info, "w")
file.write(username_info + "\n")
file.write(password_info)
file.close()
username_entry.delete(0, END)
password_entry.delete(0, END)
Label(register_screen, text="Registration Success", fg="green", font=("calibri", 11)).pack()
def login_verify():
username1 = username_verify.get()
password1 = password_verify.get()
username_login_entry.delete(0, END)
password_login_entry.delete(0, END)
list_of_files = os.listdir()
if username1 in list_of_files:
file1 = open(username1, "a")
verify = file1.read().splitlines()
if password1 in verify:
login_sucess()
else:
password_not_recognised()
else:
user_not_found()
def login_sucess():
global login_success_screen
login_success_screen = Toplevel(login_screen)
login_success_screen.title("Success")
login_success_screen.geometry("150x100")
Label(login_success_screen, text="Login Success").pack()
Button(login_success_screen, text="OK", command=delete_login_success).pack()
def password_not_recognised():
global password_not_recog_screen
password_not_recog_screen = Toplevel(login_screen)
password_not_recog_screen.title("ERROR")
password_not_recog_screen.geometry("150x100")
Label(password_not_recog_screen, text="Invalid Password").pack()
Button(password_not_recog_screen, text="OK", command=delete_password_not_recognised).pack()
def user_not_found():
global user_not_found_screen
user_not_found_screen = Toplevel(login_screen)
user_not_found_screen.title("ERROR")
user_not_found_screen.geometry("150x100")
Label(user_not_found_screen,fg="red", text="User Not Found!").pack(pady=20)
Button(user_not_found_screen, text="OK", command=delete_user_not_found_screen).pack()
def delete_login_success():
login_success_screen.destroy()
def delete_password_not_recognised():
password_not_recog_screen.destroy()
def delete_user_not_found_screen():
user_not_found_screen.destroy()
main_acc()
|
romanInventions = {
"Aquaducts": "Bridges carrying water",
"Sanitation": "Clean water and adequate sewage disposal",
"Roads": "Wide ways leading from anywhere to Rome"
}
menu = [
"List inventions",
"Look up an invention",
"Add an invention",
"Edit an invention",
"Delete an invention",
"Quit"]
def displayMenu(m):
print("\nWhat did the Romans ever give us?\n")
for i in range(len(m)):
print(str(i+1), m[i])
print()
def getOption():
a = int(input("Please enter a number: "))
return a
def listInventions(ri):
print("\nThe Romans gave us...\n")
for i in ri.keys():
print(i)
loopMenu = True
while loopMenu:
displayMenu(menu)
loopMenu = False
option = getOption()
if option == 1:
listInventions(roamanInventions)
if option
|
if __name__ == '__main__':
fichier = open('input.txt', 'r') #open() pour ouvrir un fichier, r pour lire, w pour ecrire
content = fichier.read() #lecture du fichier texte
monTableau = [int(i) for i in content.split('\n')] #discomprehension pour traduire les string en int
for monIterateur in monTableau:
for j in monTableau:
for k in monTableau:
addition = monIterateur + j + k
if addition == 2020:
multiplication = monIterateur * j * k
reponse = multiplication
print(reponse)
|
import re
from functools import reduce
from itertools import chain
from collections import Counter
import typing
def get_words(word_len: int, filename: str = "words.txt") -> typing.Set[str]:
"""
Get all words that have the desired length from the given text file.
:param filename: The name of the file to load the words from.
:param word_len: The desired length of words.
:return: an iterable of words of the given length.
"""
with open(filename) as word_file:
return {
word.lower()
for word in map(str.strip, word_file.readlines())
if len(word) == word_len and word.isalpha()
}
def get_possible_words(guesses: str, current_word: str, all_words: typing.Iterable) -> typing.List[str]:
"""
Get all possible words based on the given `current_word` and `guesses`
:param all_words: All of the words that have been loaded in.
:param guesses: what the player has already submitted as a guess
:param current_word: The current word at play.
:return: A list of all possible words.
"""
substitute: str = '.' if len(guesses) == 0 else f"[^{guesses}]"
# Make the current word a regex phrase.
current_word_regex: typing.Pattern = re.compile(current_word.replace('_', substitute))
return [word for word in all_words if current_word_regex.match(word)]
def get_statistics(possible_words: typing.Iterable) -> Counter:
"""
Gets the number of occurrences of the letters in the list possible_words
:param possible_words: The words that are to be analyzed.
:return: a Counter object with a count of each letter in possible_words
"""
return Counter(chain.from_iterable(possible_words))
def get_likeliest_letter(stats: Counter) -> typing.Tuple[str, float]:
"""
Gets the likeliest letter and its likelihood in the given stats dict.
:param stats: a dict as key: character, value: frequency of key
:return: the likeliest_letter and its likelihood.
"""
likeliest_letter, count = stats.most_common(1)[0]
likelihood = count / sum(stats.values()) * 100.0
return likeliest_letter, likelihood
def sanitize_user_input(user_input: str, last_user_input: str, initial_len_of_input: int) -> typing.Tuple[str, int]:
"""
Corrects the user's input based on previous input.
:param last_user_input: The previous user input.
:param user_input: The current user input.
:param initial_len_of_input: The initial length of the user input.
:return: The correct user input and the correct length of the user input.
"""
if initial_len_of_input == -1:
return user_input, len(user_input)
corrected_input: str = user_input
while len(corrected_input) != initial_len_of_input:
print("Your input is not the same length as it was the first time.")
print(f"Your last input was {last_user_input} and had {len(last_user_input)} characters in it.")
corrected_input = input("Try again. ").lower()
differences: typing.List[bool] = [last_user_input[i] != corrected_input[i]
for i in range(initial_len_of_input)
if last_user_input[i] != '_']
if len(differences) == 0:
return corrected_input, initial_len_of_input
has_differences: bool = all(differences) or reduce(lambda x, y: x != y, differences)
while has_differences:
print("Your input is not the same as it was the first time.")
print("You may have put a character in the wrong place.")
print(f"Your last input was {last_user_input}.")
corrected_input = input("Try again. ").lower()
differences = [last_user_input[i] != corrected_input[i]
for i in range(initial_len_of_input)
if last_user_input[i] != '_']
has_differences = all(differences) or reduce(lambda x, y: x != y, differences)
return corrected_input, initial_len_of_input
def play_hangman():
"""
Plays a game of hangman.
"""
is_playing: bool = True
was_correct: bool = True
guesses: str = ""
current_word: str = ""
len_of_word: int = -1
words: typing.Set[str] = set()
while is_playing:
# Get input from the user if the current word on the board
# changed or is new.
if was_correct:
last_word: str = current_word
print("What is currently on the board?")
current_word = input("(Input unknown characters with _) ").lower()
current_word, len_of_word = sanitize_user_input(current_word, last_word, len_of_word)
# if we found the word, we can stop playing.
if current_word.count('_') == 0:
break
# Add any guesses that might have been missed in between rounds.
guesses += ''.join([guess for guess in current_word if guess != '_' and guess not in guesses])
if len(words) == 0:
words = get_words(len(current_word))
possible_words: typing.List[str] = get_possible_words(guesses, current_word, words)
print(f"There are {len(possible_words)} possible words.")
if len(possible_words) <= 10:
[print(word) for word in possible_words]
if len(possible_words) == 1:
print(f"It's obviously {possible_words[0]}.")
break
stats_temp: Counter = get_statistics(possible_words)
stats: Counter = Counter({key: value for key, value in stats_temp.items() if key not in guesses})
print("Your most likely letter is...")
likeliest_letter: typing.Tuple[str, float] = get_likeliest_letter(stats)
print(f"{likeliest_letter[0]} with a likelihood of {likeliest_letter[1]:.2f}%")
was_correct = input("Was I correct? (y/n) ").lower() == 'y'
guesses += likeliest_letter[0]
# Print a new line to break each round up.
print("")
print(f"It took me {len(guesses)} guesses to get it.")
if __name__ == '__main__':
play_again: bool = True
while play_again:
play_hangman()
play_again = input("Want to play again? (y/n) ").lower() == 'y'
# Print a new line to separate games.
print("")
|
#print("請輸入:", end="")
#r=input("")
# r=input("輸入:")
# #print("你輸入了",r)
# if r.find("a")!=-1:
# print("你好")
# elif r.find("b")=1:
# print("哈囉")
# else:
# print("哈哈哈")
# x="1,2,3,4,5,6,7"
# z=x.split(",")#切割 split("做為切割的字串")
# print(z)
# for i in z:
# print(i)
# x=input("請輸入生日:")#切割範例
# z=x.split("-")
# print(z[0], "年")
# print(z[1], "月")
# print(z[2], "日")
# x=["A","B","C"] #串列合起來成字串
# z="".join(x)
# print(z)
# #範例
# x = [input("國家:"),input("城市:"),input("地址:"),input("號碼")]
# z = "".join(x)
# print(z)
#載入模組
# import sys
# print(sys.argv)
import os
# os.system("dir")
# os.system("tasklist")
# p=os.popen("tasklist")
# x=p.read()
# #print(x)
# y=False
# for a in x:
# if a.find("notepad.exe")!=-1:
# y=True
# if y==True:
# print("記事本已開啟")
# else:
# os.system("notepad.exe")
# p=os.popen("tasklist")
# x=p.read()
# import webbrowser
# u=input("請輸入網址:")
# webbrowser.open(u, new=1, autoraise=True)
# import os
# import sys
# ff=sys.argv[1]
#
# os.system('"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe" ')
# y=False
# for a in x:
# if a.find("notepad.exe")!=-1:
# y=True
# if y==True:
# print("記事本已開啟")
# else:
# os.system("notepad.exe")
import codecs
# f=codecs.open("1.txt", "r", "utf8") #w寫入 r讀取 a附加 b二進位
# # f.write("abc")
# x=f.read()
# f.close()
# print(x)
#b二進位 複製圖片
# f=codecs.open("1.png", "rb")
# # f.write("abc")
# x=f.read()
# f.close()
# # print(x)
# f=codecs.open("2.png", "wb")
# f.write(x)
# f.close()
#with讓檔案在範圍內(自動關閉)
# with codecs.open("1.txt", "r", "utf8") as f:
# x=f.read()
# with codecs.open("2.txt", "w", "utf8") as f:
# f.write(x)
# os.remove("2.png")
# os.mkdir("xxx")
# os.rmdir("xxx")
# r=os.listdir("D:/")#取出變成list
# rr=os.listdir("./")#./代表當前資料夾
# rrr=os.listdir("../")#../代表當前資料夾的上一個資料夾
# print(r)
# print(rr)
# print(rrr)
# for d in rr:
# print(d)
# pp=d.find("0620.py")
# print(pp)
# print("工作路徑:", os.getcwd())#取得當前工作路徑
# print(os.listdir("./"))
# os.chdir("../")
# print("工作路徑:", os.getcwd())
# print(os.listdir("./"))
# print(os.path.isdir("../python"))
# print(os.path.isdir("1.txt"))
# print(os.path.exists("1.txt"))
# print(os.path.isfile("1.txt"))
# print(os.path.basename("./0620.py"))
# priny(os.path.getsize("./0620.py"))
# def read_dir(r,t):
# z= os.listdir(r)
# for d in z :
# if os.path.isdir(r+"/"+d)==True:
# read_dir(r+"/"+d,t)
# if d.find(t)!=-1:#if t in d:
# print(r+"/"+d)
# read_dir("D:/python", "0")
x=""
while x!=0:
os.system("cls")
fileList=[]
dirList=[]
for d in os.listdir("./"):
if os.path.isdir(d)!= True:
fileList+=[d]
else:
dirList+=[d]
if x=="1":
for i in range(0,len(fileList),1):
print(i, fileList[i])
print("")
# y=os.listdir("./")
# y="\n".join(y)
# print(y)
elif x=="2":
for i in range(0, len(dirList), 1):
print(i,dirList[i])
print("")
# ff = os.listdir("./")
# for fe in ff:
# e = os.path.isdir(fe)
# if e==True:
# print(fe)
elif x=="3":
for i in range(0,len(fileList),1):
print(i, fileList[i])
print("")
p=input("請輸入檔案索引:")
os.system("cls")
print("=====檔案開始=====")
with codecs.open(fileList[int(p)], "r", "utf8") as f:
print(f.read())
print("=====檔案結束=====")
print("")
# os.system("cls")
# y=os.listdir("./")
# y="\n".join(y)
# print(y)
# input("請輸入檔案索引:")
# f=codecs.open(fi, "r", "utf8")
# x=f.read()
# f.close()
# print(x)
elif x=="4":
for i in range(0,len(fileList),1):
print(i, fileList[i])
print("")
pd=input("請輸入要刪除的檔案索引:")
os.system("cls")
os.remove(fileList[int(pd)])
print("")
elif x=="5":
for i in range(0,len(fileList),1):
print(i, fileList[i])
print("")
pp=input("請輸入要執行的檔案索引:")
os.system("cls")
os.popen(fileList[int(pp)])
elif x=="6":
for i in range(0, len(dirList), 1):
print(i,dirList[i])
print("")
dd=input("請輸入資料夾索引:")
os.chdir(dirList[int(dd)])
print("")
elif x=="7":
for i in range(0, len(dirList), 1):
print(i,dirList[i])
print("")
rd=input("請輸入資料夾索引:")
# os.rmdir(dirList[int(rd)])
def rm_dir(r):
for d in dirList:
if os.path.isdir(r+"/"+d)==True:
rm_dir(r+"/"+d)
else:
os.remove(r)
# if d.find()!=-1:
# rmdir("./")
rm_dir(dirList[int(rd)])
elif x=="8":
os.chdir("../")
print("工作路徑:", os.getcwd())
print("(0) 離開程式")
print("(1) 列出檔案")
print("(2) 列出資料夾")
print("(3) 顯示檔案內容")
print("(4) 刪除檔案")
print("(5) 執行檔案")
print("(6) 進入資料夾")
print("(7) 刪除資料夾")
print("(8) 回上層資料夾")
x = input("操作:")
|
# Snake and Snake App
# Author: Yuanjie Yuanjie
# Date: 11/20/19
import pygame
import random
import time
import config
class Snake:
# pos = (x, y), where x is the col offset, and y is the row offset.
def __init__(self, pos, rows, cols):
self.rows, self.cols = rows, cols
self.body = [pos]
self.dc, self.dr = 0, 1
self.direction = config.DOWN
# Update snake's direction according to the given direction
def _update_dir(self, direction):
if direction == config.UP:
self.dc, self.dr = 0, -1
elif direction == config.RIGHT:
self.dc, self.dr = 1, 0
elif direction == config.DOWN:
self.dc, self.dr = 0, 1
elif direction == config.LEFT:
self.dc, self.dr = -1, 0
# Return true if move is okay, false otherwise.
def move(self, opponent_snake, apple, direction):
self._update_dir(direction)
c, r = self.head()
nc, nr = (c + self.dc) % self.cols, (r + self.dr) % self.rows
# hit his own body, lose
if (nc, nr) in self.body:
return config.LOSE
# two snake run at heads, tie
if (nc, nr) == opponent_snake.head():
return config.TIE
# hit opponent snake body, lose
if (nc, nr) in opponent_snake.body:
return config.LOSE
self.body.insert(0, (nc, nr))
if not (nc, nr) == apple:
self.body.pop()
return config.CONTINUE
# Return the head of the snake.
def head(self):
return self.body[0]
class SnakeApp:
def __init__(self):
# Initialize surface
self.rows, self.cols = config.HEIGHT, config.WIDTH
self.snake_size = 20
self.surface = pygame.display.set_mode((self.cols * self.snake_size, self.rows * self.snake_size))
pygame.display.set_caption('Snake Game')
self.game_status = config.CREATE
self.snake = []
self.opponent_snake = []
self.apple = None
pygame.display.update()
def _draw_rect(self, pos, color):
c, r = pos
pygame.draw.rect(self.surface, color,
(c*self.snake_size+1, r*self.snake_size+1, self.snake_size-2 , self.snake_size-2))
# redraw the game window
def _redraw_window(self):
self.surface.fill(config.BLACK)
self._draw_rect(self.apple, config.RED)
for pos in self.snake:
self._draw_rect(pos, config.GREEN)
for pos in self.opponent_snake:
self._draw_rect(pos, config.ORANGE)
pygame.display.flip()
# run the game for one time
def run_once(self):
if self.game_status == config.OVER: return
if self.game_status == config.CREATE:
self._draw_msg('Wait for component')
elif self.game_status == config.READY:
self._draw_msg('Wait game start')
elif self.game_status == config.START:
self._redraw_window()
# show wait for opponent and wait for game start
def _draw_msg(self, msg):
self.surface.fill(config.BLACK)
assert pygame.font.get_init()
font = pygame.font.Font(None, 60)
text = font.render(msg, True, config.BLUE)
text_rect = text.get_rect()
text_x = self.surface.get_width() / 2 - text_rect.width / 2
text_y = self.surface.get_height() / 2 - text_rect.height / 2
self.surface.blit(text, [text_x, text_y])
pygame.display.flip()
# Update the status of the game to the given status
def _update_game_status(self, status):
self.game_status = status
# Update snakes and apple with the given snakes and apple
def _update_snakes_and_apple(self, snake, opponent_snake, apple):
self.snake, self.opponent_snake = [], []
self.snake.extend(snake)
self.opponent_snake.extend(opponent_snake)
self.apple = apple
# if __name__ == "__main__":
# clock = pygame.time.Clock()
# FPS = 10 # frames-per-second
# game = SnakeApp()
# while True:
# clock.tick(FPS)
# for event in pygame.event.get():
# if event.type == pygame.QUIT:
# pygame.quit()
# game.run_once()
|
from tkinter import *
from login_details import auto_login_details
def auto_login():
"""Build an auto login page using GUI"""
screen = Tk()
screen.title("User Login Page")
screen.geometry("300x250")
Label(screen, text="Please enter login details").pack()
Label(screen, text="").pack()
#Declaring type of variable for entry.
username = StringVar()
password = StringVar()
Label(screen, text="Username").pack()
Entry(screen, textvariable = username).pack() #Creating entry widget to take value.
Label(screen, text = "").pack()
Label(screen, text = "Password").pack()
Entry(screen, textvariable = password,show="*").pack()
Label(screen, text = "").pack()
#Creating button to call auto_login_details function.
Button(screen, text = "Auto fill username and password",command = auto_login_details).pack()
screen.mainloop()
auto_login()
|
def minion_game(s):
def is_vowel(c):
return c == 'A' or c == 'E' or c == 'I' or c == 'U' or c == 'O'
stuart_pts = 0
kevin_pts = 0
for i in range(len(s)):
add = len(s) - i
if is_vowel(s[i]):
kevin_pts += add
else:
stuart_pts += add
if stuart_pts > kevin_pts:
print("Stuart " + str(stuart_pts))
elif stuart_pts < kevin_pts:
print("Kevin " + str(kevin_pts))
else:
print("Draw")
|
import random
from typing import List
RANDOM_LENGTH = 3
BASE_62_DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
# This function is just for testing.
def _base62_string_to_decimal(base62_string: str) -> int:
number_list = list(map(BASE_62_DIGITS.index, base62_string))
result = 0
for num, i in zip(number_list, reversed(range(len(number_list)))):
result += num * 62 ** i
return result
def _decimal_to_base62(number: int) -> List[int]:
result = []
while number > 0:
remainder = number % 62
result.append(remainder)
number = int(number / 62)
return list(reversed(result))
def _base62_to_string(number_list: List[int]) -> str:
result = map(lambda n: BASE_62_DIGITS[n], number_list)
return "".join(result)
def _generate_random_string(length: int) -> str:
result = random.sample(BASE_62_DIGITS, length)
return "".join(result)
def generate_url_id(counter: int) -> str:
"""Based on the integer value of the counter, generate an URL ID in the alphanumeric format."""
base62_list = _decimal_to_base62(counter)
base62_string = _base62_to_string(base62_list)
random_part = _generate_random_string(RANDOM_LENGTH)
return random_part + base62_string
|
n = int(input().strip())
N = n
i = 2
while i * i <= n:
if n % i:
i += 1
else:
n //= i
if n == N:
print(True)
else:
print(False)
|
class TrieNode:
def __init__(self):
self.children = dict()
self.val = 0
class Trie:
def __init__(self, n):
self.root = TrieNode()
self.n = n
def add_num(self, num):
self._add(num)
def _add(self, num):
node = self.root
for bit in range(self.n, -1, -1):
if num & (1 << bit):
val = 1
else:
val = 0
if val not in node.children:
node.children[val] = TrieNode()
node = node.children[val]
node.val = num
class Solution:
def findMaximumXOR(self, nums: List[int]) -> int:
max_len = len(bin(max(nums))) - 2
trie_tree = Trie(max_len)
for num in nums:
trie_tree.add_num(num)
res = 0
for num in nums:
node = trie_tree.root
for bit in range(max_len, -1, -1):
if num & (1 << bit):
val = 1
else:
val = 0
if (1 - val) in node.children:
node = node.children[1 - val]
else:
node = node.children[val]
res = max(res, num ^ node.val)
return res
|
# Importando os datasets disponíveis da biblioteca sklearn
from sklearn import datasets
# Importação da classe KNeighborsClassifier do pacote neighbors do sklearn
from sklearn.neighbors import KNeighborsClassifier
# Carregamento da base de dados Iris que classifica tipos de plantas de acordo com suas características
iris = datasets.load_iris()
# Selecionando uma das plantas para fazer o cálculo da distância
iris_teste = iris.data[0,:]
# Buscando a classe (target) correta da planta
iris_teste_classe = iris.target[0]
# Variável que contem os atributos previsores que são os dados para o treinamento
X = iris.data[1:150,:]
# Variável que contem as classes
y = iris.target[1:150]
# Variável Knn que recebe o KNeighborsClassifier que fará o cálculo de singularidade (os vizinhos mais próximos)
knn = KNeighborsClassifier(n_neighbors = 3)
knn.fit(X, y) # Aqui acontece o treinamento
previsao = knn.predict(iris_teste.reshape(1,-1))
|
""" Pattern Matching with Ladder """
"""
#
# Function 1. is_match (difficulty 1)
#
Lets implement a function called `is_match`.
`is_match(pattern, input)`
"pattern" is a string where each character is a token.
"input" is a string where each word is a token (space delimited).
return value: boolean which represents whether these two strings match
Here are some python examples / test cases:
assert is_match("aba", "red blue red") == True
assert is_match("aaa", "red blue red") == False
assert is_match("aba", "red red red") == False
Implement `is_match` with linear runtime O(n + m) where n is the length of
pattern and m is the length of input. You can use any language you want. If you
finish with enough time left then see if you can make your implementation as
clean and concise as possible.
"""
def is_match(pattern, input_s):
""" Returns True/False
>>> is_match("aba", "red blue red")
True
>>> is_match("aaa", "red blue red")
False
>>> is_match("aba", "red red red")
False
>>> is_match('abc', 'red blue red')
False
"""
input_lst = input_s.strip().split()
if len(input_lst) != len(pattern):
return False
pat_str = {}
# this breaks down if any word in input_s is also a token:
# is_match('abc', 'bowl a chicken') is False but should be True
for i in range(len(pattern)):
if pattern[i] in pat_str:
if input_lst[i] != pat_str[pattern[i]]:
return False
elif input_lst[i] in pat_str:
if pattern[i] != pat_str[input_lst[i]]:
return False
else: # First time of token and word
pat_str[input_lst[i]] = pattern[i]
pat_str[pattern[i]] = input_lst[i]
# If we've made it without incident, must be True
return True
"""
#
# Function 2. find_combos (difficulty 2)
#
Lets implement a function called `find_combos`.
`find_combos(num_desired, available_pack_sizes)`
"num_desired" is an integer and represents the number of sodas that you want.
"available_pack_sizes" is a list of integers and reprents the available pack
sizes a store has.
return value: a list of lists where each entry is a valid combination
If you ran find_combos at the python REPL you'd want to see exactly this output:
>>> find_combos(7, [1, 6, 12])
[[1, 1, 1, 1, 1, 1, 1,], [1, 6]]
>>> find_combos(7, [6])
[]
>>> find_combos(4, [1, 3])
[[1, 1, 1, 1], [1, 3]]
Implement `find_combos` in the simplest way you can. There are no points for
efficiency or runtime in this question. Just focus on solving it in the
cleanest way possible. You can use any language you want. If you finish
everything else with enough time left then see if you can write some type of
upper bound on the runtime (asymptotic runtime complexity).
"""
def find_combos(num_desired, available_pack_sizes):
# Started by thinking this was a Making Change problem; I am now convinced
# it is the Rod-Cutting problem. I first saw the problem in another
# technical screen. As a person who is not a CS graduate, I have not spent
# time really studying this problem. It is complex and interesting-ish, but
# not part of my wheel-house of strengths.
pass
"""
#
# Function 3. is_match_2 (difficulty 3)
#
# This is a BONUS QUESTION. I don't expect you'll be able to get to this
# question and solve it in time.
#
Lets implement a function called `is_match_2`.
`is_match(pattern, input)`
"pattern" is a string where each character is a token.
"input" is a string.
return value: boolean which represents whether there exists any solution.
Here are some python examples / test cases:
assert is_match("ab", "xy") == True
assert is_match("ab", "xxy") == True
assert is_match("ab", "xyy") == True
assert is_match("ab", "xx") == False
assert is_match("aa", "xy") == False
Implement `is_match_2` in the simplest way possible. You can use any language
you want. If you finish with enough time left then see if you can make your
implementation as clean and concise as possible.
"""
def is_match_2(pattern, input_s):
""" Return True/False if the pattern exists anywhere in the input string,
this time evaluating characters instead of words.
This method takes advantage of the ord() function to calculate the
difference between the each character and its right-side neighbor in the
pattern and match it to the differences in the input_s characters.
>>> is_match_2("ab", "xy")
True
>>> is_match_2("ab", "xxy")
True
>>> is_match_2("ab", "xyy")
True
>>> is_match_2("ab", "xx")
False
>>> is_match_2("aa", "xy")
False
"""
# Walk through input_s; start pattern comparison at each new i
# Subtract number of changes to avoid index errors in matching
for i in range(len(input_s) - (len(pattern)-1)):
# Start with an unsuccessful array
successes = [0] * (len(pattern)-1)
# Walk through pattern
for j in range(len(pattern)-1):
# Get the difference between ordinals to compare
actual = ord(input_s[i+j]) - ord(input_s[i+j+1])
# If the pattern is going to be long and repeated, we could memoize
# the differences to reduce calculations; but I'm not sure if a
# lookup has the same cost as a simple low-integer subtraction
required = ord(pattern[j]) - ord(pattern[j+1])
if actual == required:
# Mark a success for each match
successes[j] = 1
else:
del successes
break # Go to next i
if sum(successes) == len(pattern) - 1:
# Return as soon as a matching substring is found
return True
return False
################################################################################
if __name__ == '__main__':
import doctest
doctest.testmod()
|
""" n Queens """
from collections import deque
from copy import deepcopy
class Queen(object):
def __init__(self, row):
self.row = row
self.col = None
self.possibles = deque()
def __repr__(self):
return '<Queen ({}, {}) >'.format(self.row, self.col)
def get_possibles(self, grid):
""" Get list of possible coordinates. """
for i in range(grid.bounds):
if grid.layout[self.row][i] == 1:
self.possibles.append(i)
class Grid(object):
def __init__(self, n, layout=None):
self.bounds = n
self.layout = layout if layout else [[1 for i in range(n)] for j in range(n)]
def __repr__(self):
return '<Grid n={} {}>'.format(self.bounds, self.layout)
def update_squares(self, queen):
""" Sets Qs and 0s according to past in coordinates. """
row, col = queen.row, queen.col
self.layout[row] = [0] * self.bounds
self.layout[row][col] = 'Q'
for d in range(1, self.bounds):
# Set rows and cols to limit if statements
all_coords = [(row+d, col-d), (row+d, col), (row+d, col+d)]
# Set possible coordinates, ignoring out-of-bounds, Qs, and 0s
for (i, j) in all_coords:
if ( queen.row <= i < self.bounds and 0 <= j < self.bounds and
self.layout[i][j] == 1 ):
self.layout[i][j] = 0
def do_place_queen(grid, row, queens):
""" Place one Queen in the grid; recursively call down. If Queen cannot be
placed, return False and back track. If successive Queen cannot be
placed, try next possible coordinate. If no possible coordinates remain,
return False and back track.
"""
# Return true if all Queens are placed
if row == grid.bounds:
return True
curr_queen = Queen(row)
curr_queen.get_possibles(grid)
while curr_queen.possibles:
curr_queen.col = curr_queen.possibles.popleft()
new_grid = Grid(grid.bounds, deepcopy(grid.layout))
new_grid.update_squares(curr_queen)
success = do_place_queen(new_grid, row+1, queens)
if success:
queens[row] = curr_queen
return True
return False
def place_all_queens(n):
""" Place all queens on the grid. """
success = False
if type(n) == int and n >= 4:
queens = [0] * n
grid = Grid(n)
row = 0
success = do_place_queen(grid, row, queens)
return queens if success else "Not Possible"
|
# Suppose we have a file with manager and reportee pairs (manager, reportee)
# and we would like to convert this into a tree structure.
#
# Write a function create_mangement_tree which given a list of
# (manager, reportee) pairs creates a tree and returns the root.
#
# Tree Node Data Structure:
#
# class Node(object):
# name = '' # Name of the employee
# reportees = [] # Reportees list of type Node
#
# ===== Example
#
# Alice
# |
# Ben
# / \
# Charlie Denis
#
# == Input
# #
mgr_rpt_pairs = [('Benji', 'Cherise'),
('Alice', 'Benji'),
('Benji', 'Denise'),
('Alice', 'Fiona'),
('Fiona', 'Eva'),
]
#
# == Output
#
# >>> create_mangement_tree(management_pairs)
#
# Node(name='Alice', reportees=[
# Node(name='Benji', reportees=[
# Node(name='Cherise', reportees=[]),
# Node(name='Denise', reportees=[])
# ]),
# Node(name='Fiona', reportees=[
# Node(name='Eva', reportees=[]),
# ]),
# ])
class Employee(object):
def __init__(self, name, reportees=[]):
self.name = name # Name as string;
self.reportees = reportees # Reportees as list of Employees
def __repr__(self):
return "<Employee {}>".format(self.name)
def add_reportee(self, reportee): # reportee as Employee
self.reportees.append(reportee)
def create_management_tree(mgr_rpt_pairs):
inorder(get_management_root(create_employees(mgr_rpt_pairs)))
def inorder(employee, level=0):
""" Given root, prints employee tree. Recurses, printing on the way down. """
if employee:
level += 1
print employee.name
for reportee in employee.reportees:
print " " * level,
inorder(reportee, level)
def create_employees(mgr_rpt_pairs):
""" Create dict of Employee objects. """
employees = {}
for mgr, rpt in mgr_rpt_pairs:
if not rpt in employees:
employees[rpt] = Employee(rpt, [])
if not mgr in employees:
employees[mgr] = Employee(mgr, [employees[rpt]])
else:
employees[mgr].add_reportee(employees[rpt])
return employees
def get_management_root(employees):
""" Return root - employee who is not a reportee - for tree assembly. """
reportees_set = set()
employees_set = set(employees.values())
for emp in employees_set:
reportees_set |= set(emp.reportees)
root = (employees_set - reportees_set).pop()
return root
########################################
if __name__ == '__main__':
create_management_tree(mgr_rpt_pairs)
|
def main():
print("This program illustrates a chaotic function")
n = input("Amount of times to loop?")
x = input("Enter a number between 0 and 1: ")
for i in range(n):
x = 3.9 * x * (1-x)
print(x)
main()
# this doesn't seem to work, the eval doesn't work., page 13
|
import math
from .print_ import print_simplex_table
def table_simplex(table, B, S, W):
print('Starting table simplex:')
print()
print_simplex_table(table, B, S, W)
print()
if any(i!=0 for i in table[-1][:-1]):
print("Cleaning the function from basis variables")
for b in B:
if table[-1][b]!=0:
mult = table[-1][b]
ind = B.index(b)
table[-1] = [i-mult*j for i,j in zip(table[-1],table[ind])]
print_simplex_table(table, B,S,W)
iteration = 0
while any(i<0 for i in table[-1][:-1]):
print()
print('Iteration : {}'.format(iteration))
iteration += 1
print('------------------------')
candidates = [i for i,j in enumerate(table[-1][:-1]) if j<0 and i not in B]
column = candidates[0]
candidates = [ table[i][-1]/table[i][column] if table[i][column]>0 else math.inf for i in range(len(table[:-1]))]
if all(i == math.inf for i in candidates):
print('Upper bounded => No solution!')
return None , B
ind = candidates.index(min(candidates))
print()
print('Pivoting around the element A[{}][{}]'.format(ind,column))
old = table[ind][column]
table[ind] = [i/old for i in table[ind]]
for i in range(len(table)):
if i!=ind:
mult = table[i][column]
table[i] = [ j-mult*k for j,k in zip(table[i],table[ind]) ]
B[ind] = column
print_simplex_table(table, B, S, W)
print()
return table, B
|
from collections import defaultdict
import os.path
from os import path
import numpy as np
# Prints a bar
def print_split():
print("\n--------------------------------------------------\n")
def input_problem():
print("---- NOTE ----\nThe file must be in the following format:\nn MAX\t\t\tWhere n - number of items MAX - Maximum allowed weight\nW0 W1 W2 W3 ... Wn\nP0 P1 P2 P3 ... Pn")
print_split()
file_name = input("Enter the file name: ")
# Creating absolute path to the file in folder examples
file_dir = os.path.dirname(__file__)
rel_path = "examples/" + file_name
abs_file_path = os.path.join(file_dir, rel_path)
# Checking if the file exists
if os.path.exists(abs_file_path) == False:
# File not found, throw error
print("The file doesn't exist!")
raise Exception("The file didn't load because it doesn't exist")
# File found, opening
f = open(abs_file_path, 'r')
n, max_weight = [int(x) for x in next(f).split()] # Reads the dimensions and max weight
weights = []
prices = []
weights = next(f).split()
for i in range(0, len(weights)):
weights[i] = int(weights[i])
prices = next(f).split()
for i in range(0, len(prices)):
prices[i] = int(prices[i])
f.close()
return n, weights, prices, max_weight
# Iterative solution for Knapsack
# Returns the maximum value that can
# be put in a knapsack of a given capacity
def knapsack(max_weight, weights, prices, n):
F = [[0 for x in range(max_weight + 1)] for x in range(n + 1)]
# Building matrix F[][] from the bottom-up
for i in range(n + 1):
for max_weight in range(max_weight + 1):
if i == 0 or max_weight == 0:
F[i][max_weight] = 0
elif weights[i-1] <= max_weight:
F[i][max_weight] = max(prices[i-1] + F[i-1][max_weight-weights[i-1]], F[i-1][max_weight])
else:
F[i][max_weight] = F[i-1][max_weight]
return F, F[n][max_weight]
def main():
n, weights, prices, max_weight = input_problem()
print()
F, solution = knapsack(max_weight, weights, prices, n)
F = np.array(F)
print("F:\n", F)
print_split()
print("Maximal basket value: ", solution)
if __name__ == '__main__':
main()
|
import os.path
from os import path
import sys
import numpy as np
from .print_ import print_split
def input_vars():
sol_set = 'N'
option = 2
while option != 1 or option != 2:
if option == 1:
print("---- NOTE ----\nThe input must be in the following format:\nN M\t\t\t\tWhere N - number of rows and M - number of columns\n\"max\"\t\t\tObjective function maximisation\nc1 c2 c3 ... cM\na1 a2 a3 a4 ... aM _ b\n for x1, x2, x3, ... xM >= 0\t\tWhere '_' should be '<=', '>=' or '='\n'x y' or 'N0'\t\tFor xi in set [x, y], or 'N0' for xi in set N0[0, +inf]")
print_split()
n = int(input("Input the number of constraints: "))
m = int(input("Input the number of variables: "))
# Reserving and initializing space for the Objective function
in_c = np.empty(m)
# Reserving and initializing space for the coeficients
in_A = np.empty(m)
# Reserving and initializing space for the solution values
in_b = 0
otype = input("Input \"min\" or \"max\" for the Objective function: ")
if otype != "min" and otype != "max":
raise Exception("The Objective function type is wrong it should be either \"min\" or \"max\"!\n")
# Input the Objective function
tmp = input("Objective function: ").split()
i = 0
for c in tmp:
in_c[i] = int(c)
i += 1
'''
# Converting the Objective function to minimise since the program is made with minimisation
if otype == "max":
print("Converting max to min.")
in_c *= -1
'''
sign = ''
# Input a line to a tmp variable
tmp = input(str(i) + ": ").split()
for j in range(m):
in_A[j] = int(tmp[j])
sign = tmp[m]
in_b = int(tmp[m + 1])
if sign == '>=':
in_A *= -1
if otype == 'min':
in_c *= -1
'''
# No transformation required, since this program works with "<="
# And "=" can be represented both as ">=" and "<="
if sign[i] == "=":
continue
# If the entered sign is ">" than we transform it to "<"
if sign[i] == ">":
for j in range(m):
in_A[i, j] *= -1
in_b[i] *= -1
# Add new variables to convert inequation to equation:
# x1 + x2 + x3 + ... + xn <= c
# => x1 + x2 + x3 + ... + xn + x = c
# Thus appending a canonical matrix at the end
for i in range(n):
if sign[i] == "=":
continue
tmp = np.zeros(n)
for j in range(n):
if i == j:
tmp[j] = 1
break
in_A = np.c_[in_A, tmp]
# Append 0 to the Objective function to make it the right dimension
in_c = np.append(in_c, 0)
'''
print_split()
break
elif option == 2:
print("---- NOTE ----\nEnter the relative path to the file, from under \"/examples/\" \ne.g. For file 1.txt, write \"1.txt\", that will load \"/examples/1.txt\"")
print_split()
print("---- NOTE ----\nThe input must be in the following format:\nN M\t\t\t\tWhere N - number of rows and M - number of columns\n\"max\"\t\t\tObjective function maximisation\nc1 c2 c3 ... cM\na1 a2 a3 a4 ... aM _ b\n for x1, x2, x3, ... xM >= 0\t\tWhere '_' should be '<=', '>=' or '='\n'x y' or 'N0'\t\tFor xi in set [x, y], or 'N0' for xi in set N0[0, +inf]")
print_split()
print_split()
file_name = input("Enter the file name: ")
# Creating absolute path to the file in folder examples
file_dir = os.path.dirname(__file__)
rel_path = "examples/" + file_name
abs_file_path = os.path.join(file_dir, rel_path)
# Checking if the file exists
if os.path.exists(abs_file_path) == False:
# File not found, throw error
print("The file doesn't exist!")
raise Exception("The file didn't load because it doesn't exist")
# File found, opening
f = open(abs_file_path, 'r')
in_c = []
# Read 2 first lines
for i in range(3):
if i == 0:
t = next(f).split()
n = int(t[0]) # Reads the dimensions
m = int(t[1]) # Reads the dimensions
if i == 1:
otype = next(f).split()
otype = otype[0]
if otype != "min" and otype != "max":
f.close()
raise Exception("The Objective function type is wrong it should be either \"min\" or \"max\"!\n")
if i == 2:
in_c = np.append(in_c, [int(x) for x in next(f).split()]) # Reads the Objective functiom
# Converting the Objective function to minimise since the program is made with maximization
# if otype == "min":
# print("Converting min to max.")
# in_c *= -1
tmp_array = []
for line in f: # Read the next lines
tmp_array.append([str(x) for x in line.split()])
f.close() # File not needed, all is in tmp_array
# Formatting the input
in_A = []
sign = []
in_b = []
# print(tmp_array)
for i in range(n):
for j in range(m + 2):
if j < m:
in_A.append(float(tmp_array[i][j]))
elif j == m:
sign.append(tmp_array[i][j])
elif j == (m + 1):
in_b.append(float(tmp_array[i][j]))
# Reading solution set
tmp = tmp_array[-1]
if len(tmp) == 2 and tmp[0].isdigit() and tmp[1].isdigit():
sol_set = "cust"
lb = int(tmp[0])
ub = int(tmp[1])
print(f"Solution set: [{lb}, {ub}]")
if lb > ub or lb < 0:
f.close()
raise Exception("Ivalid bounds!")
elif len(tmp) == 1 and tmp[0].lower() == 'n':
print("Solution set: [0, +inf]")
sol_set = 'inf'
lb = 0
ub = 'inf'
else:
f.close()
raise Exception("Invalid solution set!")
f.close()
'''
# No transformation required, since this program works with "<"
# And "=" can be represented both as ">=" and "<="
if sign[i] == "=":
continue
# If the entered sign is ">" than we transform it to "<"
if sign[i] == ">":
in_A_length = len(in_A)
for j in range(i*m, in_A_length, 1):
in_A[j] *= -1
in_b[i] *= -1
'''
for i in range(n):
if sign[i] == ">=":
in_A[i] *= -1
in_b[i] *= -1
sign[i] = "<="
# Converting the final list to numpy array
in_A = np.array(in_A)
in_A = in_A.reshape(n, m)
'''
# Add new variables to convert inequation to equation:
# x1 + x2 + x3 + ... + xn <= c
# => x1 + x2 + x3 + ... + xn + x = c
# Thus appending a canonical matrix at the end
for i in range(n):
if sign[i] == "=":
continue
tmp = np.zeros(n)
for j in range(n):
if i == j:
tmp[j] = 1
break
in_A = np.c_[in_A, tmp]
# Append 0 to the Objective function to make it the right dimension
in_c = np.append(in_c, 0)
'''
break
else:
option = int(input("Select the type of input:\n\t1: Manual input\n\t2: Input from file\nSelected: "))
print_split()
return n, m, otype, in_c, in_A, sign, in_b, sol_set, lb, ub
|
import os.path
from os import path
# Prints a bar
def print_split():
print("\n--------------------------------------------------\n")
def input_graph():
print("---- NOTE ----\nThe file must be in the following format:\nX\t\t\tX - Number of nodes\nN0 N1\nN1 N3\nN0 N3\n....\n....")
print_split()
file_name = input("Enter the file name: ")
# Creating absolute path to the file in folder examples
file_dir = os.path.dirname(__file__)
rel_path = "examples/" + file_name
abs_file_path = os.path.join(file_dir, rel_path)
# Checking if the file exists
if os.path.exists(abs_file_path) == False:
# File not found, throw error
print("The file doesn't exist!")
raise Exception("The file didn't load because it doesn't exist")
# File found, opening
f = open(abs_file_path, 'r')
# Read if the graph is directed or undirected
no_nodes = next(f).split()
no_nodes = int(no_nodes[0])
# Read the graph
graph = [[int(x) for x in line.split()] for line in f]
f.close() # File not needed, all is in tmp_array
return graph, no_nodes
class Graph:
def __init__(self, nodes):
self.graph = []
self.nodes = nodes
self.total = 0
def add_edge(self, p, c, weight):
self.graph.append([p, c, weight])
# BFS iterative implementation using queue
def find(self, parent, i):
if parent[i] == i:
return i
return self.find(parent, parent[i])
# A function that does union of two sets of x and y
def union(self, parent, rank, x, y):
xroot = self.find(parent, x)
yroot = self.find(parent, y)
# Attach smaller rank tree under root of
# high rank tree (Union by Rank)
if rank[xroot] < rank[yroot]:
parent[xroot] = yroot
elif rank[xroot] > rank[yroot]:
parent[yroot] = xroot
# If ranks are the same, then make it a root
# and increment the rank by one
else:
parent[yroot] = xroot
rank[xroot] += 1
# The main function to construct MST using Kruskal's algorithm
def kruskal(self):
result = []
i = 0 # Sorted graph index
e = 0 # result[] index
# Step 1: Sort the graph weights in non-decreasing order.
self.graph = sorted(self.graph, key = lambda item:item[2])
parent = []
rank = []
# Create node subsets with single elements
for node in range(self.nodes):
parent.append(node)
rank.append(0)
# Number of graph to be taken is equal to V-1
while e < self.nodes -1 :
# Step 2: Pick the smallest edge and increment the index for next iteration
p, c, weight = self.graph[i]
i = i + 1
x = self.find(parent, p)
y = self.find(parent, c)
# If inclusion of this edge doesn't create the cycle, include it in the result
# and increment the index of result for next edge
if x != y:
e = e + 1
result.append([p, c, weight])
self.union(parent, rank, x, y)
self.total = self.total + weight
# Else discard the edge
print ("Minimal spanning tree from the graph: ")
for p, c, weight in result:
print (str(p) + " -- " + str(c) + ", weight(" + str(weight) + ")")
def main():
graph, no_nodes = input_graph()
g = Graph(no_nodes)
for i in range(len(graph)):
g.add_edge(graph[i][0], graph[i][1], graph[i][2])
g.kruskal()
print("Weight: ", g.total)
print_split()
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
def my_factorial(n):
assert n >= 0
result = 1
if (n==0):
return 1
for i in range(2, n+1):
result = result * i
return result
|
with open("Day1Input.txt","r") as file:
lines = file.readlines()
freq = 0
for line in lines:
sign = line[0]
value = int(line[1:])
if sign == "-":
value = value * -1
freq = freq + value
print(freq)
|
def player_1():
global numbs1,score1,lis1,continuety
while continuety:
print("Welcome: {} ".format(numbs1))
index1 = int(input("Player#1 – score {}:".format(score1)))
index2 = int(input("Player#1 – score {}:".format(score1)))
if lis1[index1] == "*" and lis1[index2] == "*" or index1 == index2:
print("Invalid both position")
elif lis1[index1] == lis1[index2]:
score1 = score1 + 1
print(lis1[index1], lis1[index2])
numbs1.remove(index1)
numbs1.remove(index2)
lis1 = list(lis1)
lis1[index1] = "*"
lis1[index2] = "*"
lis1 = "".join(lis1)
print(lis1)
elif lis1[index1] == "*":
print("Invalid first position ")
elif lis1[index2] == "*":
print("Invalid second position")
else:
print(lis1[index1], lis1[index2])
numbs1.remove(index1)
numbs1.remove(index2)
lis1 = list(lis1)
lis1[index1] = "*"
lis1[index2] = "*"
lis1 = "".join(lis1)
print(lis1)
continuety = False
def player_2():
global numbs2,score2,lis2,continuety
while continuety :
print("Welcome: {} ".format(numbs2))
index3 = int(input("Player#2 – score {}:".format(score2)))
index4 = int(input("Player#2 – score {}:".format(score2)))
if lis2[index3] == "*" and lis2[index4] == "*" or index3 == index4:
print("Invalid both position")
elif lis2[index3] == lis2[index4]:
score2 = score2 + 1
print(lis2[index3], lis2[index4])
numbs2.remove(index3)
numbs2.remove(index4)
lis2 = list(lis2)
lis2[index3] = "*"
lis2[index4] = "*"
lis2 = "".join(lis2)
print(lis2)
elif lis2[index3] == "*":
print("Invalid first position ")
elif lis2[index4] == "*":
print("Invalid second position")
else:
print(lis2[index3], lis2[index4])
numbs2.remove(index3)
numbs2.remove(index4)
lis2 = list(lis2)
lis2[index3] = "*"
lis2[index4] = "*"
lis2 = "".join(lis2)
print(lis2)
lis1 = "FZXVLGHASDZLXVADHFGS"
score1 = 0
numbs1 = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
#Player 2 status########################
lis2 = "ABDCHFGZLKGACDFLZBHK"
score2 = 0
numbs2 = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]
continuety = True
while True :
if numbs1 == [] and numbs2 == [] :
if score1 > score2 :
print("__________________________________Player 1 is Won_____________________________________")
break
elif score2 > score1:
print("__________________________________Player 2 is Won_____________________________________")
break
else:
print("______________________________________DRAW_________________________________________")
break
print("Welcome: {} ".format(numbs1))
index1=int(input("Player#1 – score {}:".format(score1)))
index2=int(input("Player#1 – score {}:".format(score1)))
if lis1[index1] == "*" and lis1[index2] == "*" or index1 == index2 :
print("Invalid both position")
player_1()
elif lis1[index1] == lis1[index2] :
score1 = score1+1
print(lis1[index1], lis1[index2])
numbs1.remove(index1)
numbs1.remove(index2)
lis1=list(lis1)
lis1[index1] = "*"
lis1[index2] = "*"
lis1 = "".join(lis1)
print(lis1)
elif lis1[index1] == "*" :
print("Invalid first position ")
player_1()
elif lis1[index2] == "*" :
print("Invalid second position")
player_1()
else:
print(lis1[index1], lis1[index2])
numbs1.remove(index1)
numbs1.remove(index2)
lis1 = list(lis1)
lis1[index1] = "*"
lis1[index2] = "*"
lis1 = "".join(lis1)
print(lis1)
##Player 2 #########################################################
print("__________________________________Clear____________________________________")
print("Welcome: {} ".format(numbs2))
index3=int(input("Player#2 – score {}:".format(score2)))
index4=int(input("Player#2 – score {}:".format(score2)))
if lis2[index3] == "*" and lis2[index4] == "*" or index3 == index4 :
print("Invalid both position")
player_2()
elif lis2[index3] == lis2[index4] :
score2 = score2+1
print(lis2[index3], lis2[index4])
numbs2.remove(index3)
numbs2.remove(index4)
lis2=list(lis2)
lis2[index3] = "*"
lis2[index4] = "*"
lis2 = "".join(lis2)
print(lis2)
elif lis2[index3] == "*" :
print("Invalid first position ")
player_2()
elif lis2[index4] == "*" :
print("Invalid second position")
player_2()
else:
print(lis2[index3], lis2[index4])
numbs2.remove(index3)
numbs2.remove(index4)
lis2 = list(lis2)
lis2[index3] = "*"
lis2[index4] = "*"
lis2 = "".join(lis2)
print(lis2)
print("__________________________________Clear____________________________________")
|
numlist = [9, 41, 32, 2, 121, 5, 73]
max = numlist[0]
for i in numlist:
if i > max:
max = i
print(max)
|
# Primality test - Check if a number is prime or not
from math import sqrt, ceil
marked = []
try:
num = int(input("Enter the number to check if it is prime : "))
except(ValueError):
print("Please Enter a real number greater than 1 or less than -1")
quit()
num_sq = ceil(sqrt(abs(num)))
flag = False
for i in range(2, num_sq + 1):
if(num % i == 0):
flag = True
break
if(flag == True or num == 1 or num == 0):
print("Not a prime")
else:
print("It is a prime number")
|
# insertion sort
# Holding onto each element (and moving others) and then trying
# to find it's position in the list according to those positions
# iterating over each element till it is completely sorted is called insertion sort
unsorted = [3,2,5,4,1,6,7,8,22,32,43,12,54,65,87,98,78,79,90,12]
for i in range(len(unsorted)-1):
current = unsorted[i]
j = i - 1
while(j >= 0 and unsorted[j] > current):
unsorted[j+1] = unsorted[j]
j-=1
unsorted[j+1] = current
print(unsorted)
|
import math
def get_prime(n):
if n <= 1:
return []
prime = [2]
limit = int(math.sqrt(n))
print(limit)
# 奇数のリスト作成
data = [i for i in range(3, n + 1, 2)]
while limit > data[0]:
print('prime')
print(prime)
print('data')
print(data)
prime.append(data[0])
# 割り切れない数だけを取り出す
data = [j for j in data if j % data[0] != 0]
return prime + data
print(get_prime(101))
|
def tower_builder(n_floors):
floors = []
stars = 1
space = n_floors - 1
for floor in range(n_floors):
floors.append(' ' * space + '*' * stars + space * ' ')
#print(floors)
stars += 2
space -= 1
print(floors)
return floors
#test.assert_equals(tower_builder(1), ['*', ])
#test.assert_equals(tower_builder(2), [' * ', '***'])
#test.assert_equals(tower_builder(3), [' * ', ' *** ', '*****'])
|
#https://www.hackerrank.com/challenges/countingsort4
N = input()
countmap = {}
for i in range(0, N):
line = raw_input().strip().split()
num = int(line[0])
countmap.setdefault(num, [])
if i < N/2 :
countmap[num].append('-')
else :
countmap[num].append(line[1])
out = []
for key, value in countmap.items():
out.append(' '.join(value))
print ' '.join(out)
|
#https://www.hackerrank.com/challenges/find-digits
T = input()
for i in range(0, T):
N = input()
out = [n for n in list(str(N)) if int(n) and int(N) % int(n) == 0]
print len(out)
|
print("Input -1 for wanted & -2 for unwanted")
vo = input("Initial velocity : ") * 1.0
v = input("Velocity : ") * 1.0
a = input("Acceleration : ") * 1.0
t = input("Time : ") * 1.0
d = input("Distance : ") * 1.0
print " "
if vo == -2:
print "Impossible"
if v == -1:
if a == -2:
print ("Velocity = " + str(((d * 2) / t) - vo))
elif t == -2:
print ("Velocity = " + str((vo**2 + (2 * d * a))**0.5))
elif d == -2:
print ("Velocity = " + str(vo + a * t))
elif vo == -1:
if v == -2:
print "Impossible"
elif a == -2:
print ("Initial Velocity = " + str(((d * 2) / t ) - v))
elif t == -2:
print ("Initial Velocity = " + str(v**2 - (2 * a * d)))
elif d == -2:
print ("Initial Velocity = " + str(v - a * t))
elif a == -1:
if v == -2:
print ("Acceleration = " + str ((d - vo * t) / (2 * t**2)))
elif t == -2:
print ("Acceleration = " + str((v**2 - vo**2) / (2 * d)))
elif d == -2:
print ("Acceleration = " + str ((v - vo) / t))
elif t == -1:
if v == -2:
print ("That's some trig stuff do it yourself you lazy piece of trash <3")
elif a == -2:
print ("Time = " + str(d * 2 / (vo + v)))
elif d == -2:
print ("Time = " + str ((v - vo) / a))
elif d == -1:
if v == -2:
print ("Distance = " + str ((vo * t) + 0.5 * a * t**2))
elif a == -2:
print ("Distance = " + str(0.5 * (vo + v) * t))
elif t == -2:
print ("Distance = " + str((v**2 - vo**2) / 2 * a))
|
"""
This class will filter the information inside a Document
and return a filtered (SAME) Document.
"""
from document import *
from sentence import *
class TextFilter:
"""
Applies a list of filter to a document and returns same filtered Document
"""
def __init__(self, filterList=None, doc=None):
self.__filterList = filterList
self.__doc = doc
def setFilterList(self, filterList):
"""
Set a list of filters
"""
self.__filterList = filterList
def setDoc(self, doc):
"""
Set document that you're applying filters to
"""
self.__doc = doc
def apply(self, doc=None):
"""
doc is the Document we are applying each filter in the filterlist to
"""
#for each filter in the list, apply the filter
for x in range(len(self.__filterList)):
currFilter = self.__filterList[x]
if currFilter == "normalizeWhiteSpace":
self.normalizeWhiteSpace()
elif currFilter == "normalizeCase":
self.normalizeCase()
elif currFilter == "stripNull":
self.stripNull()
elif currFilter == "stripNumbers":
self.stripNumbers()
elif currFilter == "stripFiles":
self.stripFiles()
else:
#Raise exception if non-existent filter is applied
raise TextFilterException('You entered an invalid filter')
#Return the filtered document
return doc
def normalizeWhiteSpace(self):
"""
Post: removes extra (meaning more than one character) white space
from a document
"""
doc = self.__doc
sCount = doc.getSCount()
#For each sentence in the document
for sentence in range(sCount):
currSentence = doc[sentence]
#Split sentence into strings of non-whitespace characters
#Join with a single white-space
filtSen = ' '.join(currSentence.split())
doc[sentence] = Sentence(filtSen)
def normalizeCase(self):
"""
Post: normalizes the characters in a document to lowercase
"""
doc = self.__doc
sCount = doc.getSCount()
#For each sentence in the document
for sentence in range(sCount):
currSentence = doc[sentence]
#use .lower() function to make all characters lowercase
lowerCase = currSentence.lower()
doc[sentence] = Sentence(lowerCase)
def stripNull(self):
"""
Post: strips all characters that are not numbers or letters from a document
"""
doc = self.__doc
sCount = doc.getSCount()
#For each sentence in the document
for sentence in range(sCount):
currSentence = doc[sentence]
#For each word in the sentence
for word in currSentence:
#For each character in the word
for ch in word:
#If the character is not a number or a letter, get rid and join surrounding characters
if not ch.isalnum() and ch != ' ':
currSentence = currSentence.replace(ch, "")
doc[sentence] = Sentence(currSentence)
def stripNumbers(self):
"""
Post: strips all characters that are numbers from a document
"""
doc = self.__doc
sCount = doc.getSCount()
#For each sentence in the document
for sentence in range(sCount):
currSentence = doc[sentence]
#Get rid of any character that is a number
stripSen = ''.join(i for i in currSentence if not i.isdigit())
doc[sentence] = Sentence(stripSen)
def stripFiles(self):
"""
Post: strips all words found in a given file (for now we have
created a mock file holding some words to strip)
"""
doc = self.__doc
stripWords = [line.rstrip('\n') for line in open('wordstrip.txt')]
#stripWords = ['fight', 'october', 'delta']
sCount = doc.getSCount()
#For each sentence in the document
for sentence in range(sCount):
currSentence = doc[sentence]
#For each word in the document
for word in currSentence.split():
#If the word is found in the wordstrip file, get rid of it
if word in stripWords:
currSentence = currSentence.replace(word, "")
doc[sentence] = Sentence(currSentence)
def testTestFilter():
"""
Put your test for the filter class here
"""
#Set up a mock document
d = Document()
#Set document's sentences
d[0] = Sentence('This is8 the first 98 delta sentence4 in my email @')
print('Original: ', d[0])
#set up a list of filters
testFList = ['normalizeCase','stripNull','stripNumbers', 'stripFiles','normalizeWhiteSpace']
#apply filters
test = TextFilter(testFList, d)
test.apply(d)
print('Filtered: ', d[0])
if __name__ == "__main__":
testTestFilter()
|
#함수형모델을 2개를 만들어라
#1. 데이터
import numpy as np
#모델1.
x1 = np.array([range(1,101), range(711,811), range(100)])
y1 = np.array([range(101,201), range(311, 411), range(100)])
x1 = np.transpose(x1)
y1 = np.transpose(y1)
print(x1.shape) #(100, 3) output 3
#모델2.
x2 = np.array([range(4,104), range(761,861), range(100)])
y2 = np.array([range(501,601), range(431,531), range(100,200)])
x2 = np.transpose(x2)
y2 = np.transpose(y2)
print(x2.shape) #(100, 3)
#train, test분리 (슬라이싱 대신에 train_test_split)
from sklearn.model_selection import train_test_split
x1_train, x1_test, y1_train, y1_test = train_test_split(x1, y1, shuffle=True, train_size =0.7)
x2_train, x2_test, y2_train, y2_test = train_test_split(x2, y2, shuffle=True, train_size =0.7)
#함수형 모델 만들기
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, Input
#모델1.
input1 = Input(shape =(3,))
dense1 = Dense(10, activation='relu', name='king1')(input1) #모델 이름이 중복될 때 , 혹은 dense이름 변경
dense2 = Dense(7, activation='relu', name='king2')(dense1)
dense3 = Dense(5, activation='relu', name='king3')(dense2)
output1 = Dense(3, activation ='linear', name='king4')(dense3)
#모델2.
input2 = Input(shape =(3,))
dense1_1 = Dense(15, activation='relu')(input2)
dense2_1 = Dense(11, activation='relu')(dense1_1)
output2 = Dense(3, activation ='linear')(dense2_1)
#모델끼리는 별 영향을 끼치지 않는다
##########모델 병합, concantenate 여러가지 방법으로import
from tensorflow.keras.layers import Concatenate, concatenate
# from keras.layers.merge import Concatenate, concatenate
# from keras.layers import Concatentate, concatenate
#########모델 2개 병합하기
#소문자 concatenate
#merge1 = concatenate([output1, output2])#리스트로 묶기
#방법 1. Concatenate대문자 사용법
#merge1 = Concatenate()([output1, output2]) #대문자 Concatenate 면 class다
#방법 2.
merge1 = Concatenate(axis=1)([output1, output2]) #axis축
middle1 = Dense(30)(merge1) #함수형으로 모델 병합하기
middle1 = Dense(7)(middle1)
middle1 = Dense(11)(middle1)
'''
merge1 = concatenate([output1, output2])#리스트로 묶기
#앞에 변수명 같이 명시 해도 가능.
middle1 = Dense(30)(merge1) #함수형으로 모델 병합하기
middle2 = Dense(7)(middle1)
middle3 = Dense(11)(middle2) #이렇게 middle1도 가능?
'''
########### output 만들기 (분기)
output3 = Dense(30)(middle1)#middle1에서 받아온다
output3_1 = Dense(7)(output3)
output3_2 = Dense(3)(output3_1)#outputs에 마지막 아웃풋 넣기
output4 = Dense(15)(middle1)
output4_1 = Dense(14)(output4)
output4_2 = Dense(11)(output4_1)
output4_3 = Dense(3)(output4_2)#마지막 아웃풋 넣기
#모델 정의하기
model = Model (inputs =[input1, input2], outputs =[output3_2, output4_3])
#모델 1,2넣기
model.summary()
#concatenate는 연산하지 않고 병합만 해준다
# 컴파일, 훈련
model.compile(loss= 'mse', optimizer='adam', metrics=['mae'])
model.fit([x1_train, x2_train], [y2_train, y2_train], epochs=100, batch_size=8, validation_split=0.25, verbose=1)
# 평가
result = model.evaluate([x1_test, x2_test],[y1_test,y2_test], batch_size=8)
# (loss, 메트릭스의 mse)가 나온다
print('result:' , result)
#result: [62924.65234375, 62796.45703125, 128.2028350830078, 204.76409912109375, 7.117029666900635] 총 5개 나옴
#앙상블에서 output이 2개 이기 때문에 모델1, 모델2 각각 훈련한다.
#첫번째값은 모델전체의 아웃풋(모델1아웃풋값+모델2아웃풋값의더한값), 모델1의 마지막아웃풋, 모델2의 마지막아웃풋, 모델1의메트릭스mse값, 모델2의 메트릭스 mse값
#앙상블을 3개 합치면 result값이 7개
|
# RNN 기법에는 LSTM 말고도 SimpleRNN과 GRU가 있다. 두개 다 구축해보고 LSTM과 성능을 비교해보기.
#1. 데이터
import numpy as np
x=np.array([[1,2,3], [2,3,4], [3,4,5], [4,5,6]]) #(4,3)
y=np.array([4,5,6,7]) #(4,)
print("x.shape : ", x.shape)
print("y.shape : ", y.shape)
x=x.reshape(x.shape[0], x.shape[1], 1)
print("x.shape : ", x.shape)
#2. 모델 구성
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, LSTM, SimpleRNN
model=Sequential()
model.add(SimpleRNN(10, activation='relu', input_length=3, input_dim=1))
model.add(Dense(30))
model.add(Dense(100))
model.add(Dense(30))
model.add(Dense(1))
model.summary()
#simple RNN params = = (노드 * 노드) + (input_dim * 노드) + biases = (10*10)+(1*10) + 10= 120
# = (input_dim + 노드) * 노드 + biases = (1 + 10) * 10 + 10 = 120
'''
model.compile(loss='mse', optimizer='adam')
model.fit(x, y, epochs=100, batch_size=1, validation_split=0.3)
x_input=np.array([5,6,7]) #(3,) ->(1,3,1)
x_input=x_input.reshape(1,3,1)
y_predict=model.predict(x_input)
print("y_predict : ", y_predict)
'''
|
# import
import os
import csv
# csv file pulling and reading
csvfile = os.path.join("..", "PyBank", "budget_data.csv")
with open(csvfile, 'r') as bankfile:
bank_reader = csv.reader(bankfile, delimiter=',')
bank_header = next(bank_reader)
months = []
monthlyprofitloss = []
totalprofitloss = 0
greatestprofit = 0
greatestloss = 0
for row in bank_reader:
months.append(row[0])
totalprofitloss += int(row[1])
monthlyprofitloss.append(int(row[1]))
greatestprofit = max(monthlyprofitloss)
greatestloss = min(monthlyprofitloss)
if int(row[1]) == greatestprofit:
greatestprofitmonth = row[0]
if int(row[1]) == greatestloss:
greatestlossmonth = row[0]
averagechange = round(totalprofitloss/len(months), 2)
print(f'Number of months: {len(months)}')
print(f'Net total of Profit/Losses: $ {totalprofitloss}')
print(f'Average change in Profit/Losses: $ {averagechange}')
print(f'The greatest increase in profits: {greatestprofitmonth} $ {greatestprofit}')
print(f'The greatest decrease in losses: {greatestlossmonth} $ {greatestloss}')
with open("summary.txt", 'w') as summary:
summary.write("Financial Analysis" "\n" "---------------------------------------" "\n")
summary.write(f'Number of months: {len(months)}''\n')
summary.write(f'Net total of Profit/Losses: $ {totalprofitloss}''\n')
summary.write(f'Average change in Profit/Losses: $ {averagechange}''\n')
summary.write(f'The greatest increase in profits: {greatestprofitmonth} $ {greatestprofit}''\n')
summary.write(f'The greatest decrease in losses: {greatestlossmonth} $ {greatestloss}''\n')
|
import os
import csv
import traceback
class BaseCar:
"""This is a base vehicle class"""
def __init__(self, car_type=None,
photo_file_name=None,
brand=None, carrying=0.0):
self._car_type = car_type
self._photo_file_name = photo_file_name
self._brand = brand
self._carrying = carrying
def __repr__(self):
return f"{str.capitalize(self.car_type)}({self.brand}, {self.photo_file_name}, {self.carrying})"
@property
def car_type(self):
return self._car_type
@property
def photo_file_name(self):
return self._photo_file_name
@property
def brand(self):
return self._brand
@property
def carrying(self):
return self._carrying
def get_photo_file_ext(self):
os.path.splitext(self.photo_file_name)[1]
class Car(BaseCar):
"""Class describing an ordinary car"""
def __init__(self, photo_file_name=None,
brand=None, carrying=0,
passenger_seats_count=5):
super().__init__(car_type="car",
photo_file_name=photo_file_name,
brand=brand, carrying=carrying)
self._passenger_seats_count = passenger_seats_count
@property
def passenger_seats_count(self):
return self._passenger_seats_count
class Truck(BaseCar):
"""Class describing a truck"""
def __init__(self, photo_file_name=None,
brand=None, carrying=0.0,
body_width=0.0, body_height=0.0,
body_length=0.0):
super().__init__(car_type="truck",
photo_file_name=photo_file_name,
brand=brand, carrying=carrying)
self._body_width = body_width
self._body_height = body_height
self._body_length = body_length
@property
def body_width(self):
return self._body_width
@property
def body_height(self):
return self._body_height
@property
def body_length(self):
return self._body_length
def get_body_volume(self):
return self.body_width * self.body_height * self.body_length
class SpecMachine(BaseCar):
"""Special machine class"""
def __init__(self, photo_file_name=None,
brand=None, carrying=0,
extra=None):
super().__init__(car_type="spec_machine",
photo_file_name=photo_file_name,
brand=brand, carrying=carrying)
self._extra = extra
@property
def extra(self):
return self._extra
def parse_car(csv_row):
cartype_to_attrnum = {
'car': (5,),
'truck': (4, 5),
'spec_machine': (5,)
}
min_col = min(min(cartype_to_attrnum.values()))
reduced_row = [el for el in csv_row if el]
if len(reduced_row) < min_col:
raise RuntimeError("insufficient collumns number")
car_type = reduced_row[0]
it = iter(reduced_row)
next(it)
if car_type == "car":
if len(reduced_row) not in cartype_to_attrnum[car_type]:
raise RuntimeError("car: wrong collumns number")
brand, passenger_seats_count, photo_file_name, carrying = it
try:
passenger_seats_count = int(passenger_seats_count)
carrying = float(carrying)
except (ValueError, TypeError):
raise
return Car(photo_file_name=photo_file_name,
brand=brand, carrying=carrying,
passenger_seats_count=passenger_seats_count)
elif car_type == "truck":
if len(reduced_row) not in cartype_to_attrnum[car_type]:
raise RuntimeError("truck: wrong collumns number")
brand = photo_file_name = body_whl = carrying = ""
if len(reduced_row) == 5:
brand, photo_file_name, body_whl, carrying = it
else:
brand, photo_file_name, carrying = it
try:
body_whl = body_whl.split('x')
if len(body_whl) not in (1, 3):
raise RuntimeError("body_whl: wrong parameters number")
if len(body_whl) == 1:
body_width = body_height = body_length = 0.0
else:
body_whl = map(lambda el: float(el) if el else 0.0, body_whl)
body_width, body_height, body_length = body_whl
carrying = float(carrying)
except (ValueError, TypeError):
raise
return Truck(photo_file_name=photo_file_name,
brand=brand, body_width=body_width,
body_height=body_height,
body_length=body_length,
carrying=carrying)
elif car_type == "spec_machine":
if len(reduced_row) not in cartype_to_attrnum[car_type]:
raise RuntimeError("spec_machine: wrong collumns number")
brand, photo_file_name, carrying, extra = it
try:
carrying = float(carrying)
except (ValueError, TypeError):
raise
return SpecMachine(photo_file_name=photo_file_name,
brand=brand, carrying=carrying,
extra=extra)
def get_car_list(csv_filename):
car_list = []
with open(csv_filename) as csv_fd:
reader = csv.reader(csv_fd, delimiter=';')
next(reader)
for row in reader:
try:
car = parse_car(row)
car_list.append(car)
except (RuntimeError, ValueError, TypeError):
# traceback.print_exc()
continue
return car_list
def _main():
print(get_car_list("coursera_week3_cars.csv"))
if __name__ == "__main__":
_main()
"""Reference solution:
import csv
import sys
import os.path
class CarBase:
\"""Базовый класс с общими методами и атрибутами\"""
# индексы полей, которые соответствуют колонкам в исходном csv-файле
ix_car_type = 0
ix_brand = 1
ix_passenger_seats_count = 2
ix_photo_file_name = 3
ix_body_whl = 4
ix_carrying = 5
ix_extra = 6
def __init__(self, brand, photo_file_name, carrying):
self.brand = brand
self.photo_file_name = photo_file_name
self.carrying = float(carrying)
def get_photo_file_ext(self):
_, ext = os.path.splitext(self.photo_file_name)
return ext
class Car(CarBase):
\"""Класс легковой автомобиль\"""
car_type = "car"
def __init__(self, brand, photo_file_name, carrying, passenger_seats_count):
super().__init__(brand, photo_file_name, carrying)
self.passenger_seats_count = int(passenger_seats_count)
@classmethod
def from_tuple(cls, row):
\""" Метод для создания экземпляра легкового автомобиля
из строки csv-файла\"""
return cls(
row[cls.ix_brand],
row[cls.ix_photo_file_name],
row[cls.ix_carrying],
row[cls.ix_passenger_seats_count],
)
class Truck(CarBase):
\"""Класс грузовой автомобиль\"""
car_type = "truck"
def __init__(self, brand, photo_file_name, carrying, body_whl):
super().__init__(brand, photo_file_name, carrying)
# обрабатываем поле body_whl
try:
length, width, height = (float(c) for c in body_whl.split("x", 2))
except ValueError:
length, width, height = .0, .0, .0
self.body_length = length
self.body_width = width
self.body_height = height
def get_body_volume(self):
return self.body_width * self.body_height * self.body_length
@classmethod
def from_tuple(cls, row):
return cls(
row[cls.ix_brand],
row[cls.ix_photo_file_name],
row[cls.ix_carrying],
row[cls.ix_body_whl],
)
class SpecMachine(CarBase):
\"""Класс спецтехника\"""
car_type = "spec_machine"
def __init__(self, brand, photo_file_name, carrying, extra):
super().__init__(brand, photo_file_name, carrying)
self.extra = extra
@classmethod
def from_tuple(cls, row):
return cls(
row[cls.ix_brand],
row[cls.ix_photo_file_name],
row[cls.ix_carrying],
row[cls.ix_extra],
)
def get_car_list(csv_filename):
with open(csv_filename) as csv_fd:
# создаем объект csv.reader для чтения csv-файла
reader = csv.reader(csv_fd, delimiter=';')
# пропускаем заголовок csv
next(reader)
# это наш список, который будем возвращать
car_list = []
# объявим словарь, ключи которого - тип автомобиля (car_type),
# а значения - класс, объект которого будем создавать
create_strategy = {car_class.car_type: car_class
for car_class in (Car, Truck, SpecMachine)}
# обрабатываем csv-файл построчно
for row in reader:
try:
# определяем тип автомобиля
car_type = row[CarBase.ix_car_type]
except IndexError:
# если не хватает колонок в csv - игнорируем строку
continue
try:
# получаем класс, объект которого нужно создать
# и добавить в итоговый список car_list
car_class = create_strategy[car_type]
except KeyError:
# если car_type не извесен, просто игнорируем csv-строку
continue
try:
# создаем и добавляем объект в car_list
car_list.append(car_class.from_tuple(row))
except (ValueError, IndexError):
# если данные некорректны, то игнорируем их
pass
return car_list
if __name__ == "__main__":
print(get_car_list(sys.argv[1]))
"""
|
#Inclass exercise 3
import numpy as np
from matplotlib import pyplot as plt
def plot():
x = np.linspace(0, 2*np.pi, 100)
y, z = np.sin(x), np.cos(x)
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax1.plot(y, "r")
ax1.plot(z, "b")
plt.xlabel("% of Period")
plt.ylabel("Y-Value")
plt.title("Plotting sin and cos with lines")
ax2 = fig.add_subplot(212)
ax2.plot(y, "ro")
ax2.plot(z, "b^")
plt.xlabel("% of Period")
plt.ylabel("Y-Value")
plt.title("Plotting sin and cos with shapes")
plt.show()
if __name__ == "__main__":
plot()
|
import requests
from bs4 import BeautifulSoup
from tkinter import *
from tkinter import ttk
r = requests.get("https://www.worldometers.info/coronavirus/")
c = r.text
soup = BeautifulSoup(c, "html.parser")
data = soup.find("table", {"id":"main_table_countries_today"})
rows = data.find_all("a", {"class":"mt_a"})
countries = [str(r.text.strip()) for r in rows]
def country_stats(country1):
for r in rows:
link = r.get("href")
try:
country = r.text.strip()
if country1.upper()==country.upper():
rNew = requests.get(f"https://www.worldometers.info/coronavirus/{link}")
cNew = rNew.text
soup1 = BeautifulSoup(cNew, "html.parser")
print(soup1)
rows1 = soup1.find_all("div",{"style":"margin-top:15px;"})
for i in rows1:
return f"{country} \nstats: \n{i.text}"
continue
except IndexError:
return "No data for the given country"
continue
def check(event):
country = str(entry.get())
if country.capitalize() in countries or country == "USA":
label["text"] = country_stats(country)
else:
label["text"] = "That's not a country! "
window = Tk()
window.title("Coronavirus stats")
entry = Entry(window, width = 30, font = 8)
button = Button(window, text = "Search for Country's Recovered stats ")
label0 = Label(window, width = 30, font = 8)
label0["text"] = "Please Enter the country"
label = Label(window, width = 30, font = 8)
entry.grid(row = 1, column = 0)
label0.grid(row = 0, column = 0)
button.grid(row = 2, column = 0)
label.grid(row = 3, column = 0, columnspan = 2, pady = (20))
button.bind("<Button-1>", check)
window.mainloop()
|
import wolframalpha as wa
import datetime as dt
import getpass as gp
import wikipedia as wp
user = gp.getuser()
def getMessage():
time = dt.datetime.now().hour
message = "Good Morning, " if (time < 12) else ("Good Afternoon, " if (time < 18) else "Good Evening, ")
message += user.capitalize()
return message
def wolframQuestion(input):
answer = "\n"
app_id = "HJ2Q67-7A35YVXQ98"
client = wa.Client(app_id)
result = client.query(input)
answer += next(result.results).text
answer += "\nsource: WolframAlpha\n"
return answer
def wikipediaQuestion(input):
answer = "\n"
answer += wp.summary(input, sentences=2)
answer += "\nsource: Wikipedia\n"
return answer
print getMessage()
want = "yes"
while want == "yes" or want == "y":
input = raw_input("Question: ")
try:
print wolframQuestion(input)
except:
print wikipediaQuestion(input)
want = raw_input("Wanna ask a question? (yes/no): ")
|
import os # For using os.linesep instead of using a line separator: '\n'
class Book(object):
# Initialize the book title, author(s) name and price
def __init__(self, title, author):
# Assign the value to class variables
self.title = title
self.author = author
class MyBook(Book):
# Title: The book's title
# Author: author The book's author
# Price: The book's price
def __init__(self, title, author, price):
super().__init__(title, author)
self.price = price
def display(self):
# Print the class variable values
print("Title:", self.title, os.linesep+"Author:", self.author, os.linesep+"Price:", self.price)
title = input()
author = input()
price = int(input())
new_novel = MyBook(title, author, price)
new_novel.display()
|
######################################################################
# PWM_LED.py
#
# This program produce a pwm and control light exposure of an LED
# with changing it's duty cycle
######################################################################
import RPi.GPIO as GPIO
ledPin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(ledPin, GPIO.OUT)
pwmLed = GPIO.PWM(ledPin, 100)
pwmLed.start(100)
while(True):
dutyStr = input("Please Enter Brightness(0 to 100): ")
duty = int(dutyStr)
pwmLed.ChangeDutyCycle(duty)
|
class Queue:
def __init__(self):
self.list = []
def enqueue(self, item):
"""
Inserts an element in a queue.
"""
self.list.append(item)
def dequeue(self):
"""
Removes an element from a queue.
"""
return self.list.pop(0)
def isEmpty(self):
"""
Checks if the queue is empty.
"""
if len(self.list) == 0:
return True
else:
return False
def size(self):
"""
Size of the queue
"""
return len(self.list)
def display(self):
"""
Display the list.
"""
return self.list
queue = Queue()
queue.isEmpty()
queue.enqueue(4)
queue.enqueue('dog')
queue.enqueue(True)
queue.size()
queue.isEmpty()
queue.enqueue(8.4)
queue.dequeue()
queue.dequeue()
queue.size()
print(queue.display())
|
'''
Task
The provided code stub reads two integers from STDIN, a and b. Add code to print three lines where:
The first line contains the sum of the two numbers.
The second line contains the difference of the two numbers (first - second).
The third line contains the product of the two numbers.
'''
if __name__=="__main__":
a=int(input().strip())
b=int(input().strip())
print(a+b)
print(a-b)
print(a*b)
|
'''
Kevin and Stuart want to play the 'The Minion Game'.
Game Rules
Both players are given the same string, S.
Both players have to make substrings using the letters of the string S.
Stuart has to make words starting with consonants.
Kevin has to make words starting with vowels.
The game ends when both players have made all possible substrings.
Scoring
A player gets +1 point for each occurrence of the substring in the string S.
For Example:
String S= BANANA
Kevin's vowel beginning word = ANA
Here, ANA occurs twice in BANANA. Hence, Kevin will get 2 Points.
For better understanding, see the image below:
'''
def minion_game(s):
word_list=[]
stuart_list=[]
kevin_list=[]
vovels='aeiou'
for i in range(len(s)):
for j in range(len(s),i,-1):
word_list.append(s[i:j])
#print(word_list)
for word in word_list:
if word[0].lower() in vovels:
kevin_list.append(word)
else:
stuart_list.append(word)
stuart_score=len(stuart_list)
kevin_score=len(kevin_list)
if stuart_score>kevin_score:
print('Stuart {}'.format(stuart_score))
elif kevin_score>stuart_score:
print('Kevin {}'.format(kevin_score))
else:
print('DRAW')
#print(kevin_list)
#print(stuart_list)
if __name__=='__main__':
s=input()
minion_game(s)
|
import collections
n = int(input())
fields = input().split()
Students = collections.namedtuple('Students', fields)
total = 0
for _ in range(n):
student=Students(*input().split())
total +=int(student.MARKS)
print(total/n)
|
import calendar
mm,dd,yyyy=map(int,input().split())
#print(list(calendar.day_name)) ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
#print(calendar.weekday(yyyy,mm,dd)) Returns the index position for the day from the calender.day_name
print(calendar.day_name[calendar.weekday(yyyy,mm,dd)].upper())
|
import random
def random_pair_int(begin, end):
assert end > begin
first, second=random.randint(begin, end), random.randint(begin, end-1)
if second >= first: second += 1
return first, second
|
import sys, pygame, random
from pygame.math import Vector2
right = Vector2(1, 0)
left = Vector2(-1, 0)
up = Vector2(0, -1)
down = Vector2(0, 1)
cellSize = 36
cellNumber = 20
buffer = 5
class Snake():
def __init__(self):
self.body = [Vector2(5, 10), Vector2(4, 10), Vector2(3, 10)]
self.direction = right
def drawSnake(self):
for block in self.body: # Create for loop to draw the snake utilizing two dimensional vectors for readability
block_rect = pygame.Rect(int(block.x * cellSize), int(block.y * cellSize), cellSize, cellSize)
pygame.draw.rect(screen, (100, 0, 0), block_rect)
def moveSnake(self):
bodyCopy = self.body[:-1]
bodyCopy.insert(0, bodyCopy[0] + self.direction)
self.body = bodyCopy[:]
def addBlock(self):
bodyCopy = self.body[:]
bodyCopy.insert(0, bodyCopy[0] + self.direction)
self.body = bodyCopy[:]
class Apple():
def __init__(self):
self.x = random.randrange(0, cellNumber)
self.y = random.randrange(0, cellNumber)
self.position = Vector2(self.x, self.y) # Use two dimensional vector to establish position on the grid. This will make the code more readable and make this program easier to work with
def drawFood(self):
food = pygame.Rect(int(self.position.x * cellSize), int(self.position.y * cellSize), cellSize, cellSize)
screen.blit(appleImg, food)
def randomize(self):
self.x = random.randrange(0, cellNumber)
self.y = random.randrange(0, cellNumber)
self.position = Vector2(self.x, self.y) # Use two dimensional vector to establish position on the grid. This will make the code more readable and make this program easier to work with
class Score():
def __init__(self):
self.x = 8
self.y = 20
self.position = Vector2(self.x, self.y)
self.points = 0
def drawScore(self):
font = pygame.font.Font("freesansbold.ttf", 45)
text = font.render("Score: " + str(self.points), True, (255, 255, 255))
textRect = text.get_rect()
textRect = Vector2(self.position.x * cellSize, self.position.y * cellSize)
screen.blit(text, textRect)
def addPoint(self):
self.points += 1
class Game():
def __init__(self):
self.snake = Snake()
self.food = Apple()
self.score = Score()
def update(self):
self.snake.moveSnake()
self.checkCollision()
self.checkFail()
def drawElements(self):
self.food.drawFood()
self.snake.drawSnake()
self.score.drawScore()
def checkCollision(self):
if self.food.position == self.snake.body[0]:
self.food.randomize()
self.snake.addBlock()
self.score.addPoint()
def checkFail(self):
if not 0 <= self.snake.body[0].x < cellNumber or not 0 <= self.snake.body[0].y < cellNumber:
self.gameOver()
for block in self.snake.body[1:]:
if block == self.snake.body[0]:
self.gameOver()
def gameOver(self):
pygame.quit()
sys.exit()
pygame.init() # Initialize the pygame library
mainGame = Game()
SCREEN_UPDATE = pygame.USEREVENT
pygame.time.set_timer(SCREEN_UPDATE, 150) # Trigger event every 150 milliseconds
screen = pygame.display.set_mode((cellSize * cellNumber, cellSize * cellNumber + (buffer * cellSize))) # Establish the height and width of the screen
clock = pygame.time.Clock() # Create clock object to limit how fast while loop will run -- this enables the game to run more consistently on different computers
appleImg = pygame.transform.scale(pygame.image.load('images/apple.png'), (40, 40)).convert_alpha()
running = True # Set running = True to create infinite loop to keep program going
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT: # Enable program to quit
running = False
sys.exit()
if event.type == SCREEN_UPDATE:
mainGame.update()
if event.type == pygame.KEYDOWN: # Create if statements to determine which arrow key was last clicked; the last clicked arrow key will trigger which direction the snake moves
if event.key == pygame.K_LEFT:
if mainGame.snake.direction != right:
mainGame.snake.direction = left
if event.key == pygame.K_RIGHT:
if mainGame.snake.direction != left:
mainGame.snake.direction = right
if event.key == pygame.K_UP:
if mainGame.snake.direction != down:
mainGame.snake.direction = up
if event.key == pygame.K_DOWN:
if mainGame.snake.direction != up:
mainGame.snake.direction = down
screen.fill((14, 124, 123)) # Establish the fill color of the background
pygame.draw.rect(screen, (100, 100, 100), pygame.Rect(0, cellNumber * cellSize, cellNumber * cellSize, cellSize * buffer)) # Move this into draw elemeents??
mainGame.drawElements()
pygame.display.update() # Update display
clock.tick(60) # Ensures game will never run faster than 60 frames/second
|
# The tutorial to learn how to write on a video on it.
# the first lesson is to capture the video and show it in gray scale
import numpy as np
import cv2 as cv
import datetime
cap = cv.VideoCapture(0) # (task 1)
# cap = cv.VideoCapture('vtest.avi') # video capture from device (task 2)
# (task 4) adjusting and enquiring the camera parameters
# print(cap.get(cv.CAP_PROP_FRAME_WIDTH))
# print(cap.get(cv.CAP_PROP_FRAME_HEIGHT))
# cap.set(cv.CAP_PROP_FRAME_WIDTH, 700)
# cap.set(cv.CAP_PROP_FRAME_HEIGHT, 400)
# to see after the change
# width = str(cap.get(cv.CAP_PROP_FRAME_WIDTH))
# height = str(cap.get(cv.CAP_PROP_FRAME_HEIGHT))
# see if the script was able to connect with the camera
if cap is False:
print('cannot access the camera')
exit()
while True:
ret, frame = cap.read() # this command read the video and store it in var (frame) and returns vat (ret) as boolean if it can read it or not
if ret is False:
print('cannot receive the frames')
break
# text = 'width: '+width+'height:'+height
time_now = str(datetime.datetime.now())
font = cv.FONT_HERSHEY_SIMPLEX
# frame = cv.putText(frame,text,(20,40), font, 1,(255,0,0),1,cv.LINE_AA) # text, location, fontformat, fontsize, color, thickness, linetype
frame = cv.putText(frame, time_now, (20,40), font, 1, (0,255,255), 1, cv.LINE_AA) # text, location, fontformat, fontsize, color, thickness, linetype
# working on the variable frame to convert to gray color
# gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
# Display the resulting frame
cv.imshow('frame_gray', frame)
# the value inside the waitkey() dictate the frame rate per milisecond lower value mean high FBS, higher video quality
if cv.waitKey(1) == ord('q'):
break
# stop capturing
cap.release()
cv.destroyAllWindows()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.