text stringlengths 37 1.41M |
|---|
num1 = 1
for i in range(4):
for j in range(i + 1):
print(num1, end = " ")
num1 += 1
print()
|
"""
Program 2 : Write a Program that accepts an integer from user and print Sum of
all number up to entered number .
Input: 10
Output: The s um number up to 10 : 55
"""
num = input("Enter the number : ")
sum1 = 0
for itr in range(1,num+1):
sum1 = sum1 + itr
print("The Sum of number upto "+str(num)+" : "+str(sum1))
|
a = input("input : ")
if a >= 'A' and a <= 'Z':
print(a,"is in Upper Case")
else :
print(a,"is in Lower Case") |
c = raw_input("Enter Character : ")
try :
if(ord(c) >= 65 and ord(c) <= 90):
print("{} is in UpperCase".format(c))
elif(ord(c) >= 97 and ord(c) <= 122) :
print("{} is in LowerCase".format(c))
else :
print("{} is not alphabet".format(c))
except TypeError as te:
print("Character is not Entered")
pass |
r = float(input("Radius : "))
print("Area : ", 3.14 * r * r) if r >= 0 else print("Enter valid input.")
|
#!/usr/bin/env python3
a = int(input())
b = int(input())
# Stampa un messaggio se i numeri sono uguali
if a == b:
print("I due numeri sono uguali")
print(a + b)
|
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM) # Create TCP Socket
# Prepare a server socket
#Fill in start
# Identifier for a message/request: browser will assume port 80 and the webpage will be shown if your server is listening at port 80
serverPort = 6789
serverName = '10.0.0.32' # The destination, add IP address here
serverSocket.bind((serverName, serverPort)) # Assign serverPort to TCP socket
serverSocket.listen(1) # To listen for at most one connection at a time (TCP requests)
print('Ready to serve...')
#Fill in end
while True:
#Establish the connection
# Server waits on accept() for incoming requests
connectionSocket, addr = serverSocket.accept() #Fill in start #Fill in end
try:
# To recieve data from socket, the buffer size is 1024 bytes
# Read bytes from socket
message = connectionSocket.recv(1024) #Fill in start #Fill in end
# Extract path of request object from the message
filename = message.split()[1]
# Open requested object from the second character since first is '\' since it is looking into the path
f = open(filename[1:])
# Read the file and store the all the content from the requested file
outputdata = f.read() #Fill in start #Fill in end
#Send one HTTP header line into connection socket
# HTTP/1.1 *sucessful-request* \r\n\r\n
# b stands for bytes
# \r\n\r\n is a line separator
# Fill in start
connectionSocket.send(b'HTTP/1.1 200 OK\r\n\r\n')
# Fill in end
# Send the content of the requested file to the connection socket and encode it
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i].encode()) # Sends each character of outputdata
connectionSocket.send("\r\n".encode()) # Sends encoded string to socket object
# Output message when the file is found
print('Success!')
connectionSocket.close()
except IOError:
#Send response message for file not found
#Fill in start
print ('404 Not Found')
connectionSocket.send(b'HTTP/1.1 404\r\n\r\n')
#Fill in end
#Close client socket
#Fill in start
connectionSocket.close()
#Fill in end
serverSocket.close()
sys.exit()# Terminate the program after sending the corresponding data
|
import math
print("Введите коэффициенты для квадратного уравнения (ax^2 - (3-c)x - c = 0):")
a = float(input("a = "))
c = float(input("c = "))
b=-(3-c)
D = b ** 2 - 4 * a * c
print("D = %.2f" % D)
if D > 0:
x1 = (-b + math.sqrt(D)) / (2 * a)
x2 = (-b - math.sqrt(D)) / (2 * a)
if x1>x2:
print(x1)
else:
print(x2)
elif D == 0:
x = -b / (2 * a)
print(x)
else:
print("Корней нет") |
print('Введите значение аргумента')
import math
try:
try:
x=float (input('x = ',))
z1=(math.sin(2*x)+math.sin(5*x)-math.sin(3*x)) / (math.cos(x)-math.cos(3*x)+math.cos(5*x))
z2= math.tan(3*x)
print('z2 = ',z2)
print('z1 = ',z1)
except ZeroDivisionError:
print('Происходит деление на 0')
except ValueError:
print("Использованы буквы")
|
import requests
# Headers info for HTTP requests
headers = {"User-Agent":
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36" +
"(KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36"}
# Function to retrieve JSON from a GET request.
def getJSON(url):
# Variable stores a URL's data
# URL should be a JSON endpoint, preferably
r = requests.get(url, headers=headers)
# Convert it into a JSON format
data = r.json()
return data
# Function to find post links from data.
def getLinks(data):
# List to populate later on.
links = []
# Variable to easily access where reddit posts are stored
posts = data["data"]["children"]
# Iterate through posts to find their title and their link.
for post in posts:
# Save relavant data into variable
entry = {"title": post["data"]["id"], "url": post["data"]["url"]}
# Populate our own list with skimmed information.
links.append(entry)
return links
# Function that will go through our list on links and download them.
def downloadLinks(links):
# Iterate through the list of links
for x in links:
# Make sure the link ends with a JPG
# Don't want to download a not-picture
if x["url"].lower().endswith(tuple(['.jpg'])):
# Save it with the title.jpg in a downloads path
folder = 'downloads/' + x["title"] + '.jpg'
# GET request of the photo link
dlGet = requests.get(x["url"], headers=headers)
# Open a path to create/write file.
# It's being written in binary.
with open(folder, 'wb') as f:
try:
f.write(dlGet.content)
# Close it when you're done.
f.close()
# Feedback in Terminal about progress.
print('Successfully Downloaded %s!' % x["title"])
except:
print('Download for %s failed. Moving on..' % x["title"])
pass
else:
pass
return
# Terminal INterface
def interfaceDownloads():
# Save subreddit from user input
subreddit = input('From which subreddit frontpage' +
'would you like to download pictures from? ')
# Construct subreddit path from user input
path = 'https://www.reddit.com/r/' + subreddit + '/.json'
try:
# Check to see if a Subreddit exists first.
if requests.get(path, headers=headers).status_code == 200:
# If it's a go, go through functions defined.
print('Subreddit exists! Retrieving Front Page...')
data = getJSON(path)
print('Getting Links...')
links = getLinks(data)
print('Downloading Pictures...')
downloadLinks(links)
print('Downloads complete!')
# If no-go:
else:
# Retrieve the status code the input returned
error_code = requests.get(path).status_code
# Print input and the error code it returned
print(subreddit + ' failed with the error code: ' +
str(error_code))
# Restart prompt
return interfaceDownloads()
# Any other error for any other reason
# Should print in the terminal
# And restart the prompt.
except Exception as error:
print('Something went wrong...')
print(error)
return interfaceDownloads()
interfaceDownloads()
|
class TrieNode:
def __init__(self, alphabet, char):
self.alphabet = alphabet # The alphabet is a dictionary that can will have keys that tell us if a particular
# character has been used at that junction
self.char = char # The node will contain the character for concatenation while searching
# String based trie
class Trie:
def __init__(self, string_set):
self.stringSet = string_set # The large set S of strings
self.alphabet = self.get_alphabet() # To generate the alphabet of the trie
self.root = TrieNode(self.alphabet, None) # Initializing the root node with the alphabet and a null value
self.construct_trie()
# Will use each char in the string as keys, since keys are unique we automatically avoid duplicates
def get_alphabet(self):
_alphabet = {}
for char in self.stringSet:
_alphabet[char] = None
return _alphabet
pass
# Will use a dictionary in each node whose keys are the alphabet and whose values are either none or the next
# node in the path
def construct_trie(self):
_split = self.stringSet.split()
_root = self.root
for string in _split:
_root = self.root # Every subsequent string begins at the root
for char in string:
_root.alphabet[char] = TrieNode(self.alphabet, char)
_root = _root.alphabet[char]
pass
# Trace a path through each nodes dictionary
def search(self, search_string):
_root = self.root
for char in search_string:
if _root.alphabet[char] is None:
return False
_root = _root.alphabet[char]
return True
pass
|
import turtle as tt
tt.shape("turtle")
tt.penup()
tt.goto(0, -120)
tt.pendown()
i = 0
while(i < 360):
tt.forward(3)
tt.left(1)
i+=1
|
'''
Курс "Информатика на Python 3" на ФБМФ.
Работа №16, задача 3, частотный анализ текста.
'''
class FrequentAnalysis:
alphabet = "абвгдеёжзийклмнопрстуфхцчшщъыьэюя"
def __init__(self, text, correct_order):
# Считаем вхождения русских букв в текст независимо от регистра
counter = [text.lower().count(letter) for letter in self.alphabet]
total_length = sum(counter)
# Делаем из количества букв частоту встречаемости с округлением до 5 знаков
values = [round(number/total_length, 5) for number in counter]
# Создаем список букв, встречающихся в тексте, в порядке убывания встречаемости
frequencies = list(zip(values, list(self.alphabet)))
self.frequencies = sorted(frequencies, reverse=True)
sorted_alphabet = [item[1] for item in self.frequencies]
self.sorted_alphabet = sorted_alphabet + [letter.upper() for letter in sorted_alphabet]
# Создаем словарь для замены, учитывая верхний регистр
self.correct_order = correct_order + [letter.upper() for letter in correct_order]
self.substitution_dictionary = dict(zip(self.sorted_alphabet, self.correct_order))
def decode(self, text):
output = []
for letter in text:
if letter in self.substitution_dictionary.keys():
output.append(self.substitution_dictionary[letter])
else:
output.append(letter)
return ''.join(output)
if __name__ == '__main__':
with open('ex_3.txt', 'r') as input_file:
lines = input_file.readlines()
data = ''.join(lines)
'''with open('table.txt', 'r') as table:
frequency_default = []
table = table.readlines()
for line in table:
line = tuple(line.split())
frequency_default.append(line[1])'''
# К сожалению, порядок полусинтетический: таблица из Википедии хороша, но разница в
# сотые доли процента сказывается на порядке букв и сильно снижает понятность текста.
# Также подпортили картину специальные слова, такие как "шиФр" и "алФавит", например
frequency_default = ['а', 'о', 'и', 'е', 'т', 'в', 'н', 'р', 'л', 'с',
'м', 'к', 'п', 'ы', 'з', 'ф', 'д', 'я', 'ш', 'б',
'ь', 'у', 'г', 'ч', 'ж', 'й', 'х', 'ц', 'ю', 'э',
'ё', 'щ', 'ъ']
cipher = FrequentAnalysis(data, frequency_default)
print(cipher.decode(data))
with open('ex_3_output.txt', 'w') as output_file:
output_file.write(cipher.decode(data))
|
'''
George Whitfield
gwhitfie@andrew.cmu.edu
June 9 2020
client.py - client for testing the communication with the server in server.py
How to use this file:
python3 client.py <message to send to server>
'''
import socket
import sys
# starter code copied from python documentation about socketserver and sockets
HOST = "localhost"
PORT = 9999
def main():
data = " ".join(sys.argv[1:]) # data = string of the cmd line args
print(f"Opening socket on host {HOST} and port {PORT}.")
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((HOST, PORT))
# send the data to the server
sock.sendall(bytes(data + "\n", "utf-8"))
#receive response from the server
resp = str(sock.recv(1024), "utf-8")
print(f"Sent: {data}")
print(f"Recieved: {resp}")
main() |
""" A coordinate location on the graph """
import numpy as np
import math
from matplotlib.patches import Rectangle
class Point:
def __init__(self, coord):
""" Initialize a point on the Graph
coord: int or ndarray
if only x is specified, then a 1x2 array with coordinates
"""
if np.array(coord).shape != (2,):
raise Exception("Invalid Coordinate passed, Coordinate should be a 1x2 array")
self.coord = np.array(coord)
# The id of the point on its grid
self._grid_id = None
def __str__(self):
return f"<{self.x}, {self.y}>"
def __repr__(self):
return f"<{int(self.x)},{int(self.y)}>"
def __call__(self):
return self.coord
def __add__(self, point):
# Normalize for situations where the second point is None
# This is because the Grid.centric_point may return a None value
# and we want to be able to add all grid.centric_point values when calculating
# the CentralGrid's Centric Point
# TODO except there is a better way to do this (:
if not point or point is None:
point = np.zeros((1, 2))
return Point(self.coord + point.coord)
def __sub__(self, point):
if not point or point is None:
point = np.zeros((1, 2))
return Point(self.coord - point.coord)
def __mul__(self, val):
if isinstance(val, Point):
return Point(self.coord * val.coord)
return Point(self.coord * val)
def __truediv__(self, scalar):
return Point(self.coord/scalar)
def __getitem__(self, index):
return self.coord[index]
def __pow__(self, num):
return Point(self.coord**num)
def __abs__(self):
return np.abs(self.coord)
def __ge__(self, point):
return self.coord >= point.coord
def __eq__(self, point):
return np.all(self.coord == point.coord)
def hyp(self):
return (np.abs(self.coord)).sum()
def set_grid_id(self, id):
if self._grid_id is not None:
raise Exception("Point already has a grid")
self._grid_id = id
def update_grid_id(self, id):
""" update id of point in the grid
This is necessary when a point is deleted from the grid
"""
self._grid_id = id
def distance_cost(self, dest_point):
return Point.distance_from(self, dest_point)
@property
def grid_id(self):
return self._grid_id
@staticmethod
def distance_from(point_A, point_B):
""" The distance from a point to another"""
return np.power(np.square(point_A.coord - point_B.coord).sum(), 0.5)
# return ((self.x - next_point.x)**2 + (self.y - next_point.y)**2)**0.5
@property
def x(self):
return self.coord[0]
@property
def y(self):
return self.coord[1]
def calculate_costs(points, centric_point):
""" Returns the accumulated costs of all point in `points` from the centric_point """
if len(points) == 1:
return points[0].hyp()
_part = (points - centric_point)**2
_fin = []
for point in _part:
_fin.append(point.hyp())
return (np.array(_fin)).sum()
class Grid:
def __init__(self, coords):
""" Initialize a grid
Parameters
-----------
points: array
Points contained in the Grid
coords: array
The full coordinates of the grid in the format (bottom_left, top_left, top_right, bottom_right)
Each element of the coords is a type of Point
"""
self._points = []
self._coords = coords
self._cost = None
self._centric_point = None
# self._costs = self.calculate_costs(self._points, self._centric_point)
def __str__(self):
return f'<Grid @ {self.coords} with {len(self._points)} points>'
def __repr__(self):
return f'<Grid @ {self.coords}>'
def __getitem__(self, index):
""" Return point contained in Grid with index """
return self._points[index]
def __len__(self):
""" Return number of points in the grid """
return len(self._points)
@property
def cost(self):
""" Cumulated costs of points from the centric point """
return self._cost
def compute_cost(self):
""" Recompute the total costs """
self._cost = calculate_costs(self.points, self.centric_point)
@property
def points(self):
return np.array(self._points)
def calculate_centric_point(self):
""" Calculate the centric_point of the grids """
return np.sum(self.points)/len(self.points)
def point_cost(self, point):
""" Return the cost of a point `point` moving in the Grid """
if self.has_points:
return point.distance_cost(self.centric_point)/self.cost
return 1
@property
def centric_point(self):
""" Calculate center of points density of grid """
# if grid has no points return the center of the grid
if not self.has_points:
return Point((self.x_coords.sum()/2, self.y_coords.sum()/2))
# if centric point has not being calculated, recalculate🤕
if not self._centric_point:
self._centric_point = self.calculate_centric_point()
return self._centric_point
def add_point(self, point):
""" Add a point to the Grid """
self._points = np.append(self.points, point)
point.set_grid_id(len(self.points)-1)
def remove_point(self, point):
""" Remove point from list of points in Grid """
# TODO Look for an efficient way todo all this
# Update the ids of other points in the grid
# Very inefficient way of doing this I think😕
# Using this for Now
for i, _point in enumerate(self._points):
if point == _point:
self._points = np.delete(self._points, i)
# TODO This might be a better way to do this
# self._points = np.delete(self._points, point.grid_id)
# if self.has_points:
# for i in range(point.grid_id, len(self._points)):
# self._points[i].update_grid_id(i-1)
@property
def x_coords(self):
""" Returns the X-coordinates of the grid """
return np.array([self._coords[0][0], self.coords[2][0]])
@property
def y_coords(self):
""" Returns the Y-coordinates of the grid """
return np.array([self._coords[0][1], self.coords[1][1]])
@property
def coords(self):
return self._coords
def contains(self, point):
""" Returns whether a point is contained in a grid or not"""
return (self.x_coords[0] <= point[0] <= self.x_coords[1]) and \
(self.y_coords[0] <= point[1] <= self.y_coords[1])
def all_visited(self):
""" Returns whether all the points of the grid have being visited """
return len(self._points) <= 0
@property
def has_points(self):
""" Return whether the grid contains any points or not """
return len(self._points) > 0
@property
def weight(self):
""" Return the weight of the Grid
This is distance from one horizontal/vertical edge to another
"""
return self.x_coords[1] - self.x_coords[0]
def plot(self, ax, with_points=False, color='black'):
""" Plots the Grid on axes ax """
grid = Rectangle(
(self.x_coords[0], self.y_coords[0]),
self.weight, self.weight, facecolor="white", edgecolor=color, fill=False)
ax.gca().add_patch(grid)
if self.has_points:
ax.scatter(self.centric_point[0], self.centric_point[1], color='red')
if with_points:
points = self._points.copy()
for i, point in enumerate(points):
points[i] = point()
points = np.vstack(points)
ax.scatter(points[:, 0], points[:, 1])
class OmniscientReference:
""" The CentricPoint of the map
This dictates the cost of inter-grid travels. It is more like the
center of Gravity of all other Grid points
"""
def __init__(self, pos, grids):
""" Initializes the Centric Grid """
self._grids = grids
self._points = np.array([grid.centric_point for grid in grids ])
self._coords = pos
# Use only the Non-zero Grid points in calculating costs
non_zero_grid_points = self._points.take(self._points.nonzero())
self.points_cost = None
self._cost = calculate_costs(non_zero_grid_points[0], self.coords)
@classmethod
def derive_from_grids(cls, grids):
""" create reference point from a list of grids """
# Get list of all grid centric points
_grid_centric_points = [ grid.centric_point for grid in grids ]
sum_ = np.sum(_grid_centric_points)/len(_grid_centric_points)
return cls(sum_, grids)
def plot(self, ax):
ax.scatter(self.coords[0], self.coords[1], color='blue')
@property
def coords(self):
return self._coords
@property
def grids(self):
return self._grids
@property
def points(self):
return self._points
def grid_cost(self, grid):
""" Return the cost of a grid `grid` moving in the Graph """
return grid.centric_point.distance_cost(self.coords)/self._cost
|
'''
==============
3D scatterplot
==============
Demonstration of a basic scatterplot in 3D.
'''
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Data for three-dimensional scattered points
# zdata = 15 * np.random.random(100)
# xdata = np.sin(zdata) + 0.1 * np.random.randn(100)
# ydata = np.cos(zdata) + 0.1 * np.random.randn(100)
xdata=[]
ydata=[]
zdata=[]
import json
# read file
with open('depo/0/0-test.json', 'r') as myfile:
data=myfile.read()
# parse file
obj = json.loads(data)
for depo in obj['depos']:
if depo == {}: break # EOS
x = depo['x']
y = depo['y']
z = depo['z']
if x>-3100 and x<-1800 and y>2800 and y<6000 and z>3000 and z<4500:
xdata.append(depo['z'])
ydata.append(depo['x'])
zdata.append(depo['y'])
xdata = np.array(xdata)
ydata = np.array(ydata)
zdata = np.array(zdata)
ax.scatter(xdata, ydata, zdata, s=0.01) #, c=zdata, cmap='Greens');
ax.set_xlabel('Beam Direction')
ax.set_ylabel('Drift Direction')
ax.set_zlabel('Height')
plt.show()
|
#Output an image to the console
import Question1 # catch the training set
import numpy as np
def Question1Image(no):
myimage = Question1.train_images[no]
myimage = np.array(myimage)
return myimage
# print image to console
def printImage(myimage):
for row in myimage:
for col in row:
print('.' if col<=127 else '$',end='') #less than 128
print()
number = 3 #type a number in number
printImage(Question1Image(number))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 20 11:35:24 2019
@author: mica
"""
""" PROJECT OVERVIEW
KENTUCKY DERBY WEIGHTED HORSE PICKER
This is a simple console program designed to allow the user to
generate various Kentucky derby bets, with random choice, based
on how they would rate each horse.
The layout of the project should include the following features.
1. User should be presented with two choices, the input should
be an int either 1 or 2.
*QUIT SHOULD BE A GLOBALLY RECOGNIZED COMMAND DURING ANY INPUT LINE WITH 'q'.
1. New
2. Load
2a. 'New' Branch
Steps: 1. Ask for total number of horses
2. Populate Data (Dictionary) Key = Unique Number
Minimum of two Values ([Name, Rating])
3. Direct user to 'picking' interface
2b. 'Load' Branch
Steps: 1. Load saved dictionary from local storage
2. Direct user to 'picking' interface
3. 'Picking' interface, should have the user select from the menu
with a choice from the following menu the input should be an int:
(1. Save), (2. pick 2), (3. pick 3),
(4. pick 4.), (5. Change horse rating), (6. Scratch Horse),
(7. Print Lineup), (8. OPTIONAL ADD ON), (9. OPTIONAL ADD ON)
3.1 Save Method should save the user's input from the dictionary into local storage
3.2, 3.3, 3.4 Pick Methods should ask for a quantity of picks and return a list
of however many picks the user wants
3.5 Ask which horse they would like to reweigh and change the value
3.6 Remove a horse from being in the dictionary
3.7 Return the lineup.
Note: After each input call the user should be returned to the 'picking' menu
""" |
'''
isinstance(x,y) x是否為y的子類
type(x) 誰實例化x
'''
class A:
pass
class B(A):
pass
class C:
pass
a = A()
b = B()
# isinstance(b,B) or isinstance(b,A) or isinstance(b,C)
print(isinstance(b, (B, A, C)))
|
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f'name={self.name} age={self.age}'
s1 = Student(name="test", age=20)
l1 = [1, 2, 3]
d1 = {1: 1, 2: 2}
# Student.__bases__
'''
<type 'type'>
type of all types
<type 'upject'>
base of all other types
'''
|
import important
'''
切片方式
[start:end:step]
結果不包含end 只到end前面一位
[:] 包含全部內容 拷貝的意思
[:3] = [0:3]
[0:5:3] 取index = 0 and index = 3的值
反向取值
a = [1, 2, 3, 4, 5, 6]
d = a[5:0:-1] # [6, 5, 4, 3, 2]
c = a[::-1] # [6, 5, 4, 3, 2, 1]
'''
# 獲取列表機本信息
list1 = [1, 2, 3, 5, 8, 5, 3, 2, 46, -10]
# print(f'list1的長度為{len(list1)}')
# print(f'list1的最大值為{max(list1)}')
# print(f'list1的最小值為{min(list1)}')
# print(f'list1的出現3的次數為{list1.count(3)}')
list2 = ['a', 'c', 'd']
# 加入一個元素
list2.append('e')
# 特定位置插入
list2.insert(1, 'b')
# 刪除元素
list2.remove('c')
# 列表翻轉
list2.reverse()
# 列表排序
list1.sort() # 預設為小到大
list1.sort(reverse=True) # reverse後 大到小
# 若有比較的方法 列表內的元素要統一
listtest = [1, 2, 'abc', [58, 67], 1]
'''
列表函數
len(list) 求長度
max(list) 求最大值
min(list) 求最小值
list(seq) 將元組轉換為列表
列表方法
list.append(obj) 添加在最後
list.count(obj) obj在列表出現幾次
list.extend(seq) 新增一個序列裡面的內容在最後
list.index(obj) obj的位置
list.insert(index,obj)在index插入obj
list.pop([index = -1])默認最後一個值 返回被刪除的值
list.remove(obj)移除列表中的obj
list.reverse()反轉列表不回傳
list.sort(key=None,reverse=False)排序 默認小到大
list.clear()清空列表
list.copy()複製列表
'''
# 冒泡排序
def buboo(arr):
totalLen = len(arr)
for i in range(totalLen):
for j in range(totalLen - i - 1): # -1是因為最後一位是長度-1 -i是因為有跑過的且最大的已經在最後一位了 不需要再跑了
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
arr = [5, -1, 2, 3, 4, 6, 9, 2, 0]
buboo(arr)
print(arr)
'''
tuple and list
元組不可改變,創建時只需一個內存
列表可改變,創建時須兩塊,一塊是固定的一塊是提供擴展的,較靈活
'''
|
# 前綴為class
# attribut and methiod
# methiod's first pramater si self(js's this)
# self __init__ 內設置屬性 _代表受保護的 可以更改也可以從外面獨拿到該屬性
# __代表私有的 實例拿不到 只能在該class中修改與獲取
# 通常都使用_protect_ __private_做前綴
# 透過dir 可以拿到該實例能拿到的所有屬性 __為開頭的屬性 需要加_類的名稱 即可訪問修改
class People:
def __init__(self, name, age):
self.name = name
self.age = age
self._protect_var = 10 # 被保護的
self._var = 10 # 被保護的
self.__private_var = 10 # 只能在class中使用
self.__ll = 10 # 只能在class中使用
@property # 訪問私有屬性 可以做判斷
def ll(self):
return self.__ll
@ll.setter # 設置私有屬性 可以做判斷
def ll(self, val):
if val < 10:
print('too low')
else:
self.__ll = val
def sayHi(self):
print(f'Hi! my name is {self.name} and I am {self.age}')
def getll(self):
print(self.__ll)
def setll(self, val):
self.__ll = val
jack = People('Jack', 26)
# jack.age = 30 # 可直接修改
# print(dir(jack))
# jack._People__ll = 20
# jack.getll()
jack.ll = 20
print(jack.ll)
|
a = 2
b = 0b1010 # 2進制
c = 0o12 # 8進制
d = 0xa # 16進制
'''
整數除法 / 精確計算 type float // type int
float做運算 結果都是float
'''
# print(type(4 / 2)) # float
# print(type(3//2)) # int
name = 'python'
age = 27
new_str = 'I am %s today %d' % (name, age) # python2
new_str_1 = 'I am {} today {}'.format(name, age) # python3 不會有數據類型的問題
new_str_2 = 'I am {name} today {age}'.format(
name=name, age=age
)
new_str_3 = f'I am {name} today {age}' # python3.6
# print(new_str)
# print(new_str_1)
# print(new_str_2)
# print(new_str_3)
'''
string -> list
str.split() 填入要做為區分的字元 預設為空白
list -> string
" ".join(list) join前面放入要將內容串起來的文字
'''
str_list = 'google.com.apple'
# print(str_list.split('.')) #['google', 'com', 'apple']
list_str = ['google', 'com', 'apple']
# print('~'.join(list_str)) #google~com~apple
|
'''
The valid function takes a function (f) and a list (l) and
returns what items in l are valid for a given f.
'''
import math
def valid(f, l):
try:
for i in l:
f(i)
except:
del(l[l.index(i)])
valid(f,l)
return l
'''
examples:
valid(chr, [-1, 10, 123.456, 2**20]) == [10]
valid(asin, [0.3, -0.1, -1, 1, 'sneezing panda', '1', 1.3]) == [0.3, -0.1, -1, 1]
valid(sqrt, [-3, -0.1, 0, 8]) == [0, 8]
'''
|
# Flatten a list containing sublists
# https://stackoverflow.com/questions/17864466/flatten-a-list-of-strings-and-lists-of-strings-and-lists-in-python
def flatten_to_strings(listOfLists):
"""Flatten a list of (lists of (lists of strings)) for any level
of nesting"""
result = []
for i in listOfLists:
# Only append if i is a basestring (superclass of string)
if isinstance(i, basestring):
result.append(i)
# Otherwise call this function recursively
else:
result.extend(flatten_to_strings(i))
return result
|
import tkinter.messagebox as tm
import tkinter
from module import kalkulasi_persamaan
def show():
tm.showinfo(title="Hasil", message=kalkulasi_persamaan.kalkukasi_turunan(persamaan.get(), berapa_kali.get()))
root = tkinter.Tk()
tkinter.Label(root, text="Persamaan: ").grid(row=0)
tkinter.Label(root, text="Berapa Turunan: ").grid(row=1)
persamaan = tkinter.Entry(root)
berapa_kali = tkinter.Entry(root)
persamaan.grid(row=0, column=1)
berapa_kali.grid(row=1, column=1)
tkinter.Button(root, text="Tampilkan", command=show).grid(row=3, column=1)
tkinter.mainloop() |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/9/8 18:07
# @Author: yuzq
# @File : TestStocks
import csv
import pprint
from collections import namedtuple
def traverse1():
print('------------我是方法分界线起始---------------')
with open('stocks.csv') as f:
f_csv = csv.reader(f)
headers = next(f_csv)
for row in f_csv:
# Process row
pprint.pprint(row)
print(row[2])
print('------------我是方法分界线终止---------------')
def traverse2():
print('------------我是方法分界线起始---------------')
with open('stocks.csv') as f:
f_csv = csv.reader(f)
headings = next(f_csv)
Row = namedtuple('Row', headings)
for r in f_csv:
row = Row(*r)
# Process row
pprint.pprint(row)
print(row.Price)
print('------------我是方法分界线终止---------------')
def traverse3():
print('------------我是方法分界线起始---------------')
with open('stocks.csv') as f:
f_csv = csv.DictReader(f)
for row in f_csv:
# process row
pprint.pprint(row)
print(row['Symbol'])
print('------------我是方法分界线终止---------------')
def write1():
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),
('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),
('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),
]
with open('stocks2.csv', 'w') as f:
f_csv = csv.writer(f)
f_csv.writerow(headers)
f_csv.writerows(rows)
def write2():
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
rows = [{'Symbol': 'AA', 'Price': 39.48, 'Date': '6/11/2007',
'Time': '9:36am', 'Change': -0.18, 'Volume': 181800},
{'Symbol': 'AIG', 'Price': 71.38, 'Date': '6/11/2007',
'Time': '9:36am', 'Change': -0.15, 'Volume': 195500},
{'Symbol': 'AXP', 'Price': 62.58, 'Date': '6/11/2007',
'Time': '9:36am', 'Change': -0.46, 'Volume': 935000},
]
with open('stocks.csv', 'w') as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writeheader()
f_csv.writerows(rows)
if __name__ == '__main__':
# write1()
write2()
# traverse1()
# traverse2()
traverse3()
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2020/7/28 16:06
# @Author: yuzq
# @File : GuessNumber
import random
def guess_number():
print('I am Thinking of a number between 1 and 20')
target_number = random.randint(1, 20)
count = 0
while count < 6:
print('Take a guess')
number = int(input())
if number < target_number:
print('Your guess is too low')
elif number > target_number:
print("Your guess is too high")
else:
print("Good job! You guessed my number in " + str(count) + 'guesses!')
break
count = count + 1
if count == 6:
print('Nope. The number I was thinking of was' + str(target_number))
if __name__ == '__main__':
guess_number()
|
# 给定一个包含 n 个整数的数组 nums 和一个目标值 target,判断 nums 中是否存在四个元素 a,b,c 和 d ,使得 a + b + c + d 的值与 target 相等?找出所有满足条件且不重复的四元组。
# 注意:答案中不可以包含重复的四元组。
# 示例 1:
# 输入:nums = [1,0,-1,0,-2,2], target = 0
# 输出:[[-2,-1,1,2],[-2,0,0,2],[-1,0,0,1]]
# 示例 2:
# 输入:nums = [], target = 0
# 输出:[]
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/4sum
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
##################################################################################################
# 网络题解:
nums = [1,0,-1,0,-2,2]
target = 0
nums.sort() # [-2, -1, 0, 0, 1, 2]
# left = 0
# mid = 1
# right = len(nums) - 1
res_list = []
#
# # for i in range(len(nums)):
# # left = i + 1
# # mid = i + 2
# # right = len(nums) - 1
#
# for index, num in enumerate(nums):
# if left < index < right and index > mid:
# res = nums[left] + nums[mid] + nums[index] + nums[right]
# if res > target:
# right -= 1
# elif res == target:
# res_list.append([nums[left], nums[mid], nums[index], nums[right]])
# else:
# mid += 1
# if res < target:
# left += 1
#
# print(res_list)
# for i in range(len(nums) - 3):
# if i > 0 and nums[i] == nums[i-1]:
# continue
# if nums[i] + nums[i+1] + nums[i+2] + nums[i+3] > target:
# break
# if nums[i] + nums[len(nums)-1] + nums[len(nums)-2] + nums[len(nums)-3] < target:
# continue
# for j in range(i+1, len(nums)-2):
# if j - i > 1 and nums[j] == nums[j-1]:
# continue
# if nums[i] + nums[j] + nums[j+1] + nums[j+2] > target:
# break
# if nums[i] + nums[j] + nums[len(nums)-1] + nums[len(nums)-2] < target:
# continue
#
# left = j + 1
# right = len(nums) - 1
# while left < right:
# temp = nums[i] + nums[j] + nums[left] + nums[right]
# if temp == target:
# res_list.append([nums[i], nums[j], nums[left], nums[right]])
# while left < right and nums[left] == nums[left+1]:
# left += 1
# while left < right and nums[right] == nums[right-1]:
# right -= 1
# left += 1
# right -= 1
# elif temp > target:
# right -= 1
# else:
# left += 1
#
# print(res_list)
nums.sort()
ln = len(nums)
ret = []
if ln < 4:
print([])
for i in range(0, ln - 3):
num1 = nums[i]
for j in range(i + 1, ln - 2):
num2 = nums[j]
left = j + 1
right = ln - 1
while left < right:
total = num1 + num2 + nums[left] + nums[right]
if total == target:
tmp = [num1, num2, nums[left], nums[right]]
if tmp not in ret:
ret.append(tmp)
right -= 1
elif total < target:
left += 1
else:
right -= 1
print(ret)
|
# 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
#
# 说明:你不能倾斜容器。
#
# 示例 1:
#
# 输入:[1,8,6,2,5,4,8,3,7]
# 输出:49
# 解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
#
# 示例 2:
#
# 输入:height = [1,1]
# 输出:1
#
# 示例 3:
#
# 输入:height = [4,3,2,1,4]
# 输出:16
#
# 示例 4:
#
# 输入:height = [1,2,1]
# 输出:2
#
# 来源:力扣(LeetCode)
# 链接:https://leetcode-cn.com/problems/container-with-most-water
# 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
height = [1,8,6,2,5,4,8,3,7]
# area = 0
# area_list = []
#
# for index in range(len(height)):
# if index <= len(height) - 2:
# first_range = [num for num in range(index, len(height) - 1)]
# second_range = [num for num in range(index + 1, len(height) - 1)]
#
# for first_number in first_range:
# for second_number in second_range:
# min_height = min(height[first_number], height[second_number])
# length = second_number - first_number + 1
# area = min_height * length
# area_list.append(area)
#
# print(max(area_list))
left = 0
right = len(height) - 1
area = 0
while left < right:
min_height = min(height[left], height[right])
length = right - left
area = max(area, min_height * length)
if height[left] < height[right]:
left += 1
else:
right -= 1
print(area)
|
"""A Collection of useful miscellaneous functions.
misc.py:
Collection of useful miscellaneous functions.
:Author: Hannes Breytenbach (hannes@saao.ac.za)
"""
import collections.abc
import itertools
import operator
def first_true_index(iterable, pred=None, default=None):
"""find the first index position for the which the callable pred returns True."""
if pred is None:
func = operator.itemgetter(1)
else:
func = lambda x: pred(x[1])
# either index-item pair or default
ii = next(filter(func, enumerate(iterable)), default)
return ii[0] if ii else default
def first_false_index(iterable, pred=None, default=None):
"""find the first index position for the which the callable pred returns False."""
if pred is None:
func = operator.not_
else:
func = lambda x: not pred(x)
return first_true_index(iterable, func, default)
def sortmore(*args, **kw):
"""
Sorts any number of lists according to:
optionally given item sorting key function(s) and/or a global sorting key function.
Parameters
----------
One or more lists
Keywords
--------
globalkey : None
revert to sorting by key function
globalkey : callable
Sort by evaluated value for all items in the lists
(call signature of this function needs to be such that it accepts an
argument tuple of items from each list.
eg.: ``globalkey = lambda *l: sum(l)`` will order all the lists by the
sum of the items from each list
if key: None
sorting done by value of first input list
(in this case the objects in the first iterable need the comparison
methods __lt__ etc...)
if key: callable
sorting done by value of key(item) for items in first iterable
if key: tuple
sorting done by value of (key(item_0), ..., key(item_n)) for items in
the first n iterables (where n is the length of the key tuple)
i.e. the first callable is the primary sorting criterion, and the
rest act as tie-breakers.
Returns
-------
Sorted lists
Examples
--------
Capture sorting indices::
l = list('CharacterS')
In [1]: sortmore( l, range(len(l)) )
Out[1]: (['C', 'S', 'a', 'a', 'c', 'e', 'h', 'r', 'r', 't'],
[0, 9, 2, 4, 5, 7, 1, 3, 8, 6])
In [2]: sortmore( l, range(len(l)), key=str.lower )
Out[2]: (['a', 'a', 'C', 'c', 'e', 'h', 'r', 'r', 'S', 't'],
[2, 4, 0, 5, 7, 1, 3, 8, 9, 6])
"""
first = list(args[0])
if not len(first):
return args
globalkey = kw.get("globalkey")
key = kw.get("key")
if key is None:
if globalkey:
# if global sort function given and no local (secondary) key given, ==> no tiebreakers
key = lambda x: 0
else:
# if no global sort and no local sort keys given, sort by item values
key = lambda x: x
if globalkey is None:
globalkey = lambda *x: 0
if not isinstance(globalkey, collections.abc.Callable):
raise ValueError("globalkey needs to be callable")
if isinstance(key, collections.abc.Callable):
k = lambda x: (globalkey(*x), key(x[0]))
elif isinstance(key, tuple):
key = (k if k else lambda x: 0 for k in key)
k = lambda x: (globalkey(*x),) + tuple(f(z) for (f, z) in zip(key, x))
else:
raise KeyError(
"kw arg 'key' should be None, callable, or a sequence of callables, not {}".format(
type(key)
)
)
res = sorted(zip(*args), key=k)
if "order" in kw:
if kw["order"].startswith(("descend", "reverse")):
res = reversed(res)
return tuple(map(list, zip(*res)))
def groupmore(func=None, *its):
"""Extends the itertools.groupby functionality to arbitrary number of iterators."""
if not func:
func = lambda x: x
its = sortmore(*its, key=func)
nfunc = lambda x: func(x[0])
zipper = itertools.groupby(zip(*its), nfunc)
unzipper = ((key, zip(*groups)) for key, groups in zipper)
return unzipper
|
# using INSERT IGNORE prevents duplicates in the db
def generate_insert_statement(table_name, column_name, email):
return "INSERT IGNORE INTO " + table_name + "(" + column_name + ") VALUES(\'" + email + "\');"
def generate_mysql(fn, table_name, column_name):
input_file = open("email_list_output.txt", "r")
readable_input_file = input_file.readlines()
mysql_statement = ""
if len(readable_input_file) != 0:
for email in readable_input_file:
mysql_statement += generate_insert_statement(table_name.rstrip('\n'), column_name.rstrip('\n'), email.rstrip('\n')) + "\n"
else:
raise EOFError(fn + ' contained no emails!')
input_file.close()
return mysql_statement
|
# -*- coding: utf-8 -*-
import os, sys, paramiko
def get_csv_files(path: str) -> [] :
"""
get csv files from directory
:param path: file path
:return: csv files list
"""
files = []
for f in os.listdir(path):
if (f.endswith(".csv")):
files.append(f)
return files
def upload_files(local_path: str, remote_path: str):
"""
upload csv file from local to remote via sftp.
:param local_path: local path
:param remote_path: remote path
:return:
"""
sftp_server = "192.168.11.1"
sftp_port = 22
sftp_user = "abc"
sftp_password = "abc"
server = paramiko.Transport((sftp_server, sftp_port))
server.connect(username=sftp_user, password=sftp_password)
sftp = paramiko.SFTPClient.from_transport(server)
csv_files = get_csv_files(local_path)
for f in csv_files:
local_file = os.path.join(local_path, f)
remote_file = os.path.join(remote_path, f)
print("upload file:" + local_file)
sftp.put(local_file, remote_file)
sftp.close()
server.close()
"""
usage: python upload.py [local_path] [remote_path]
upload files from local path to remote path via sftp.
local_path: local path
remote_path: sftp server path
"""
if __name__ == '__main__':
if (len(sys.argv) > 2):
local_path = sys.argv[1]
remote_path = sys.argv[2]
upload_files(local_path, remote_path)
else:
print("usage: python upload.py [local_path] [remote_path]")
|
my_dick = {"a":1, "b":2, "c":3}
try:
value = my_dict["d"]
except IndexError:
print("This index does not exist!")
except KeyError:
print("This key is not in the dictionary!")
except
print("Some other error occurred!")
try:
x = int(input())
except ValueError:
print ("Vi vveli ne cheslo")
x = 0
print(x)
try:
x = int(input())
except ValveError:
print("Vi vveli ne cheslo")
x = 0
try:
y = int(input())
except ValveError:
print("Vi vveli ne cheslo")
y = 0
else:
print("Vse verno")
finally:
print("Vinolnitsa 100%")
try:
res = x/y
except ZeroDivisionError:
print("Vi vveli 0")
res = 0
print(res)
|
# ---------------------
# Imports
from person import Person
from product import Product
from db import DataBase
from classes import (Writer, Pen, Typewriter)
# # ---------------------
# # Instance Person class
# person_one = Person('Ciclano', 25)
# person_two = Person.by_birth_year('Fulano', 1996)
# # ---------------------
# # Talking
# person_one.talk('POO')
# person_one.stop_talk()
# person_two.talk('Python')
# person_two.stop_talk()
# # ---------------------
# # Eating
# person_one.eat('Churrasco')
# person_one.stop_eat()
# person_two.eat('Prato Mil')
# person_two.stop_eat()
# # ---------------------
# # Age and birth year
# print(person_one.age)
# person_one.get_birth_year()
# print(person_two.age)
# person_two.get_birth_year()
# # ---------------------
# # Generate ID
# print(person_one.generate_id())
# print(person_two.generate_id())
# # ---------------------
# # ---------------------
# # Instance Product class
# product_one = Product('Camiseta', 50)
# product_two = Product('Caneca', 'R$15')
# # ---------------------
# # Product discount
# product_one.discount(10)
# product_two.discount(50)
# # ---------------------
# # ---------------------
# # Instance DataBase class
# db = DataBase()
# # ---------------------
# # Add customers
# db.add_customers(1, 'Fulano')
# db.add_customers(2, 'Ciclano')
# db.add_customers(3, 'Beltrano')
# # ---------------------
# # Delete customer
# db.delete_customer(2)
# # ---------------------
# # List customers
# db.list_customers()
# # ---------------------
# # Accessing a private argument (DO NOT use it on production env)
# print(db._DataBase__data)
# ---------------------
# ---------------------
# Instance Writer class
writer = Writer('João')
pen = Pen('BIC')
typewriter = Typewriter('Royal')
# ---------------------
# Check arguments
print(writer.name)
print(pen.brand)
# ---------------------
# Class association (weak association)
writer.tool = typewriter
writer.tool.write()
|
'''
Question 4.1
Route Between Nodes: Given a directed graph, design an algorithm to find out whether there is a route between two nodes.
'''
class Graph:
def __init__(self):
'''
The implementation of an undirected Graph ADT with a few key features kept in mind.
'''
self.graph = {}
def add_edge(self, v, e):
'''
Adds and vertex/edge, if vertex as key is found in dict, then append to the list of edge ends i.e. a -> e would be add_edge(a, e) and the subsequent dict would show something like the following:
self.graph[a] => [e, ...]
'''
if v in self.graph:
self.graph[v].append(e)
else:
self.graph[v] = [e]
def __str__(self):
s = ''
for k in self.graph:
s += '{} -> {}\n'.format(k, self.graph[str(k)])
return s
def has_path(self, start, dest):
start = self.graph[start]
for x in start:
temp = self.graph[x] if x in self.graph else []
start.extend(temp)
if dest in start:
return True
return False
def main():
_Graph = Graph()
_Graph.add_edge('a', 'd')
_Graph.add_edge('b', 'a')
_Graph.add_edge('c', 'b')
_Graph.add_edge('c', 'e')
_Graph.add_edge('e', 'd')
_Graph.add_edge('d', 'f')
print(str(_Graph))
print(_Graph.has_path('c', 'd'))
print(_Graph.has_path('e', 'a'))
print(_Graph.has_path('c', 'f'))
if __name__ == '__main__':
main() |
from socket import *
serverPort = 12000
serverSocket = socket(AF_INET,SOCK_STREAM)
serverSocket.bind(('',serverPort))
#it binds the serverSocket to port number specified in serverPort variable.
#then when anybody sends anything to server IP address and serverPort the serverSocket will get it.
serverSocket.listen(1)
#server listens to TCP connection waiting for client requests.
#the 1 specifies the max number of queued connections(at least 1)
print 'The TCP server is ready to receive'
while 1:
#While 1 is an infinite loop. server is always waiting for requests
connectionSocket, addr = serverSocket.accept()
#when a client reaches to server the accept method for serverSocket creates a new socket in server called connectionSocket.
#the connectionSocket is dedicated to that client. Then the clientSocket and the connectionSocket will do a handshaking to create a TCP connection.
sentence = connectionSocket.recv(1024)
capitalizedSentence = sentence.upper()
connectionSocket.send(capitalizedSentence)
connectionSocket.close()
#the connectionSocket will be closed after the modified sentence is sent back.(new sentence new connectionSocket)
|
age = 20
age = age + 20
# we dont need to give any datatype to the variables
# we can just write any variable and its value
price = 19.85
first_name = "Hitansh "
answer = False
# python is a k sensitive language
print(age)
print(price)
print(first_name)
print(answer) |
# Третьяков Роман Викторович
# Факультет Geek University Python-разработки. Основы языка Python
# Урок 3. Задание 3:
# Реализовать функцию my_func(), которая принимает три позиционных аргумента,
# и возвращает сумму наибольших двух аргументов
def my_func(*args):
# Сортировку намеренно указываем в обратном порядке. Независимо от количества чисел, передаваемых
# в функцию, наибольшие числа будут в начале списка
args = sorted(list(args), reverse = True)
return args[0] + args[1]
try:
print(my_func(4, 2, 10))
except:
print('Ошибка вызова функции!')
try:
print(my_func(6, 12, 78, 3, 1, 23))
except:
print('Ошибка вызова функции!')
try:
print(my_func(1))
except:
print('Ошибка вызова функции!') |
import pandas as pd
def faculties_by_degree(degree):
return degree['Наименование факультета'].dropna()
def specialties_by_faculty(faculty, degree):
faculties = degree['Наименование факультета']
# faculties = faculties.fillna(method='ffill', axis=0) # заполнение объединённых ячеек
fac_specialties = [] # словарь с названием факультета
specialties = degree['Наименование направления подготовки']
# print(specialties)
for i, specialty in enumerate(specialties):
# print(faculties[i], faculty)
if faculties[i].strip() == faculty.strip():
fac_specialties.append(specialty.replace('\xa0',''))
return fac_specialties
def choose_specialty(fac_specialties, specialty):
return {list(fac_specialties.keys())[0]: specialty}
# specialties = specialties_by_faculty('Математический', bachelor)
# faculties = faculties_by_degree(bachelor)
# a = {}
# faculties = [faculty.replace('\xa0','') for faculty in set(faculties)]
# for faculty in faculties:
# a[faculty] = specialties_by_faculty(faculty, bachelor)
# print(a)
# print(bachelor['Наименование факультета'].unique())
# print(bachelor['Наименование факультета'])
# a = dict.fromkeys(('Биология', 'Химия'))
# print(a)
def possible_specialties(exams) -> dict:
specialties = {}
file_path = 'data/specialties.csv'
bachelor = pd.read_csv(file_path)
poss_exams = (bachelor['Вступительное испытание 1'],
bachelor['Вступительное испытание 2_1'],
bachelor['Вступительное испытание 2_2'])
for i, item in enumerate(zip(*poss_exams)):
if item[0] in exams:
if item[1] in exams or item[2] in exams:
specialties[bachelor['Наименование факультета'][i]] = specialties.get(bachelor['Наименование факультета'][i], [])
specialties[bachelor['Наименование факультета'][i]].append({
'Специальность': bachelor['Наименование направления подготовки'][i],
'Профиль': bachelor['Наименование направленности (профиля)'][i]})
return specialties
# print(bachelor.loc[bachelor['Вступительное испытание 1'] == 'Математика'].values)
# dict from keys |
# -*- coding:UTF-8 -*-
import sqlite3
class PriceDatabase:
def __init__(self, watcher):
self.watcher = watcher
self.conn = sqlite3.connect('./db/' + self.watcher.name + '.db')
def create_table(self):
self.conn.execute('CREATE TABLE tbl_price('
'id INTEGER PRIMARY KEY AUTOINCREMENT, '
'name VARCHAR(20), '
'price REAL, '
'time TIMESTAMP);')
print '成功创建数据表!'
def insert(self):
params = (self.watcher.name, self.watcher.price)
self.conn.execute('INSERT INTO tbl_price (name, price, time) '
'VALUES (?, ?, Datetime());', params)
self.conn.commit()
print '成功添加新条目!'
def query(self):
data_list = []
data = self.conn.execute('SELECT name, price, time FROM tbl_price')
for row in data:
price_item = {'name': row[0], 'price': row[1], 'time': row[2]}
data_list.append(price_item)
print '查询成功!'
return data_list
def close_conn(self):
self.conn.close() |
from collections import defaultdict, deque
import functools
import math
import re
def part1(data):
grid, instructions = parse_data(data)
for direction, n in instructions:
new_grid = fold(grid, direction, n)
grid = new_grid
break
return len(grid)
def part2(data):
grid, instructions = parse_data(data)
for direction, n in instructions:
new_grid = fold(grid, direction, n)
grid = new_grid
print_grid(grid)
return None
def fold(grid, direction, n):
new_grid = set()
end = n * 2
for x, y in grid:
if direction == 'y':
if y < n:
new_grid.add((x, y))
elif y <= end:
new_grid.add((x, end - y))
else:
if x < n:
new_grid.add((x, y))
elif x <= end:
new_grid.add((end - x, y))
return new_grid
def print_grid(grid):
x = [p[0] for p in grid]
y = [p[1] for p in grid]
max_x = max(x)
max_y = max(y)
for y in range(max_y + 1):
row = ''
for x in range(max_x + 1):
if (x, y) in grid:
row += '#'
else:
row += '.'
print(row)
def parse_data(data):
rows = data.split('\n')
i = False
grid = set()
instructions = []
for r in rows:
if not r.strip():
i = True
elif not i:
x, y = r.split(',')
grid.add((int(x), int(y)))
else:
foldline = r.split(' ')[-1]
direction, n = foldline.split('=')
instructions.append((direction, int(n)))
return grid, instructions
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def __init__(self):
self.m = {}
def maxPathSum(self, root: TreeNode) -> int:
self.setSums(root)
mm = None
for k in self.m:
d = k.val
if k.left and self.m[k.left] > 0:
d += self.m[k.left]
if k.right and self.m[k.right] > 0:
d += self.m[k.right]
mm = max(mm, d) if mm else d
return mm
def setSums(self, r):
if not r:
return 0
self.m[r] = r.val
mC = max(self.setSums(r.left), self.setSums(r.right))
if mC > 0:
self.m[r] += mC
return self.m[r]
|
from queue import Queue
class Solution:
def numberOfSubstrings(self, s: str) -> int:
q = Queue()
c = {
'a': 0,
'b': 0,
'c': 0
}
movingBound = -1
num = 0
for i, ch in enumerate(s):
q.put((i, ch))
c[ch] += 1
while all(c.values()):
t = q.get()
firstInd = t[0]
c[t[1]] -= 1
num += (firstInd - movingBound) * (len(s) - i - 1) + 1
movingBound = firstInd
return num
print(Solution().numberOfSubstrings('ababbbc'))
print(Solution().numberOfSubstrings('abcabc'))
print(Solution().numberOfSubstrings('aaacb'))
print(Solution().numberOfSubstrings('abc')) |
class Solution:
def capitalizeTitle(self, title: str) -> str:
parts = title.split(' ')
capitalized = []
for p in parts:
if len(p) <= 2:
capitalized.append(p.lower())
else:
capitalized.append(p.title())
return ' '.join(capitalized)
|
from collections import deque
def part1(data):
nums = deque([int(i) for i in data])
for _ in range(100):
cc = nums.popleft()
sides = [nums.popleft() for i in range(3)]
nums.append(cc)
dc = (cc - 1) or 9
while dc in sides:
dc -= 1
# Wrap.
if dc == 0:
dc = 9
for j, n in enumerate(nums):
if n == dc:
for k, s in enumerate(sides):
nums.insert((j + 1 + k) % len(nums), s)
break
return ''.join([str(i) for i in nums])
class Node(object):
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def part2(data):
max_num = 1000000
nodes = dict()
first_node = None
curr_node = None
for i in data:
n = Node(int(i))
if curr_node:
curr_node.right = n
n.left = curr_node
else:
first_node = n
nodes[n.value] = n
curr_node = n
for i in range(10, max_num + 1):
n = Node(i)
curr_node.right = n
n.left = curr_node
nodes[i] = n
curr_node = n
curr_node.right = first_node
first_node.left = curr_node
curr_node = first_node
for _ in range(10000000):
nn = curr_node.right
sides = set()
for _ in range(3):
sides.add(nn.value)
nn = nn.right
dc = (curr_node.value - 1) or max_num
while dc in sides:
dc = (dc - 1) or max_num
n = nodes[dc]
moving_link_start = curr_node.right
moving_link_end = nn.left
r = n.right
n.right = moving_link_start
moving_link_start.left = n
r.left = moving_link_end
moving_link_end.right = r
curr_node.right = nn
nn.left = curr_node
curr_node = nn
first = nodes[1].right
second = first.right
return first.value * second.value
def parse_data(data):
rows = data.split('\n')
return rows
|
x = int(input('enter an integer for which you would like the cube-root: '))
for guess in range(abs(x) + 1):
if guess **3 >= abs(x):
break
if guess**3 != abs(x):
print(x, 'is not a perfect cube.')
else:
if x < 0:
guess = -guess
print(guess, 'is the cube root of ' , x )
|
x = int(input('enter an integer for which you would like the cube-root: '))
for guess in range(x + 1):
if guess**3 == x:
print(guess, 'is the cube root of ', x)
if guess == x:
print(x, 'is not a perfect cube.')
|
i = 10
print('Hello!')
while i >= 2:
print(i)
i -= 2
|
#coding=utf-8
# 输出 9*9 乘法口诀表。
for i in range(1,10):
for j in range(1,10):
a=" "
if(j<=i):
print(j, "*", i,"=",i*j ,a,end="")
print("\n")
for i in range(1,10):
for j in range(1,10):
if j<=i:
print(i,"*",j,"=",i*j," ",end="")
print("\n")
|
#coding=utf-8
# 输入中文你好
print("你好")
# 编写程序输入你的名字 并输出
#请写出 多行文字 并对其进行注释
"""
asdfasdfasdfas
asdfasdfasdf
"""
#一条语句如果很长,如何来实现多行语句
#字符串操作
str = 'Runoob'
# 输出第一个到倒数第二个的所有字符
# 输出字符串第一个字符
# 输出从第三个开始到第五个的字符
# 输出从第三个开始的后的所有字符
# 输出字符串两次
# 连接字符串
#做一个不换行输出
#如何查询变量所指的对象类型
#演示删除一个对象的引用
#演示 数值运算 除法,得到一个浮点数
#演示 数值运算 除法,得到一个整数
#演示 数值运算 2的3次方
#演示 数值运算 取余
#判断题 回答python是否有 字符类型?
#演示声明一个列表
#输出完整列表
#输出第一个元素
# # 从第二个开始输出到第三个元素
# 输出从第三个元素开始的所有元素
# 再声明一个列表并连接
#列表的元素是可以修改的
# 第一个元素改成9
#元组和列表不同在与元素不能修改
# tuple=(12,"成",99.8,30)
# 输出第二个
#创建一个空的集合
#创建一个学生集合
students=["zhangsan","xo","llllls"]
# 判断 zhangsan 是否则在学生集合里面 如果是 输出yes
if "zhangsan" in students :
print("true")
else:
print("false")
a=set("abcl")
b=set("abcdef")
# print(a-b)
# print(a | b)
# print(a^b)
print(a-b)# a 和 b 的差集
print(a|b)# a 和 b 的并集
# a 和 b 中不同时存在的元素
|
#获取文件对象
file=open("hello.txt","w")
# strmess="""Python是非常好的 语言!
# 我们都很喜欢她
# """
print("文件名字:",file.name)
file.write("123")
file.write('\n')
file.write("456")
# 关闭打开的文件
file.close()
file1=open("hello.txt");
strreadline=file1.readline()
print("strreadline=",strreadline)
file1.close |
# Write a program that simualates the Monty Hall Problem and prove numerically why you should always switch.
# Two inputs: number of games and switch/stay
"""
Suppose you're on a game show, and you're given the choice of three doors: Behind one door is a car; behind the others, goats. You pick a door, say No. 1, and the host, who knows what's behind the doors, opens another door, say No. 3, which has a goat. He then says to you, "Do you want to pick door No. 2?" Is it to your advantage to switch your choice?
"""
def MontyHall(num_games, switch_stay):
"""
num_games: Positive integer. Number of games to be played
switch_stay: string 'switch' or 'stay'. Which action to take
return: Probability of winning the game
"""
# import random module
import random
# Initial conditions
# Set up win count = 0
# Set up lose count = 0
# Set up play count = number of games to play
# Set up doors
win_count = 0
lose_count = 0
play_count = num_games
doors = ['car', 'goat', 'goat']
# Playing the game
while play_count > 0:
# Initial conditions per game
# Player chooses random door
pick1 = random.choice(doors)
# If pick1 == car
if pick1 == 'car':
# Stay, Win Game
if switch_stay == 'stay':
win_count += 1
# Switch, Lose Game
else:
lose_count += 1
# If pick1 = goat
# Game host will always show other goat
else:
# Stay, Lose Game
if switch_stay == 'stay':
lose_count += 1
# Switch, Win Game
else:
win_count += 1
# Update game count by 1
play_count -= 1
# When all games are played
# Find the % of won games
# Print out probability of winning for switch/stay
win_prob = (win_count / num_games) * 100
print('The probability of winning if you played', num_games, 'games and ', end = '')
print(switch_stay, 'is:', str(win_prob) + '%')
MontyHall(1000,'switch')
MontyHall(1000,'stay') |
class Queue:
def __init__(self):
self.items = []
def is_empty(self):
if not self.items:
print("Stack is empty")
return
def enqueue(self,item):
self.items.append(item)
def dequeue(self):
self.is_empty()
self.items.pop(0)
def size(self):
self.is_empty()
print()
print(len(self.items))
def peak(self):
self.is_empty()
return print(self.items[0])
def enqueue_without_using_insert(self,item):
self.items.append(item)
def print(self):
self.is_empty()
for element in self.items:
print(str(element) +"-->",end='')
if __name__ == "__main__":
obj = Queue()
obj.enqueue(3)
obj.enqueue(7)
obj.enqueue(9)
obj.dequeue()
obj.print()
|
from cards import Card
import random
class Game:
def __init__ (self):
self.size = 4
self.card_options = ['Add', 'Boo', 'Cat', 'Dev',
'Egg', 'Far', 'Gum', 'Hut']
self.columns = ['A', 'B', 'C', 'D']
self.cards = []
self.locations = []
for column in self.columns:
for num in range(1, self.size + 1):
self.locations.append(f'{column}{num}')
def set_cards(self):
used_locations = []
for word in self.card_options:
for i in range(2):
available_locations = set(self.locations) - set(used_locations)
random_location = random.choice(list(available_locations))
used_locations.append(random_location)
card = Card(word, random_location)
self.cards.append(card)
self.cards.append(card)
def create_row(self, num):
row = []
for column in self.columns:
for card in self.cards:
if card.location == f'{column}{num}':
if card.matched:
row.append(str(card))
else:
row.append(" ")
return row
#method
#create cards
#create grid
#check for matches
#check game wom
#run game
#dunder main
if __name__ == "__main__":
game = Game()
game.set_cards()
game.cards[0].matched = True
game.cards[1].matched = True
game.cards[2].matched = True
game.cards[3].matched = True
print(game.create_row(1))
print(game.create_row(2))
print(game.create_row(3))
print(game.create_row(4))
#create game instance
#call start game
|
from abc import ABCMeta, abstractmethod
class Animal(metaclass = ABCMeta):
@abstractmethod
def __init__(self, species, shape, character):
self.species = species
self.shape = shape
self.character = character
@property
def is_raptor(self):
if self.species == 'eat-meat' and self.character == 'ferocious' and (self.shape == 'M' or self.shape == 'L'):
return True
return False
class Cat(Animal):
sound = 'miaomiao'
def __init__(self, name, species, shape, character):
self.name = name
super().__init__(species, shape, character)
@property
def is_pet(self):
if self.character == 'mild' and self.shape == 'S':
return True
else:
return False
class Zoo:
def __init__(self, name):
self.name = name
self.animals = {}
def add_animal(self, animal):
animal_id = id(animal)
animal_class_name = animal.__class__.__name__
if animal_id in self.animals:
print (f'Animal with id {animal_id} already added')
return
else:
self.animals[animal_id] = animal
if __name__ == '__main__':
z = Zoo('time-zoo')
cat1 = Cat('big-cat', 'eat-meat', 'M', 'mild')
z.animals('cat1')
|
from board import Board
def get_row_col (initiate_board : bool = False) -> int:
row, col = -1, -1
while row == -1 or col == -1:
row, col = -1, -1
try :
row = str (input ('linha? '))
col = int (input ('coluna? '))
except:
print ('Erro na introduçao de dados')
if initiate_board:
try:
row = int (row)
except:
print ('row must be an integer')
else:
row = ord (row) - ord ('A')
col -= 1
return row, col
def interaction(board : Board) -> None:
while (True):
row, col = get_row_col ()
if board.in_bounds (row, col):
board.make_play(row, col)
board.draw_board()
if board.check_winner():
print ('Winner!')
cmd = input ('continue? ')
if cmd == 'n':
break
print ('hey')
main()
def main ():
rows, cols = get_row_col (initiate_board = True)
board = Board(rows, cols)
board.draw_board()
interaction(board)
if __name__ == '__main__':
main () |
import requests
from bs4 import BeautifulSoup
class PriceBot(object):
URL = 'https://www.johnlewis.com/house-by-john-lewis-hinton-office-chair/p2083183'
def get_price(self):
r = requests.get(self.URL)
content = r.content
soup = BeautifulSoup(content, "html.parser")
element = soup.find("span", {"itemprop": "price", "class": "now-price"})
string_price = element.text.strip() # £129.00
price_without_symbol = string_price[1:]
price = float(price_without_symbol)
return price
# if price < 200:
# print('You should buy the chair!')
# print('The current price is {}'.format(price))
# else:
# print('Do not buy, it\'s too expensive!') |
def do_twice(func):
def wrapper_do_twice(*args, **kwargs):
func(*args, **kwargs)
return func(*args, **kwargs) # <- Zwrócenie wartości
return wrapper_do_twice
@do_twice
def return_greeting(name):
print("Creating greeting")
return f"Hi {name}"
if __name__ == '__main__':
print(return_greeting("Bart"))
print(return_greeting.__name__) |
# a = 1
# b = 2
#print(a+b)
# Przykład działania funkcji na referencji
def last_item_add1(list_a, elem_a=10):
last_elem = list_a[-1]
last_elem += elem_a
list_a.append(last_elem)
# Funkcja zwracająca wartość
def last_item_add2(list_a, elem_a):
last_elem = list_a[-1]
last_elem += elem_a
list_a.append(last_elem)
return list(list_a)
# Funkcja z argumentem z wartością domyślną
def last_item_add3(list_a, elem_a=10):
last_elem = list_a[-1]
last_elem += elem_a
list_a.append(last_elem)
return list(list_a)
# Przykład działania last_item_add2
temp_list = [1,2,3,4]
temp_list_2 = last_item_add2(temp_list,5)
print(temp_list_2)
print(temp_list_2 is temp_list)
# Przykład działania last_item_add1
temp_list_3 = last_item_add3(temp_list)
print(temp_list_3)
|
"""
Gettery i settery.
W OOP program powinien mieć argumenty prywatne.
Aby móc do nich dostać się z zewnątrz, potzebne są pewne metody.
Getter to metoda która pozwala nam na uzystanie wartości dla atrybutu prywatnego.
Natomiast setter pozwala na ustawienie wartości atrybutu.
"""
class CodeCouple(object):
def __init__(self, name):
self.set_name(name)
def get_name(self):
return self.__name
def set_name(self, name):
if name == 'Agnieszka':
self.__name = 'beautiful'
elif name == 'Krzysztof':
self.__name = 'ugly'
else:
self.__name = 'CodeCouple'
if __name__ == '__main__':
agnieszka = CodeCouple('Agnieszka')
print(agnieszka.get_name())
krzysztof = CodeCouple('Krzysztof')
print(krzysztof.get_name())
code_couple = CodeCouple('UglyKrzysztof')
print(code_couple.get_name())
print(agnieszka.__dict__)
print(agnieszka._CodeCouple__name) |
temp_list = []
for i in range(100):
temp_list.append(i**2)
print(temp_list)
temp_list_2 = [i**2 for i in range(100)]
print(temp_list_2)
print(temp_list == temp_list_2)
|
"""
Pakiet argparse.
Ten pakiet pozwala nam nie tylko interpretować argumenty linii komend
ale także podać informację pomocniczą w razie gdyby nie wiadomo było
co trzeba wprowadzić
"""
import argparse
# Dodajemy opis programu za pomocą słowa kluczowego 'description'
parser = argparse.ArgumentParser(description="Example of simple argument parser")
# Dodajemy nazwę argumentu linii komend <- zwykły pozycyjny
parser.add_argument(
"square", # <- nazwa argumentu
help="display a square of given number", # <- opis pomocniczy
type=int # <- typ argumentu
)
# Dodajemy argument opcjonalny
parser.add_argument("-v", "--verbosity", type=int,
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
print("the square of {} equals {}".format(args.square, answer))
elif args.verbosity == 1:
print("{}^2 == {}".format(args.square, answer))
else:
print(answer) |
def isPerfect(n):
# To store sum of divisors
sum = 1
# Find all divisors and add them
i = 2
while i * i <= n:
if n % i == 0:
sum = sum + i + n / i
i += 1
# If sum of divisors is equal to
# n, then n is a perfect number
return (True if sum == n and n != 1 else False)
# Driver program
t = int(input("Enter the number of test :"))
for i in range(t):
n = int(input("Enter the Values: "))
if isPerfect(n):
print("YES")
else:
print("NO") |
"""
This is the program for adding two numbers
"""
import os,sys
fname=input("Enter File Name: ")
if os.path.isfile(fname):
print("File exists:",fname)
f=open(fname,"r")
else:
print("File does not exist:",fname)
sys.exit(0)
print("The content of file is:")
data=f.read()
print(data) |
try:
number_input_a = int(input("정수입력>"))
print("원의 반지름:",number_input_a)
print("원의 둘레:",2*3.14*number_input_a)
print("원의 넓이:",3.14*number_input_a*number_input_a)
except Exception as exception:
print("type(exception):",type(exception))
print("exception:",exception)
list_number = [52,324,534,23,100]
try:
number_input_a = int(input("정수입력>"))
print("{}번째 요소:{}".format(number_input_a,list_number[number_input_a]))
except Exception as exception:
print("type(exception):",type(exception))
print("exception:",exception)
try:
number_input_a = int(input("정수입력>"))
print("{}번째 요소:{}".format(number_input_a,list_number[number_input_a]))
except ValueError as exception:
print("정수를 입력하세요")
print("exception:",exception)
except IndexError as exception:
print("인덱스를 벗어 났어요")
print("exception:",exception)
list_number = [52,273,32,72,100]
try:
number_input = int(input("정수 입력>"))
print("{}번째 요소:{}".format(number_input,list_number[number_input]))
raise NotImplementedError
except ValueError as exception:
print("정수를 입력해 주세요!")
print(type(exception),exception)
except IndexError as exception:
print("리스트 인덱스를 벗어 났어요?")
print(type(exception),exception)
except Exception as exception:
print("미리 파악하지 못한 예외가 발생")
print(type(exception),exception)
|
dic={
"name" : "7d 건조 망고",
"type" : "당절임",
"ingredient" : ["망고","설탕","메타중아황산나트륨","치자황색소"],
"origin" : "필리핀"
}
print("name:",dic["name"])
print("type:",dic["type"])
print("ingredient:",dic["ingredient"])
print("origin:",dic["origin"])
dic["name"] = "8d 건조 망고"
print("name:",dic["name"])
print("ingredient:",dic["ingredient"][1])
dic["price"] = 5000
print("price : ",dic["price"])
print(dic)
del dic["ingredient"]
print(dic)
dic2={
"test" : "test"
}
print("요소추가 이전:",dic2)
dic2["name"]="새로운 이름"
dic2["head"]="새로운 정신"
dic2["body"]="새로운 몸"
print("요소 추가 이후:",dic2)
print("요소제거 이전 :",dic)
del dic["name"]
del dic["type"]
print("요소제거 이후 : ",dic)
key = input(">접근하고자 하는 키 :")
print(key)
print(dic2[key])
if key in dic2:
print(dic2[key])
else:
print("존재하지 않는 키에 접근하고 있습니다.")
value = dic2.get(key)
print("값:",value)
if value == None:
print("존재하지 않는 키에 접근 했었습니다. ")
for key in dic2:
print(key,":",dic2[key])
|
import sqlite3
conn = sqlite3.connect('participants_db.db')
print("Opened database successfully")
conn.execute('''CREATE TABLE PARTICIPANT_BALANCE
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
BALANCE INT NOT NULL);''')
print("Table created successfully")
conn.execute("INSERT INTO PARTICIPANT_BALANCE (ID,NAME,BALANCE) \
VALUES (1, 'a', 2000)");
conn.execute("INSERT INTO PARTICIPANT_BALANCE (ID,NAME,BALANCE) \
VALUES (2, 'b', 5000)");
conn.execute("INSERT INTO PARTICIPANT_BALANCE (ID,NAME,BALANCE) \
VALUES (3, 'c', 3000)");
conn.execute("INSERT INTO PARTICIPANT_BALANCE (ID,NAME,BALANCE) \
VALUES (4, 'd', 6000)");
conn.execute("INSERT INTO PARTICIPANT_BALANCE (ID,NAME,BALANCE) \
VALUES (5, 'e', 7000)");
conn.execute("INSERT INTO PARTICIPANT_BALANCE (ID,NAME,BALANCE) \
VALUES (6, 'f', 8000)");
conn.execute("INSERT INTO PARTICIPANT_BALANCE (ID,NAME,BALANCE) \
VALUES (7, 'g', 8000)");
conn.commit()
print("Records created successfully");
conn.close()
|
class Node:
def __init__(self, data):
self.data = data
self.next_node = None
self.prev_node = None
class LinkedList:
def __init__(self):
self.head = None
self.tail=None
self.size = 0
def insertBeg(self, data):
if self.head == None:
self.head = Node(data)
self.tail=self.head
self.size+=1
else:
newNode = Node(data)
newNode.next_node = self.head
self.head.prev_node = newNode
self.head = newNode
newNode.prev_node=None
self.size+=1
def insertEnd(self, data):
if self.tail is None:
return
else:
newnode = Node(data)
currentNode = self.tail
currentNode.next_node=newnode
newnode.prev_node=currentNode
def traversingfrombeg(self):
newnode = self.head
while newnode is not None:
print(newnode.data)
newnode = newnode.next_node
return
def traversingfromend(self):
newnode=self.tail
while newnode is not None:
print(newnode.data)
newnode=newnode.prev_node
l=LinkedList()
l.insertBeg(1)
l.insertBeg(34)
l.insertBeg(4)
l.insertBeg(304)
l.insertBeg(43)
l.traversingfromend()
print()
l.traversingfrombeg()
|
# 1. Создать программно файл в текстовом формате, записать в него построчно данные, вводимые пользователем.
# Об окончании ввода данных свидетельствует пустая строка.
with open('file.txt', 'w') as f_text:
my_list = input('Введите предложение: ').split()
for line in my_list:
f_text.write(line + '\n')
print(f_text)
|
class VMWriter:
""" todo: !!! important!!! symobl tables for operators so we can convert
todo: them easily to vm code
"""
BIN_OPS = \
{
'+': 'add',
'-': 'sub',
'&': 'and',
'|': 'or',
'<': 'lt',
'>': 'gt',
'=': 'eq'
}
UN_OPS = \
{
'~': 'not',
'-': 'neg'
}
def __init__(self, out_file_name):
self.outFile = open(out_file_name, 'w')
def out(self, string):
self.outFile.write(string + '\n')
def writePush(self, segment, index):
"""
this method writes a push command in vm language according to the
segment and index we are pulling from
:param segment: the segment from which we are pushing
:param index: the index in that segment
:return: nothing
"""
self.out('push ' + segment + ' ' + str(index))
def writePop(self, segment, index):
"""
this method writes a pop command in vm language according to the
segment and index we are pushing to
:param segment: the segment to which we are pushing
:param index: the index in the segment
:return: nothing
"""
self.out('pop ' + segment + ' ' + str(index))
def WriteArithmetic(self, command, un):
"""
this method writes an arithmetic command in vm language
:param command: the arithmetic operators name
:param un: whether the symbol is unary or not
:return: nothing
"""
if un:
command = self.UN_OPS[command]
else:
command = self.BIN_OPS[command]
self.out(command)
def WriteLabel(self, label):
"""
this method writes a new label in vm language
:param label: the labels name
:return: nothing
"""
self.out('label ' + label)
def WriteGoto(self, label):
"""
this method writes a goto command to a certain label in vm language
:param label: the labels name
:return: nothing
"""
self.out('goto ' + label)
def WriteIf(self, label):
"""
this method writes an if command in vm language
:param label: the labels name
:return: nothing
"""
self.out('if-goto ' + label)
def writeCall(self, name, n_args):
"""
this method calls a function in vm language
:param name: the name of the function
:param n_args: the number of arguments it uses
:return: nothing
"""
self.out('call ' + name + ' ' + str(n_args))
def writeFunction(self, name, n_args):
"""
this method declares a function in vm language
:param name: the name of the function
:param n_args: the number of arguments it uses
:return: nothing
"""
self.out('function ' + name + ' ' + str(n_args))
def writeReturn(self):
"""
just writes return basically
:return: nothing
"""
self.out('return')
def close(self):
"""
closes the output file we are writing into
:return: nothing
"""
self.outFile.close()
|
from tkinter import *
from random import randint
root = Tk()
root.title('Password Generator by Alvin')
root.geometry("500x300")
def new_rand():
#Clear entry box
pw_entry.delete(0, END)
#Get password lenght
length = 8
#Create variable to hold our password
my_password = ''
#Loop through password length
for x in range(length):
my_password += chr(randint(33,126))
#Output password
pw_entry.insert(0, my_password)
#Labelframe
frame = LabelFrame(root, text='Password Lenght is 8 Characters')
frame.pack(pady=20)
#Password label
my_label = Label(root, text='Password Length is 8 Characters')
my_label.pack()
#Input field for password
pw_entry = Entry(root, text='', font=("Helvetica", 24))
pw_entry.pack(pady=20)
#Create frame for buttons
my_frame = Frame(root)
my_frame.pack(pady=20)
#Create buttons
my_button = Button(my_frame, text='Generate Strong Password', command=new_rand)
my_button.grid(row=0, column=0, padx=10)
root.mainloop() |
price = 0
avgprice = 83
import time
name = input("What is your name: ")
print("We offer 3 different sizes of pizza, 6 ince ,9 ince or 12 inch")
choice1 = input("Pizza size(inch): ")
if choice1 == "6":
price += 20
elif choice1 == "9":
price += 30
elif choice1 == "12":
price += 40
else:
price += 20
time.sleep(0.5)
print()
choice2 = input("Do you want a thicker crust? That will be charged $5 extra!\n If yes,please input yes: ")
if choice2 == "yes":
choice2b = "thick"
price += 5
else:
choice2b = "thin"
price += 0
print()
m,p,c,t = 0,0,0,0
time.sleep(0.5)
print("What ingredients do you want? Ingredients available: mushroom $15, peproni $20, chicken $25, tomato $8")
choice3 = input("Input format: 'm' for mushroom , 'p' for peproni, 'c' for chicken, 't' for tomato: ")
active = True
while True:
c3 = input(choice3)
if c3 == "m":
price += 15
print("Mushroom added! Anything more?")
elif c3 == "p":
price += 20
print("Peproni added! Anything more?")
elif c3 == "c":
price += 25
print("Chicken added! Anything more?")
elif c3 == "t":
price += 8
print("Tomato added! Anything more?")
break
active = False
print(f"The total cost is: {price}")
print("Order received! Your pizza is being prepared!")
|
import re
#正则表达式简介
#怎样验证一个字符串是日期YYYY-MM-DD格式?
#正则表达式:一些由字符和特殊符号组成的字符串,它们描述了重复模式,能够匹配多个字符串
def date_is_right(date):
return re.match("\d{4}-\d{2}-\d{2}", date) is not None
date1 = "2021-02-03"
date2 = "202-01-04"
date3 = "2022/05/05"
date4 = "20210707"
print(date1, date_is_right(date1))
print(date2, date_is_right(date2))
print(date3, date_is_right(date3))
print(date4, date_is_right(date4))
|
# Tyrone Tong 39813123
import project5 as game
import copy
import random
import pygame
class board:
def starting_board(self) -> None:
''' This function creates the list if it is empty or has contents in it'''
user_input_lst = []
lst = []
built_row = []
contents_lst = []
dimensions = game.get_dimensions()
row = dimensions[0]
column = dimensions[1]
for i in range(row):
built_row.append('|')
for x in range(column * 3):
built_row.append(" ")
built_row.append('|')
lst.append(built_row)
built_row = []
self.fall(lst)
def fall(self,board_state) -> None:
'''This function is called on when a user puts in a command that starts with F its purpose is to iterate throught the rows and make changes to the function'''
pygame.init()
game_window = pygame.display.set_mode((600,600))
pygame.display.set_caption("Columns")
game_window.fill((255,255,255))
pygame.display.flip()
gameExit = False
game.build_board(board_state,game_window)
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
quit()
color = ["S", "T", "V", "W", "X", "Y", "Z"]
colors = [color[random.randint(0, 6)], color[random.randint(0, 6)], color[random.randint(0, 6)]]
copy_board_state = copy.deepcopy(board_state)
interesting_column = (random.randint(1,6) * 3) - 1
for rows_index in range(len(board_state)):
x = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors, game_window)
if x[0] == "NEW":
board_state = x[1]
break
elif x[0] == "True":
interesting_column = x[1]
elif x[0] == "SIDE":
interesting_column = x[1]
elif x[0] == "ROTATE":
colors = x[1]
else:
self.game_over()
quit()
board_state = self.check_board(board_state,game_window)
def straight(self, board_state: list, rows_index: int, interesting_column: int, copy_board_state: list,colors: list,game_window) -> bool:
'''This function makes changes to the board as it iterates through the rows where it is called on'''
indexes = 2
if rows_index == 0:
current_row = board_state[rows_index]
if current_row[interesting_column] == " ":
current_row[interesting_column - 1] = '['
current_row[interesting_column + 1] = ']'
current_row[interesting_column] = colors[indexes]
game.build_board(board_state,game_window)
user_input = game.user_input()
if user_input == "":
return ("True", interesting_column)
elif user_input == "<":
if current_row[interesting_column - 3] == ' ':
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column - 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
interesting_column = y[1]
return ("SIDE", interesting_column)
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == ">":
if current_row[interesting_column + 3] == ' ':
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column + 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
interesting_column = y[1]
return ("SIDE", interesting_column)
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == "R":
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
last_element = colors[2]
colors.pop(2)
colors = [last_element] + colors
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
if type(y[1]) == int:
pass
else:
colors = y[1]
return ("ROTATE", colors)
else:
game.build_board(board_state,game_window)
return "False"
if rows_index == 1:
previous_row = board_state[rows_index - 1]
current_row = board_state[rows_index]
if current_row[interesting_column] == " ":
previous_row[interesting_column - 1] = '['
previous_row[interesting_column + 1] = ']'
current_row[interesting_column - 1] = '['
current_row[interesting_column + 1] = ']'
previous_row[interesting_column] = colors[indexes - 1]
current_row[interesting_column] = colors[indexes]
game.build_board(board_state,game_window)
user_input = game.user_input()
if user_input == "":
return ("True", interesting_column)
elif user_input == "<":
if current_row[interesting_column - 3] == ' ':
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column - 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
interesting_column = y[1]
return ("SIDE", interesting_column)
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == ">":
if current_row[interesting_column + 3] == ' ':
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column + 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
interesting_column = y[1]
return ("SIDE", interesting_column)
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == "R":
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
last_element = colors[2]
colors.pop(2)
colors = [last_element] + colors
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
if type(y[1]) == int:
pass
else:
colors = y[1]
return ("ROTATE", colors)
else:
previous_row[interesting_column - 1] = '|'
previous_row[interesting_column + 1] = '|'
previous_row[interesting_column] = colors[indexes]
game.build_board(board_state,game_window)
user_input = game.user_input()
if user_input == "":
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
game.build_board(board_state,game_window)
return "False"
elif user_input == "<":
if current_row[interesting_column - 3] == ' ':
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column - 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
interesting_column = y[1]
return ("SIDE", interesting_column)
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == ">":
if current_row[interesting_column + 3] == ' ':
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column + 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
interesting_column = y[1]
return ("SIDE", interesting_column)
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == "R":
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
last_element = colors[2]
colors.pop(2)
colors = [last_element] + colors
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
if type(y[1]) == int:
pass
else:
colors = y[1]
return ("ROTATE", colors)
if rows_index == 2:
previous_row2 = board_state[rows_index - 2]
previous_row = board_state[rows_index - 1]
current_row = board_state[rows_index]
if current_row[interesting_column] == " ":
previous_row2[interesting_column - 1] = '['
previous_row2[interesting_column + 1] = ']'
previous_row[interesting_column - 1] = '['
previous_row[interesting_column + 1] = ']'
current_row[interesting_column - 1] = '['
current_row[interesting_column + 1] = ']'
previous_row2[interesting_column] = colors[indexes - 2]
previous_row[interesting_column] = colors[indexes - 1]
current_row[interesting_column] = colors[indexes]
game.build_board(board_state,game_window)
user_input = game.user_input()
if user_input == "":
return ("True", interesting_column)
elif user_input == "<":
if current_row[interesting_column - 3] == ' ':
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column - 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
interesting_column = y[1]
return ("SIDE", interesting_column)
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == ">":
if current_row[interesting_column + 3] == ' ':
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column + 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
interesting_column = y[1]
return ("SIDE", interesting_column)
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == "R":
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
last_element = colors[2]
colors.pop(2)
colors = [last_element] + colors
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
if type(y[1]) == int:
pass
else:
colors = y[1]
return ("ROTATE", colors)
else:
previous_row2[interesting_column - 1] = '|'
previous_row2[interesting_column + 1] = '|'
previous_row[interesting_column - 1] = '|'
previous_row[interesting_column + 1] = '|'
previous_row2[interesting_column] = colors[indexes - 1]
previous_row[interesting_column] = colors[indexes]
game.build_board(board_state,game_window)
user_input = game.user_input()
if user_input == "":
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
game.build_board(board_state,game_window)
return "False"
elif user_input == "<":
if current_row[interesting_column - 3] == ' ':
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column - 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
interesting_column = y[1]
return ("SIDE", interesting_column)
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == ">":
if current_row[interesting_column + 3]:
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column + 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
interesting_column = y[1]
return ("SIDE", interesting_column)
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == "R":
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
last_element = colors[2]
colors.pop(2)
colors = [last_element] + colors
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
if type(y[1]) == int:
pass
else:
colors = y[1]
return ("ROTATE", colors)
if rows_index > 2 and rows_index != len(board_state) - 1:
previous_row2 = board_state[rows_index - 2]
previous_row = board_state[rows_index - 1]
current_row = board_state[rows_index]
if current_row[interesting_column] == " ":
previous_row2[interesting_column - 1] = '['
previous_row2[interesting_column + 1] = ']'
previous_row[interesting_column - 1] = '['
previous_row[interesting_column + 1] = ']'
current_row[interesting_column - 1] = '['
current_row[interesting_column + 1] = ']'
board_state[rows_index - 3] = copy_board_state[rows_index - 3]
previous_row2[interesting_column] = colors[indexes - 2]
previous_row[interesting_column] = colors[indexes - 1]
current_row[interesting_column] = colors[indexes]
game.build_board(board_state,game_window)
user_input = game.user_input()
if user_input == "":
return ("True", interesting_column)
elif user_input == "<":
if current_row[interesting_column - 3] == ' ':
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column - 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
interesting_column = y[1]
return ("SIDE", interesting_column)
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == ">":
if current_row[interesting_column + 3] == ' ':
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column + 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
interesting_column = y[1]
return ("SIDE", interesting_column)
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == "R":
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
last_element = colors[2]
colors.pop(2)
colors = [last_element] + colors
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
if type(y[1]) == int:
pass
else:
colors = y[1]
return ("ROTATE", colors)
else:
rows_index = rows_index - 1
previous_row2 = board_state[rows_index - 2]
previous_row = board_state[rows_index - 1]
current_row = board_state[rows_index]
current_row[interesting_column - 1] = '|'
current_row[interesting_column + 1] = '|'
previous_row2[interesting_column - 1] = '|'
previous_row2[interesting_column + 1] = '|'
previous_row[interesting_column - 1] = '|'
previous_row[interesting_column + 1] = '|'
board_state[rows_index - 3] = copy_board_state[rows_index - 3]
previous_row2[interesting_column] = colors[indexes - 2]
previous_row[interesting_column] = colors[indexes - 1]
current_row[interesting_column] = colors[indexes]
game.build_board(board_state,game_window)
user_input = game.user_input()
if user_input == "":
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
return ("NEW", board_state)
elif user_input == "<":
if current_row[interesting_column - 3] == ' ':
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column - 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
interesting_column = y[1]
return ("SIDE", interesting_column)
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == ">":
if current_row[interesting_column + 3] == ' ':
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column + 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
interesting_column = y[1]
return ("SIDE", interesting_column)
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == "R":
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
last_element = colors[2]
colors.pop(2)
colors = [last_element] + colors
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
if type(y[1]) == int:
pass
else:
colors = y[1]
return ("ROTATE", colors)
if (rows_index + 1) == len(board_state):
previous_row2 = board_state[rows_index - 2]
previous_row = board_state[rows_index - 1]
current_row = board_state[rows_index]
if current_row[interesting_column] == " ":
previous_row2[interesting_column - 1] = '|'
previous_row2[interesting_column + 1] = '|'
previous_row[interesting_column - 1] = '|'
previous_row[interesting_column + 1] = '|'
current_row[interesting_column - 1] = '|'
current_row[interesting_column + 1] = '|'
board_state[rows_index - 3] = copy_board_state[rows_index - 3]
previous_row2[interesting_column] = colors[indexes - 2]
previous_row[interesting_column] = colors[indexes - 1]
current_row[interesting_column] = colors[indexes]
game.build_board(board_state,game_window)
user_input = game.user_input()
if user_input == "":
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
previous_row2[interesting_column] = colors[indexes - 2]
previous_row[interesting_column] = colors[indexes - 1]
current_row[interesting_column] = colors[indexes]
return ("NEW", board_state)
elif user_input == "<":
if current_row[interesting_column - 3] == ' ':
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column - 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return (y[0], y[1])
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == ">":
if current_row[interesting_column + 3] == ' ':
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column + 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return (y[0], y[1])
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == "R":
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
last_element = colors[2]
colors.pop(2)
colors = [last_element] + colors
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
if type(y[1]) == int:
pass
else:
colors = y[1]
return ("NEW", board_state)
else:
rows_index = rows_index - 1
previous_row2 = board_state[rows_index - 2]
previous_row = board_state[rows_index - 1]
current_row = board_state[rows_index]
current_row[interesting_column - 1] = '|'
current_row[interesting_column + 1] = '|'
previous_row2[interesting_column - 1] = '|'
previous_row2[interesting_column + 1] = '|'
previous_row[interesting_column - 1] = '|'
previous_row[interesting_column + 1] = '|'
board_state[rows_index - 3] = copy_board_state[rows_index - 3]
previous_row2[interesting_column] = colors[indexes - 2]
previous_row[interesting_column] = colors[indexes - 1]
current_row[interesting_column] = colors[indexes]
game.build_board(board_state,game_window)
user_input = game.user_input()
if user_input == "":
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
return ("NEW")
elif user_input == "<":
if current_row[interesting_column - 3] == ' ':
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column - 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
interesting_column = y[1]
return ("NEW", board_state)
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == ">":
if current_row[interesting_column + 3] == ' ':
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
interesting_column = interesting_column + 3
board_state = copy.deepcopy(copy_board_state)
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
interesting_column = y[1]
return ("NEW", board_state)
else:
board_state = copy.deepcopy(copy_board_state)
self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
return ("SIDE", interesting_column)
elif user_input == "R":
previous_row2[interesting_column - 1] = ' '
previous_row2[interesting_column + 1] = ' '
previous_row2[interesting_column] = ' '
previous_row[interesting_column - 1] = ' '
previous_row[interesting_column + 1] = ' '
previous_row[interesting_column] = " "
current_row[interesting_column - 1] = ' '
current_row[interesting_column + 1] = ' '
current_row[interesting_column] = ' '
last_element = colors[2]
colors.pop(2)
colors = [last_element] + colors
y = self.straight(board_state, rows_index, interesting_column, copy_board_state, colors,game_window)
if type(y[1]) == int:
pass
else:
colors = y[1]
return ("NEW", board_state)
def check_board(self, board_state: list,game_window) -> list:
''' This function is called on after every new move to check if the board has any 3 or more in a row. It takes
in the current board and returns the modified board'''
x = self.vertical(board_state)
y = self.horizontal(board_state)
z = self.diagonal(board_state)
t = board_state
if x == False or y == False or z == False:
game.build_board(board_state,game_window)
user_input = game.user_input()
if user_input == "":
self.clear_board(board_state)
t = self.clean_board(board_state)
game.build_board(t,game_window)
else:
game.build_board(board_state,game_window)
self.game_over()
else:
game.build_board(board_state,game_window)
return t
def vertical(self, board_state: list) -> bool:
'''This function is the first step of the check board function. It take in the current board and checks if there
is any three or more in a row vertically and put stars around the indicated region and then returns whether the board was motified'''
copy_board_state = copy.deepcopy(board_state)
for rows_index in range(len(board_state)):
if rows_index == 0:
pass
elif rows_index < len(board_state) - 1:
previous_row = board_state[rows_index - 1]
current_row = board_state[rows_index]
future_row = board_state[rows_index + 1]
for index in range(len(current_row)):
if current_row[index] != " " and current_row[index] != '*' and current_row[index] != '|':
if previous_row[index] == current_row[index] and current_row[index] == future_row[index]:
previous_row[index + 1] = "*"
previous_row[index] ="L"
current_row[index + 1] = "*"
current_fow[index] = "L"
future_row[index + 1] = "*"
future_row[index] = "L"
previous_row[index - 1] = "*"
current_row[index - 1] = "*"
future_row[index - 1] = "*"
elif rows_index == (len(board_state) - 1):
previous_row2 = board_state[rows_index - 2]
previous_row = board_state[rows_index - 1]
current_row = board_state[rows_index]
for index in range(len(current_row)):
if current_row[index] != " " and current_row[index] != '*' and current_row[index] != '|':
if previous_row[index] == current_row[index] and current_row[index] == previous_row2[index]:
previous_row[index + 1] = "*"
current_row[index + 1] = "*"
previous_row2[index + 1] = "*"
previous_row[index - 1] = "*"
current_row[index - 1] = "*"
previous_row2[index - 1] = "*"
previous_row[index] = "L"
current_fow[index] = "L"
future_row[index] = "L"
return board_state == copy_board_state
def horizontal(self, board_state: list) -> bool:
'''This function is the second step of the check board function. It take in the current board and checks if there
is any three or more in a row horizantally and put stars around the indicated region and then returns whether the board was motified'''
copy_board_state = copy.deepcopy(board_state)
for rows_index in range(len(board_state)):
current_row = board_state[rows_index]
for index in range(len(current_row)):
if current_row[index] != " " and current_row[index] != '*' and current_row[
index] != '|' and index != 2 and index != (len(current_row) - 3):
if current_row[index] == current_row[index - 3] and current_row[index] == current_row[index + 3]:
current_row[index + 2] = "*"
current_row[index] = "L"
current_row[index + 1] = "*"
current_row[index + 4] = "*"
current_row[index - 3] = "L"
current_row[index - 2] = "*"
current_row[index - 1] = "*"
current_row[index + 3] = "L"
current_row[index - 4] = "*"
return board_state == copy_board_state
def diagonal(self, board_state: list) -> bool:
'''This function is the last step of the check board function. It take in the current board and checks if there
is any three or more in a row diagonally in both directions and put stars around the indicated region
and then returns whether the board was motified'''
copy_board_state = copy.deepcopy(board_state)
for rows_index in range(len(board_state)):
try:
previous_row = board_state[rows_index - 1]
current_row = board_state[rows_index]
future_row = board_state[rows_index + 1]
if rows_index == 0:
pass
elif rows_index < len(board_state) - 1:
previous_row = board_state[rows_index - 1]
current_row = board_state[rows_index]
future_row = board_state[rows_index + 1]
for index in range(len(current_row)):
if current_row[index] != " " and current_row[index] != '*' and current_row[
index] != '|' and index != 2 and index != (len(current_row) - 3):
if current_row[index] == previous_row[index - 3] and current_row[index] == future_row[
index + 3]:
previous_row[index - 3 + 1] = "*"
previous_row[index - 3] ="L"
current_row[index + 1] = "*"
future_row[index + 1 + 3] = "*"
future_row[index + 3] ="L"
previous_row[index - 3 - 1] = "*"
current_row[index - 1] = "*"
current_row[index] = "L"
future_row[index - 1 + 3] = "*"
elif current_row[index] == future_row[index - 3] and current_row[index] == previous_row[
index + 3]:
future_row[index + 1 - 3] = "*"
future_row[index - 3] = "L"
current_row[index + 1] = "*"
current[row_index] ="L"
previous_row[index + 1 + 3] = "*"
future_row[index - 1 - 3] = "*"
previous_row[index + 3] ="L"
current_row[index - 1] = "*"
previous_row[index - 1 + 3] = "*"
except IndexError:
pass
return board_state == copy_board_state
def clear_board(self, board_state: list) -> None:
'''This function is called on if the current board was modified and turns all colors indicated with stars to blank spaces'''
for rows_index in range(len(board_state)):
current_row = board_state[rows_index]
for item in range(int(((len(current_row)) - 2) / 3)):
item = (((item + 1) * 3) - 1)
if current_row[item - 1] == '*' and current_row[item + 1] == '*':
current_row[item - 1] = ' '
current_row[item + 1] = ' '
current_row[item] = ' '
def clean_board(self, board_state: list) -> list:
'''This function is called to make the floating colors drop to the bottom so there are no blank spaces and then returns the current board'''
built_row = []
temp_lst = []
column_lst = []
final_lst = []
len_row = board_state[0]
for i in range(len(len_row)):
for rows in board_state:
built_row.append(rows[i])
temp_lst.append(built_row)
built_row = []
for content in temp_lst:
for x in range(len(content)):
if content[x] == " ":
content.pop(x)
content.insert(0, " ")
column_lst.append(content)
len_col = column_lst[0]
for i in range(len(len_col)):
for column in column_lst:
built_row.append(column[i])
final_lst.append(built_row)
built_row = []
return final_lst
def game_over(self) -> None:
'''This function is called on whenever the games rule is broken resulting in a Game Over'''
print("GAME OVER")
|
#!/usr/bin/python3
"""
Given a pile of coins of different values,
determine the fewest number of coins needed to meet a given amount `total`.
"""
def makeChange(coins, total):
"""
Return: fewest number of coins needed to meet `total`.
* If total is 0 or less, return 0.
* If total cannot be met by any number of coins you have, return -1.
- Your solution’s runtime will be evaluated in this task.
"""
if total <= 0:
return 0
length = len(coins)
optimized = [0 for _ in range(total + 1)]
for i in range(1, total + 1):
smallest = float("inf")
for j in range(length):
if (coins[j] <= i):
smallest = min(smallest, optimized[i - coins[j]])
optimized[i] = 1 + smallest
if type(optimized[total]) is not int:
return -1
return optimized[total]
|
#! HERANÇA SIMPLES
# Conseguimos reutilizar a class Camera para um tipo espeficico de camera.
# Não é necessario criar novamente toda a classe.
# Implicitamente todas classe tem uma herança de object.
class Camera(object):
def __init__(self, marca, megapixels) -> None:
self.marca = marca
self.megapixels = megapixels
def tirar_foto(self):
print(f'Foto tirada com a camera {self.marca} e resolução {self.megapixels} megapixels.')
#ex1 - camera celular
class Camera_cel(Camera):
def __init__(self, marca, megapixels, quantidade_cameras) -> None: #basicamente utilizar os atributos da classe PAI e add alguns diferentes;
super().__init__(marca, megapixels) #super é uma função indica quais atributos continuam na classe pai.não tendo que repetir métodos anteriormente criados
self.qtd_cameras = quantidade_cameras
def aplicar_filtro(self, filtro):
print(f'Aplicando o filtro {filtro}')
def tirar_foto(self,n_camera):
print(f'\n Foto tirada com a camera {self.marca} \
e resolução {self.megapixels} megapixels, utilizando a camera numero {n_camera}.')
# Facilmente temos acesso aos metodos e atributos da Classe PAI; > pass
# camera_cel = Camera_cel('Apple','1800')
# print(camera_cel.marca)
#* 01 - Buscando atributos e metodos:
cam_cel = Camera_cel('Sony','25mp',4)
""" print(cam_cel.marca + '\n' + str(cam_cel.qtd_cameras))
cam_cel.aplicar_filtro('B&W')
"""
#* 02 - Modificar o metodo tirar_foto do PAI:
# criei o mesmo metodo tirar foto, porem coloquei mais um argumento Obrigatorio.
cam_cel.tirar_foto(33)
#! Verificar HERANÇA - se uma classe é filho ou não
print(issubclass(Camera_cel,Camera)) |
'''
Metodos acessos a Campos - o objetivo principal de usar getters e setters em
programas orientados a objetos é garantir o encapsulamento de dados.
Adicionar lógica de validação em torno de obter e definir um valor.
'''
class Teste():
def __init__(self,valor):
self.valor = valor
def get_valor(self):
return self.valor
def set_valor(self,v):
self.valor = v
obj = Teste(15)
#print('\nO valor de input é:', obj.get_valor()) #jeito 1
#print('O valor de input é:', obj.valor) #jeito 2
obj.set_valor(22)
#print('\nO valor de input é:', obj.get_valor())
## ---- Otavio Miranda ----##
class Produto():
def __init__(self, nome, preco):
self.n = nome
self.p = preco
def desconto(self,valor):
self.p = self.p - (self.p*(valor/100))
#--Preco
#Getter #Getter vai pegar esse valor, e depois vamos settar ele abaixo.
@property #@property é um dos decoradores embutidos.
def p(self): #realizo um metodo pro atributo p (preco)
return self._p #diferenciar p e _p para evitar cair no loop
@p.setter #aqui é setado o valor de p
def p(self,valor):
if isinstance(valor,str): #verificar o tipo do input recebido
valor = float(valor.replace('R$',''))
self._p = valor #vantagem que não mexe na estrutura main, so add mais codigo.
#--Nome
@property
def n(self):
return self._n
@n.setter
def n(self,valor):
self._n = valor.title()
p1 = Produto('camiseta','R$50')
p1.desconto(10)
print('\n',p1.n.capitalize(),' -- R$:',p1.p)
p2 = Produto('CANECA','30')
p2.desconto(50)
print('\n',p2.n.capitalize(),' -- R$:',p2.p)
#SET E GET - Caso alguem coloque o preço como str R$15
#p2 = Produto('caneca','R$15')
print(n.valor)
|
# Exercício Python #094 - Unindo dicionários e listas
#a) qtde pessoas b) media de idade c) as mulheres cadastradas d)Lista de pessoas acima da media de idade
galera = list()
pessoa = dict()
soma = media = 0
while True:
pessoa.clear()
pessoa['nome'] = str(input('\nNome: ')).upper()
pessoa['idade'] = int(input('\nIdade: '))
soma += pessoa['idade']
#campo Sexo
while True:
pessoa['sexo'] = str(input('\nSexo [M/F]: ')).upper()[0]
if pessoa['sexo'] in "MF":
break
else:
print('\n-=-=-= ERR0 -=-=-= Escreva M ou F')
#add ao dicionario
galera.append(pessoa.copy()) # a lista recebe uma copia do dicionario
stop = str(input('\nDeseja continuar [S/N]: ')).upper()[0]
if stop == 'N':
break
#print(f'\n{galera}',sep='\n')
print('\n{:-^40}'.format('Respostas')) #fluff
print(f'\na) A quantidade de registros são {len(galera)}.')
media = soma/len(galera)
print(f'\nb) A média das idades é {media:.2f}.') # cinco casas ao todo e duas decimais
print('\nc) As mulheres cadastradas foram', end='')
# logica c) e d)
for p in galera:
if p['sexo'] == 'F':
a = p["nome"]
print(f' {a}', end=',')
print(f'\nd) As pessoas que estão com idade acima da média {media} são ')
for d in galera:
if d['idade'] > media:
b = d['nome']
print(f'{b}', end = ',')
for k,v in d.items():
print(f'\n{k} : {v}', end='')
print()
print(f':-^40.format('Encerrado') |
#! Utilizando TRY CATCH - TRATAMENTO de ERROS
""" try:
meses = [1,2,3,4,5,6,7,8,9,10,11,12]
print(meses[14])
except IndexError as erro:
print('\nDigite um valor válido !')
print(erro) #conseguimos verificar o erro
"""
#! 02 - Caso precise tomar ação. FINALLY SEMPRE IRA RODAR
# Não ira printar pois internet precisa ser str
""" internet = None
try:
print("Conectando a " + internet)
except TypeError as erro:
print("Não foi possível conectar.")
else: #Retorna caso nenhuma erro apareça
print('Tudo OK')
finally: #Sempre retorna
print("Desfazendo a compra")
"""
#! 03 - CLASS EXCEPTION - acessando as variaveis do erro
""" internet = None
try:
print("Conectando a " + internet)
except Exception as erro:
print ('Ocorreu um erro de : {}'.format(erro.__class__))
print ('Ocorreu um erro de : {}'.format(erro.args))
"""
#! 03 - Utilizando LOGGING para registro.
import logging
'''Níveis de logging (gravidade):
debug | info | warning | error | critical
Por padrão somente log de warning acima é exibido.
Podemos alterar isso no config.
'''
#Setar o nível de exibição, e criar o arquivo para guardar o log.
logging.basicConfig(
level=logging.DEBUG,
filename='app.log',
filemode='a',
datefmt='%Y-%m-%d %H:%M:%S',
format='%(asctime)s - %(levelname)s- %(message)s') #format é o modelo que queremos de log, são palavras reservadas;
x = 2 #somente irá guardar o log quando acessar as funções
try:
logging.debug('logging no nivel')
logging.info('logging no nivel \n')
print(10/x)
except:
logging.warning('logging no nivel')
logging.error('logging no nivel \n')
finally:
logging.critical('logging no nivel') |
# -=-=-=-=- Sistema de login em Python -=-=-=-=-
from os import system
from colorama import init, Fore, Back, Style
from getpass import getpass
from time import sleep
init(autoreset= True)
#criar a o menu de opções
def exibir_menu():
print(Fore.GREEN + ''' Bem Vindos ao projeto
Sistema de Login
Escolha um opção:
[1] Cadastrar novo usuario
[2] Fazer Login
[3] Sair
''')
opcao = int(input('\nDigite a sua opção: '))
return(opcao)
def fazer_login():
login = str(input('\nNome : '))
senha = str(input('\nSenha: \n'))
return(login,senha)
def buscar_usuario(login, senha): #necessario para login 1
usuarios = []
with open('users_sistema.txt', r+, encoding='Utf-8',newline='') as arquivo:
for linha in arquivo:
linha = linha.strip(',')
usuarios.append(linha.split())
for usuario in usuarios:
nome = usuario[0]
#Cadastrar novo usuario
login,senha = fazer_login() #recebo duas variaveis
if login == senha:
print(Fore.RED+ "Usuario já existente")
user = buscar_usuario(login,senha)
if user == True:
print()
a = exibir_menu()
print(a)
b = fazer_login()
print(b)
#while True:
# system('cls')
# opcao = exibir_menu
|
#! HERANÇA MULTINIVEL
#evitar vários niveis, cada filho adicionado mais complexidade.
#! HERANÇA MULTIPLA
#irá herdar de duas classes
class Pessoa:
nome = 'Sou uma pessoa.'
def convidar():
print('Ola sou uma pessoa, vamos sair ?')
class Profissional:
nome = 'Sou um profissional.'
def convidar():
print('Ola sou um profissional, vamos sair ?')
class AtorProf (Pessoa,Profissional):
pass
#Qual classe será considerada para nome ???
# print(AtorProf.nome)
# MRO mostra a ordem das classes > [<class '__main__.AtorProf'>, <class '__main__.Pessoa'>, <class '__main__.Profissional'>, <class 'object'>]
# print(AtorProf.mro())
#*------------
#! MAGIC DUNDER METHODS (__init__) > dunder ou duble underscore;
#são métodos predefinidos em todos os objetos, com invocação automática sob circunstâncias especiais.
""" x,y = 32 ,44
print(x.__add__(y))
w = [3,55,20]
print(w.__len__())
"""
class Pessoa:
def __init__(self) -> None:
self.nome = 'Humano'
self.habilidades = ['hab1','hab2','hab3']
#repr - mais técnica e em geral usando uma expressão completa que pode ser usada para reconstruir o objeto
def __repr__(self) -> str:
return 'Classe com Nome e Habilidades'
#len - tamanho de algum atributo
def __len__(self):
return len(self.habilidades)
#str - retorna uma string com dados sobre o objeto. Ajuda no Debug.
def __str__(self) -> str:
return (f'{self.nome} com as habilidades {self.habilidades} .')
pessoa = Pessoa()
print(pessoa.nome)
print(repr(pessoa))
print(len(pessoa))
print(pessoa)
print(dir(pessoa)) |
#Emprestimo bancário - Pergunte o valor da casa, o salario do comprador e a qts anos.
#A prestação não pode passar 30% do salario
valor_casa = float(input('\n Qual o valor da casa?\n'))
salario = float(input('\n Qual o valor do seu salario ? \n'))
anos = int(input('\n Em quantos anos será o emprestimo ?\n'))
parcela = valor_casa/(anos*12)
minimo = salario * 30/100
print('\nPara pagar uma casa de R${:.2f} em {} anos'.format(valor_casa, anos))
print(', a prestação será de R${:.2f}\n'.format(parcela))
if parcela <= minimo:
print('\n Emprestimo CONCEDIDO')
else:
print('\n Emprestimo NEGADO')
|
# SQL - Structured Query Language
#db.sqlite3
import sqlite3
#criar conexão no banco de dados
with sqlite3.connect('artistas.db') as conexao:
sql = conexao.cursor()
#Check se a tabela existe no banco. fetchall cria uma lista com todas as tabelas.
listofTables = sql.execute(
''' SELECT name FROM sqlite_master
WHERE type = 'table'
ORDER BY NAME;
'''
).fetchall()
if listofTables == []:
#rodar comando SQL
sql.execute('CREATE TABLE banda (nome text, estilo text, membros integer);')
#inserir dados
sql.execute('INSERT INTO banda(nome, estilo, membros) values ("Banda 1","Rock",3);')
#usar dados da aplicação em SQL
nome = input("Nome da banda: ")
estilo = input("Estilo: ")
qtd_integrantes = int(input("Quantidade de integrantes: "))
sql.execute('''INSERT INTO banda values (?,?,?)''',\
[nome, estilo, qtd_integrantes])
#salvar alterações no banco
conexao.commit()
bandas = sql.execute("SELECT * FROM banda;")
for banda in bandas:
print(banda)
|
print("Este programa calcula la distancia entre dos puntos en un plano bidimencional ")
print("Por favor inserte las cordenadas del primer punto")
x1 = int(input("x1: "))
y1 = int(input("y1: "))
print("Ahora inserte las cordenadas del segundo punto")
x2 = int(input("x2: "))
y2 = int(input("y2: "))
distance = ((x2 - x1)**2) + ((y2 - y1)**2)
print("La magnitud de la distancia entre los puntos es de: ", distance, "unidades")
|
import random
def game(n1, n2):
lim1 = n1
lim2 = n2
answer = bool()
while answer == False:
number = random.randint(lim1,lim2)
print("The number I'm thinking is: ", number)
feedback = input("The number you're thinking is: ")
feedback = feedback.lower()
try:
if feedback == "equal":
print("Thanks for playing with me")
answer = True
else:
if feedback == "higher":
lim1 = number
elif feedback == "lower":
lim2 = number
except ValueError:
print("That is not a word, try it again")
print("Lets play a game")
print("You're going to think a number between two limits and I will guess it")
print("First you have to stipulate those limits")
print("After I generate the number you have to say if the number you're")
print("thinking is: higher, lower or equal")
while True:
a = input("Limit 1: ")
b = input("Limit 2: ")
try:
a = int(a)
b = int(b)
game(a,b)
break
except ValueError:
print("One of the limits is not an integer, please insert them again")
|
print(" Escriba un numero de pies\n")
unit_foots = int(input("ft: "))
yards = unit_foots/3
inches = unit_foots*12
cm = inches*2.54
meters = cm/100
print("Su numero de pies equivale a: \n", yards,"Yardas, ",inches, "pulgadas, ", cm, "Centimetros, ", meters, "metros " ) |
#program that prints out a double half-pyramid
#of a specified height, per the below.
def main():
nline = 1
while True:
height = int(input("Height: "))
if height > 0 and height < 23:
break
for i in range (height):
print(" " * (height - nline),
'#' * nline,'', '#' * nline)
nline = nline + 1
if __name__ == "__main__":
main() |
# This script demonstrates how to create directories
import os
# This function creates [number] directories under root
def mkdir( root, number ):
for i in range(0, number):
dirname = root + "/" + str(i)
os.mkdir( dirname )
def main():
root = "/Users/liuyuan/temp/foo/"
os.mkdir( root )
mkdir( root, 5 )
main()
|
"""GIVEN three positive integers representing three representatives
of a population who are, respectively, dominant homozygous, heterozygous and
recessive homozygous for an allele RETURN the probability that two randomly
selected individuals mating will produce offspring that have(and manifest) the
dominant allele"""
def probability(k, m, n):
pt = k+m+n
pt1 = pt - 1.0
p1 = k/pt*(k-1.0)/pt1*1.0
p2 = k/pt*m/pt1*1.0
p3 = k/pt*n/pt1*1.0
p4 = m/pt*(m-1.0)/pt1*0.75
p5 = m/pt*k/pt1*1.0
p6 = m/pt*n/pt1*0.5
p7 = n/pt*(n-1.0)/pt1*0
p8 = n/pt*m/pt1*0.5
p9 = n/pt*k/pt1*1.0
probtot = p1+p2+p3+p4+p5+p6+p7+p8+p9
return probtot
k1
m1
n1
print probability(k1,m1,n1)
|
import os
import sys
def removeEmptyDirectories(curPath):
dir_list = os.listdir(curPath)
if dir_list:
for i in dir_list:
dir = os.path.join(curPath, i)
if os.path.isdir(dir):
removeEmptyDirectories(dir)
if not os.listdir(curPath):
os.rmdir(curPath)
else:
os.rmdir(curPath)
try:
if os.path.exists(sys.argv[1]):
removeEmptyDirectories(sys.argv[1])
print("Success!")
else:
raise NameError("The directory does not exist!")
except NameError as e:
print(e)
except Exception as e:
print(e)
|
class Room:
def __init__(self, name, desc):
self.name = name
self.desc = desc
self.n_to = None
self.s_to = None
self.e_to = None
self.w_to = None
self.items = []
self.hidden_items = None
self.hidden_rooms = None
self.is_dark = False
self.is_locked = False
def add_item(self, item, player):
self.items.append(item)
player.remove_from_inventory(item)
def remove_item(self, item, player):
if self.is_dark:
print("Unable to do anything as you can't see.")
return
self.items.remove(item)
player.add_to_inventory(item)
def view_items(self):
if self.is_dark:
print("Room is too dark - you can't see!")
return
if len(self.items) > 0:
for item in self.items:
print(item.name)
else:
print("Room is too dark to do anything.") |
'''
Initialize your list and read in the value of followed by lines of commands where each command
will be of the types listed above. Iterate through each command in order and perform the
corresponding operation on your list.
Example:
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
'''
arr = []
commands = {
'insert': lambda a: arr.insert(a[0], a[1]),
'remove': lambda x: arr.remove(x[0]),
'append': lambda x: arr.append(x[0]),
'print': lambda _: print(arr),
'sort': lambda _: arr.sort(),
'pop': lambda _: arr.pop(),
'reverse': lambda _: arr.reverse(),
}
if __name__ == '__main__':
#print("Awaiting input: ")
N = int(input())
for _ in range(N):
cmd, *params = input().strip().split()
params = list(map(int, params))
if len(params) > 0:
commands[cmd](params)
else:
commands[cmd](_)
|
""" Find the number closest to 0
Simpler solution to the "Temperature closest to zero problem"
Sample inputs:
-40 -5 -4 -2 2 4 5 11 12 18
7 -10 13 8 4 -7.2 -12 1 -3.7 3.5 -9.6 6.5 -1.7 -6.2 7
-273
"""
import sys
try:
print("Enter the list of numbers: ")
temps = list(map(float, input().split()))
n = len(temps)
if n == 0:
print(0)
elif n == 1:
print(temps[0])
else:
temps.sort()
print(f"Sorted {n} items: ", temps, file=sys.stderr, flush=True)
positive_temps = list(map(abs, temps))
hit = min(positive_temps)
print("Closest hit: ", hit if hit in temps else -hit)
except Exception as e:
print("Processing failed: ", e)
|
from Entity import Entity
import sys, os
clear = lambda: os.system('cls')
playerName = input("What is your name?: ")
Player = Entity(playerName)
Opponent = Entity()
PlayerControl = 1
battling = True
while(Player.health > 0 and Opponent.health > 0 and battling == True):
#Clear screen
clear()
#Print stats
CharCount = len(Player.name+str(Player.health)+Opponent.name+str(Opponent.health))+7
print('-' * CharCount)
print("| %s:%d %s:%d |" % (Player.name, Player.health, Opponent.name, Opponent.health))
print('-' * CharCount)
if PlayerControl == 1:
#attack or defend?
command = input("Attack/Defend/Info/Exit/Restart: ")
if command == "Attack":
Player.attack_creature(Opponent)
PlayerControl = 0
elif command == "Defend":
#set defense
Player.defend()
PlayerControl = 0
elif command == "Info":
CharCount = len(Player.name+Opponent.name)+7
print('-' * CharCount)
print("| %s | %s |" % (Player.name, Opponent.name))
print("| HP:%d | HP:%d |" % (Player.health, Opponent.health))
print("| AT:%d | AT:%d |" % (Player.attack, Opponent.attack))
print("| DE:%d | DE:%d |" % (Player.defense, Opponent.defense))
print("| DA:%s | DA:%s |" % (Player.defenseAdvantage, Opponent.defenseAdvantage))
print('-' * CharCount)
elif command == "Exit":
sys.exit(0)
elif command == "Restart":
battling = False
break
else:
print("That command doesn't exist, please try again.\n")
input("Press Enter to continue...")
#Clear screen
clear()
else:
Opponent.attack_creature(Player)
PlayerControl = 1
input("Press Enter to continue...")
#Clear screen
clear()
if battling == False:
print("Restarting game...")
elif Player.health <= 0:
print("%s has died. Farewell brave soul." % (Player.name))
else:
print("%s was slain. Huzzah!" % (Opponent.name)) |
#!python3
import os,shutil
#to append a zip file newzip = zipfile.zipfile('new.zip','a')
alpha_string='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
currentpath = 'C:\\Users\\Starkey\\Desktop'
for folderN, subfolder, filename in os.walk('C:\\Users\\Starkey\\Desktop\\folder1'):
#for i in str(filename).strip('[\']'):
if '.txt' in str(filename).strip('[\']'):
temp = os.path.dirname(filename)
currentpath = os.path.join(currentpath, temp)
print(currentpath)
#def copyfun():
|
'''
Created on Dec 31, 2017
@author: jghuf
'''
import time
# if number is divisible by 20 than it also is divisible by 2 etc,
divList = [11, 13, 14, 16, 17, 18, 19, 20]
def number(limit):
for num in range(limit,999999999,limit):
if all((num % i == 0) for i in divList):
return num
if __name__ == '__main__':
limit = 20
start = time.time()
smallestMultiple = number(limit)
elapsed = (time.time() - start)
print("The smallest multiple is %s , found in %s seconds" % (smallestMultiple,elapsed))
|
#file Exercise.py
class Exercise():
_registery = []
def __init__(self, name, time):
self._registery.append(self)
try:
if len(name) <= 1:
raise ValueError('Invalid name')
else:
self.name = name
except ValueError:
print("Invalid name")
self.name = None
try:
self.time = int(time)
except:
self.time = None
def display(self):
print("Name of exercise: ", self.name)
print("Time of exercise in minutes: ", self.time)
return(0) |
import time
# Using time.sleep in a forloop does not guarantee exactly 1 sec.
t = time.time()
for i in range(100):
print("delta t:", time.time()-t)
t = time.time()
time.sleep(1)
"""
# This results in a cumulative error
zero_time = time.time()
for i in range(100):
time.sleep(1)
print("delta t:", time.time()-zero_time)
"""
|
# hello world in a for loop
import time
for i in range(1,6):
print(i, "hello")
time.sleep(1)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.