text
stringlengths 37
1.41M
|
---|
palavra = str(input("Digite uma palavra:\n"))
while palavra.isalpha() is False:
print("\nPor favor, digite apenas letras!\n".upper())
palavra =str(input("Digite uma palavra:\n"))
else:
print("\nMuito bem, você digitou apenas letras!")
|
from random import randint
quantidade = int(input("Digite qual a quantidade de termos da sua lista!"))
lista_gerada = []
def bubble_sort(lista_parametro):
"""
Método de ordenação bubble sort que consiste em comparar dois valores subsequentes de uma lista
e trocá_los de lugar caso o valor de i+1 seja maior que o valor de i.
A função executará essas comparações quantas vezes forem necessárias, até que nenhuma troca seja feita.
"""
mudou = True
while mudou is True:
mudou = False
for i in range (len(lista_parametro)-1):
if lista_parametro[i] > lista_parametro[i+1]:
lista_parametro[i], lista_parametro[i+1] = lista_parametro[i+1], lista_parametro[i]
mudou = True
return lista_parametro
for i in range (quantidade):
sair = True
termo = randint(0, 1000)
while sair:
if termo in lista_gerada:
continue
else:
lista_gerada.append(termo)
sair = False
print(lista_gerada)
print(bubble_sort(lista_gerada))
|
def maximum(n):
l=len(n)
for i in range(l-1):
for j in range(i+1,l):
if n[i]>n[j]:
max=n[i]
else:
max=n[j]
print("the largest number is " + str(max))
limit = int(input("Enter the size of the list "))
n = list(int(num) for num in input("Enter the list items separated by space ").strip().split())[:limit]
maximum(n)
|
"""
It is possible to return the value in the form of HTML.
Flask will try to find the HTML file in the 'templates' folder;
The 'templates' folder should go with this python script in the same folder;
by using render_template(), the Jinga2 template engine will turn the initial HTML into the final HTML;
"""
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/hello/')
def hello_world():
return '<html><body><h1>Hello World</h1></body></html>'
@app.route('/hello/<user>/')
def hello_name(user):
# the parameter 'param1' corresponds to {{ param1 }} in hello(tutorial6).html;
return render_template('hello(tutorial6).html', param1=user)
if __name__ == '__main__':
app.run(debug=True)
|
# Задача-2: Исходные значения двух переменных запросить у пользователя.
# Поменять значения переменных местами. Вывести новые значения на экран.
# Решите задачу, используя только две переменные.
# Подсказки:
# * постарайтесь сделать решение через действия над числами;
# * при желании и понимании воспользуйтесь синтаксисом кортежей Python.
a = int(input('Введите 1ое число: '))
b = int(input('Введите 2ое число: '))
s = a + b
print(f'a={s-a}, b={s-b}')
|
# Задание-2:
# Дан шестизначный номер билета. Определить, является ли билет счастливым.
# Решение реализовать в виде функции.
# Билет считается счастливым, если сумма его первых и последних цифр равны.
# !!!P.S.: функция не должна НИЧЕГО print'ить
def lucky_ticket(ticket_number):
lst_tn = list(str(ticket_number))
return sum(map(int, lst_tn[:3])) == sum(map(int, lst_tn[3:6]))
print(lucky_ticket(123006))
print(lucky_ticket(123321))
print(lucky_ticket(436751))
|
# Задача-1:
# Дан список фруктов.
# Напишите программу, выводящую фрукты в виде нумерованного списка,
# выровненного по правой стороне.
fruits = ['апельсин', 'яблоко', 'груша', 'манго']
for i, fruit in enumerate(fruits):
print(f'{i+1}. - {fruit:>10}')
|
import networkx
import matplotlib.pyplot as plot
import random
import math
"""This module is a graph-based social network model using networkx with a dictionaries of dictionaries
implementation. Please make sure to install the following dependencies before running:
- networkx: pip3 install networkx
- matplotlib: pip3 install matplotlib
- tkinter: apt install pyton3-tk or equivalent for non-debian linux or mac
- scipy: pip3 install scipy
The code is uses Python 3 features.
"""
class SocialNetwork:
"""This class models a social network of connected people. This is a graph-based model with each
node representing a person and each edge representing a connection between two people. The default
instance of this class uses a simple small network of people with random connections. The constructor
provides for the ability to specify the people and the connections in two separate lists or sets. A
third argument "gov" is provided in the case that no connections are provided and simple designates one
of two algorithms for creating connections between people in the network. The two possible values
are "random" which creates random connections, this is to be used whenever you want to provide only a
list of people and still create a meaningful social network, the other option is "full" which exists
only for graph testing purposes and shouldn't be used. If a connections list is provided, a gov argument
has no effect"""
__test_people = ["Ahmed", "Mohamed", "Mahmoud", "Moaz", "Amr", "Omar", "Mai", "Hoda"]
def __init__(self, people=__test_people, connections=None, gov=None):
self.people = people
self.connections = []
self.graph = networkx.MultiGraph()
self.plot = plot
# the default connection creation between people is random. They're also a full connection
# implementation that connects all nodes to all other nodes. It's there but not useful for this model
if connections is None:
if gov is None:
self.create_connections_random()
elif gov == "random":
self.create_connections_random()
elif gov == "full":
self.create_connections_full()
else:
self.connections = connections
# create the graph with nodes and connections
self.populate_graph()
def create_connections_full(self):
"""Create a list of connections that connect all nodes to all other nodes in the network,
not useful for our needs and don't use it for purposes of testing this model as it creates
a meaningless social network.
Note: This function should not be called from outside but for testing
purposes external invocation is allowed"""
# This little devilish loop here creates lots of connections
for i in self.people:
for j in self.people:
# self connections are actually handled by networkx by I want a clean connection list
if i is j:
continue
self.connections.append((i, j))
def create_connections_random(self):
"""Create a list of connections that randomly connect nodes to other nodes in the network,
this is the recommended way of creating a meaningful network for our model.
Note: This function should not be called from outside but for testing
purposes external invocation is allowed"""
for i in self.people:
for j in self.people:
# self connections are actually handled by networkx by I want a clean connection list
if i is j:
continue
# this creates connections at a random boolean-like decision
m = random.randint(0, 1)
if m == 0:
continue
else:
self.connections.append((i, j))
# this loop only executes one for each person to create less and easier connections
break
def populate_graph(self):
"""Populate the graph object with the nodes and the edges.
Note: This function should not be called from outside but for testing
purposes external invocation is allowed"""
# add the nodes to the graph
self.graph.add_nodes_from(self.people)
# add the edges to the graph
self.graph.add_edges_from(self.connections)
def draw_graph(self):
"""Create the plot of the network graph.
Note: this function doesn't display the plot, to do that call show_graph() afterwards"""
# this is the matplotlib plot object, this subplot full height and left-most occupying
self.plot.subplot(121)
# draw the network graph on the subplot
networkx.draw_networkx(self.graph, with_labels=True, font_weight='bold')
def draw_graph_shell(self):
"""Create the plot of the network graph shell.
Note: this function doesn't display the plot, to do that call show_graph() afterwards"""
# this is the matplotlib plot object, this subplot full height and right-most occupying
self.plot.subplot(122)
# draw the shell of network graph on the subplot for an easier outside-in view
networkx.draw_shell(self.graph, with_labels=True, font_weight='bold')
def show_graph(self):
"""Show the drawn plots for this network"""
self.plot.show()
def get_adjacency_with_separation_degree(self, degree):
"""Get a list of all nodes in the network and for each node a set of nodes that are exactly
degree degrees of separation away from the node"""
# store the adjacency list
adjacency = {}
# iterate over the iterable for all shortest path lengths in the graph
# each i is a dictionary containing with the person's name and a dictionary
# of degrees of separation from each other node in the network
for i in networkx.all_pairs_shortest_path_length(self.graph):
# holder for the set of people that are exactly degree degrees away from the current node
temp = set()
# a dictionary to hold the separation dictionary in i
dic = dict(i[1])
# iterate over the separation dictionary for the current node
for j in dic:
# if the current node of the separation dictionary is exactly degree degrees of separation
# add it to the current set of nodes
if dic.get(j) == degree:
temp.add(j)
# after iterating over all separations add the person and the set of people that are exactly
# degree degrees away from that person
adjacency.update({i[0]: temp})
# return the adjacency dictionary
return adjacency
def get_friends(self):
"""Friends of a node are the people who are exactly 1 degree of separation away.
Note: this notation is not consistent with social theory degree of separation,
it is consistent with graph theory degree of separation that uses edges"""
return self.get_adjacency_with_separation_degree(1)
def get_friends_of_friends(self):
"""Friends of friends of a node are the people who are exactly 2 degrees of separation away.
Note: this notation is not consistent with social theory degree of separation,
it is consistent with graph theory degree of separation that uses edges"""
return self.get_adjacency_with_separation_degree(2)
def get_most_popular(self):
"""Get a set of all the most popular people in the network, the node(s) with the highest connectivity"""
# a unique set of popular people
populars = set({})
# a placeholder for a comparable object representing a person
person = None
for i in self.graph.degree:
# this is for the first iteration to cast person from None to a comparable object type
if person is None:
person = i
continue
# if the current person object's connectivity level (how many people they're connected to)
# is higher than the place holder, replace the placeholder with the current person
if i[1] > person[1]:
person = i
# add the most popular person to the set of most popular people
populars.add(person[0])
# this loops adds other people who are equally popular to the most popular person
for i in self.graph.degree:
# if the current person object's connectivity level is equal than the place holder,
# this person is as popular to the most popular person and add them to the set
if i[1] == person[1]:
populars.add(i[0])
# return the set of most popular people
return populars
def get_least_popular(self):
"""Get a set of the least popular people in the network, the node(s) with the least connectivity.
Note: Certain variable names contained in this method may trigger people who were triggered by
certain historic python terminology. Please open a PEP if you wish to rectify this issue."""
# placeholder for a unique set of least popular people
unpopulars = set({})
# placeholder for a comparable person object
person = None
for i in self.graph.degree:
if person is None:
person = i
continue
if i[1] < person[1]:
person = i
unpopulars.add(person[0])
for i in self.graph.degree:
if i[1] == person[1]:
unpopulars.add(i[0])
return unpopulars
def get_average(self, gov=None):
"""Get the average level of connectivity in the network.
Note: averages are floating points but to be meaningful this function returns an integer,
for this reason you may specify a governor for rounding. Possible governors are "ceiling", "floor",
"cast" which uses python's int() casting for rounding, or unspecified which returns floating point"""
# the summation of all degrees and the count of nodes
summation, count = 0, 0
# iterate over the degrees of connectivity of all nodes in the network
for i in self.graph.degree:
# increase the number of nodes
count += 1
# sum the values of node degrees
summation += i[1]
# do rounding according to the governor argument
if gov == "floor":
return math.floor(summation/count)
elif gov == "ceiling":
return math.ceil(summation/count)
elif gov == "cast":
return int(summation/count)
else:
return summation/count
def get_more_than_four(self):
"""Get a set of people who have four or more friends in the network"""
# a unique set of people with more than four friends
populars = set({})
# iterate over the degrees of separation of all nodes in the network
for i in self.graph.degree:
if i[1] > 4:
populars.add(i[0])
if len(populars) == 0:
return "No one has more than four friends"
return populars
# create the social network mode
social_network = SocialNetwork()
# draw the graph for the network
social_network.draw_graph()
# draw the network graph shell
social_network.draw_graph_shell()
# show the graph plots
social_network.show_graph()
# print the friends of everyone in the network
print("Friends:", social_network.get_friends())
# print the friends of friends of everyone in the network
print("Friends of friends:", social_network.get_friends_of_friends())
# print the most popular people in the network
print("Most popular:", social_network.get_most_popular())
# print the least popular people in the network
print("Least popular:", social_network.get_least_popular())
# print the average popularity of people in the network
print("Average popularity:", social_network.get_average())
# print people in the network with more than four friends
print("More than 4 friends:", social_network.get_more_than_four())
|
alien_0 = {'color':'green'}
print(f"The alien is {alien_0['color']}.")
alien_0['color'] = 'yellow'
print(f"The alien is now {alien_0['color']}.")
# country
country_codes = {'Finland': 'fi', 'South Africa': 'za','Nepal': 'np'}
print(country_codes)
print(len(country_codes))
if country_codes:
print('country_codes is not empty')
else:
print('country_codes is empty')
country_codes.clear()
if country_codes:
print('country_codes is not empty')
else:
print('country_codes is empty')
# Iterating through a Dictionary
days_per_month = {'January': 31, 'February': 28, 'March': 31}
print(days_per_month)
for month, days in days_per_month.items():
print(f'{month} has {days} days')
# Using a dictionary to represent an instructor's grade book.
grade_book = {
'Susan': [92, 85, 100],
'Eduardo': [83, 95, 79],
'Azizi': [91, 89, 82],
'Pantipa': [97, 91, 92]
}
all_grades_total = 0
all_grades_count = 0
for name, grades in grade_book.items():
total = sum(grades)
print(f'Average for {name} is {total/len(grades):.2f}')
all_grades_total += total
all_grades_count += len(grades)
print(f"Class's average is: {all_grades_total / all_grades_count:.2f}")
|
#CONDITIONS (15PTS TOTAL)
# PROBLEM 1 (GPA - 4pts)
# Grades are values between 0 and 100
# We will translate grades to letters using:
# http://www.collegeboard.com/html/academicTracker-howtoconvert.html
# Make a variable for your percentage grade.
# Make a series of if/elif/else statements to print the letter grade.
# If the user enters a grade lower than zero or higher than 100, just give an error message.
# Don't worry about making an exception for these right now.
def grade(percent):
if percent >= 97 and percent <= 100:
print("A+")
elif percent >= 93 and percent <= 96:
print("A")
elif percent >= 90 and percent <= 92:
print("A-")
elif percent >= 87 and percent <= 89:
print("B+")
elif percent >= 83 and percent <= 86:
print("B")
elif percent >= 80 and percent <= 82:
print("B-")
elif percent >= 77 and percent <= 79:
print("C+")
elif percent >= 73 and percent <= 76:
print("C")
elif percent >= 70 and percent <= 72:
print("C-")
elif percent >= 67 and percent <= 69:
print("D+")
elif percent >= 65 and percent <= 66:
print("D")
elif percent <= 65 and percent >= 0:
print("F")
else:
print("Error")
grade(int(input("Enter your grade: ")))
print()
# PROBLEM 2 (Vowels - 5pts)
# Ask the user to supply a string.
# Print how many different vowels there are in the string.
# The capital version of a lower case vowel is considered to be the same vowel.
# y is not considered a vowel.
# Try to print proper output (e.g., printing “There are 1 different vowels in the string” is ugly).
# Example: When the user enters the string “It’s Owl Stretching Time,”
# the program should say that there are 3 different vowels in the string
user_input = (str(input("Enter a phrase: "))).lower()
vowels = []
count = 0
for i in ["a", "e", "i", "o", "u"]:
if i in user_input:
vowels.append(i)
if len(vowels) == 1:
print("There is 1 vowel in your phrase.")
else:
print("There are", len(vowels), "different vowels in your phrase.")
print()
# PROBLEM 3 (Quadratic Equation - 6pts)
# You can solve quadratic equations using the quadratic formula.
# Quadratic equations are of the form Ax2 + Bx + C = 0.
# Such equations have zero, one or two solutions.
# The first solution is (−B + sqrt(B^22 − 4AC))/(2A).
# The second solution is (−B − sqrt(B^2 − 4AC))/(2A).
# There are no solutions if the value under the square root is negative.
# There is one solution if the value under the square root is zero.
# Write a program that asks the user for the values of A, B, and C,
# then reports whether there are zero, one, or two solutions,
# then prints those solutions.
# Note: Make sure that you also take into account the case that A is zero,
# and the case that both A and B are zero.
a = float(input("Enter any value for a: "))
b = float(input("Enter any value for b: "))
c = float(input("Enter any value for c: "))
solutions = 0
if a == 0:
print("Undefined")
elif ((b ** 2) - (4 * a * c)) < 0:
print("There are no real solutions")
elif ((b ** 2) - (4 * a * c)) == 0:
print("The solution is: ", -b)
else:
x = (-b -(((b ** 2) - (4 * a * c)))** 0.5)/(2 * a)
y = (-b +(((b ** 2) - (4 * a * c)))** 0.5)/(2 * a)
print("There are 2 solutions,", x, "and", y)
|
#!/usr/bin/python3
for letters in range(97, 123):
if not letters == 101 and not letters == 113:
print("{}".format(chr(letters)), end="")
|
import os
import uu
import sqlite3
import base64
import cv2
import getpass
"""
This script will run in the terminal/shell and works in an interactive manner (input & output)
The 'encodeFiles' function below is used to gather directory & file information, input commands, and
store or recover files/folders in/from a created database by encoding files into binary format.
"""
def encodeFiles(PATH, conn):
# Creating dictionary/hash table to relate file types with file extensions
FILE_TYPES = {
"txt": "TEXT",
"java": "TEXT",
"dart": "TEXT",
"py": "TEXT",
"jpg": "IMAGE",
"png": "IMAGE",
"jpeg": "IMAGE",
"mp4": "VIDEO",
"mp3": "AUDIO",
}
# Splitting off the file name from the directory name
file_name = PATH.split("\\")
file_name = file_name[len(file_name) - 1]
# Creating an empty string to place binary information in
file_string = ""
NAME = file_name.split(".")[0]
EXTENSION = file_name.split(".")[1]
try:
EXTENSION = FILE_TYPES[EXTENSION]
except:
Exception()
# The below conditional statements are comparing the associated file extension that was input from the user
# with the file type from the hash table/dictionary above to determine which block of logic to execute.
if EXTENSION == "IMAGE":
# Using Python library cv2 to encode image information into binary format with base64, a separate Python library.
IMAGE = cv2.imread(PATH)
file_string = base64.b64encode(cv2.imencode('.jpg', IMAGE)[1]).decode().encode("utf-8")
elif EXTENSION == "TEXT":
# Reading the file into memory as a string, then encoding the string into binary with utf-8 formatting.
file_string = open(PATH, "r").read()
file_string = base64.b64encode(file_string.encode("utf-8"))
elif EXTENSION == "VIDEO":
# Using Python library uu to encode video files into utf-8 binary.
uu.encode(PATH, PATH.split(".")[0] + ".txt")
file_string = open(PATH.split(".")[0] + ".txt", "r").read()
file_string = base64.b64encode(file_string.encode("utf-8"))
os.remove(PATH.split(".")[0] + ".txt")
elif EXTENSION == "AUDIO":
# Using Python library uu to encode audio files into utf-8 binary.
uu.encode(PATH, PATH.split(".")[0] + ".txt")
file_string = open(PATH.split(".")[0] + ".txt", "r").read()
file_string = base64.b64encode(file_string.encode("utf-8"))
os.remove(PATH.split(".")[0] + ".txt")
EXTENSION = file_name.split(".")[1]
# Storing the input directory into the database in case the user would like to associate the file to the directory
db_directory = "\\".join(PATH.rsplit('\\')[:-1])
# Creates SQL Command to store relevant data in database.
command = 'INSERT or REPLACE INTO SAFE (FILE_NAME, DIRECTORY, NAME, EXTENSION, FILES) VALUES (%s, %s, %s, %s, %s);' % (
'"' + file_name + '"', '"' + db_directory + '"', '"' + NAME + '"', '"' + EXTENSION + '"',
'"' + str(file_string, "utf-8") + '"')
# Executes & Commits the SQL Command into the conn argument (passed in as a sqlite3 object)
conn.execute(command)
conn.commit()
# Create a secure password that you would like to set before compiling
PASSWORD = "password"
# Creating a name/variable defined as a password entry (without echoing the input)
connect = getpass.getpass(prompt="Please enter your password:\n")
# As long as each password entry is incorrect, the loop below will keep running
while connect != PASSWORD:
# GetPass is a python library that does not echo the input from keystrokes into the terminal
connect = getpass.getpass(prompt="Incorrect password. Please try again:\n")
# Quits the program if the user inputs the 'q' keystroke
if connect == "q":
break
# If the password is correct, a connection is established to a file named mySafe.db
if connect == PASSWORD:
conn = sqlite3.connect('mySafe.db')
# If mySafe.db does not exist, the try/except loop below will create it.
try:
conn.execute('''CREATE TABLE SAFE
(FILE_NAME TEXT PRIMARY KEY NOT NULL,
DIRECTORY TEXT NOT NULL,
NAME TEXT NOT NULL,
EXTENSION TEXT NOT NULL,
FILES TEXT NOT NULL);''')
print("Database created. What would you like to do?")
except:
print("Database found. What would you like to do?")
# Defining a list of commands that can be used in the terminal
while True:
print("\n" + "*" * 15)
print("Commands:")
print("rf = Recover File")
print("rd = Recover Directory")
print("sf = Store File")
print("sd = Store Directory")
print("dr = Delete all Recovered files")
print("df = Delete data base File")
print("da = Delete All data base files")
print("ls = LiSt stored Directories ")
print("q = Quit program")
print("*" * 15)
input_ = input(":")
# If the user accidentally had caps lock on, the .lower() method will force the input into lowercase.
# This is used to make an appropriate conditional assessment
if input_.lower().startswith("q"):
# Exits the program if 'q' is pressed on the keyboard.
break
if input_.lower() == "rf":
# If the 'rf' command is placed, the block below will recover a single file based on the input
# given by the user.
# This is set in the file_type and file_name inputs.
file_type = input("File type? (e.g. txt, jpg, mp3, mp4, py)\n")
file_name = input("File name?\n")
FILE_ = file_name + "." + file_type
# Creates a SQL command to select the file that was requested by the user.
cursor = conn.execute("SELECT * from SAFE WHERE FILE_NAME=" + '"' + FILE_ + '"')
# Loops through the cursor object defined above
# Appends the string found in the 4th column (file information in bytes) into the file_string container
file_string = ""
for row in cursor:
file_string += row[4]
# Performs check to decide whether or not to decode a bytes text file into a video or audio file.
if file_type == "mp4" or file_type == "mp3":
with open(file_name + ".txt", 'wb') as f_output:
f_output.write(base64.b64decode(file_string))
# Decodes the requested audio or video file as the text file in which the byte information
# was initially stored using the 'uu' Python library.
uu.decode(file_name + ".txt", FILE_)
os.remove(file_name + ".txt")
else:
# Creates a file in the current working directory
# and writes the decoded string information from the file_string container defined above.
with open(FILE_, 'wb') as f_output:
f_output.write(base64.b64decode(file_string))
if input_.lower() == "rd":
# Recovers a directory by checking the database for the input placed by the user.
directory = input("Please enter directory path containing previously stored files.\n")
cursor = conn.execute("SELECT * from SAFE WHERE DIRECTORY=" + '"' + directory + '"')
recovered_files = []
# Appends files found in the database with the directory path that was intially stored.
for row in cursor:
# row[1] is the directory and row[0] is the file name.
# The position of the elements in the cursor object were defined in the 'command' sqlite3 object
# which was executed in the encodeFiles function.
recovered_files.append(row[1] + "\\" + row[0])
for file in recovered_files:
# Goes through each file stored in the recovered_files list to decode one-by-one.
# Manipulates the files for easier management
FILE_ = file.split('\\')[-1]
file_type = FILE_.split(".")[-1]
file_name = FILE_.split(".")[0]
# Creates the sqlite3 cursor object which is used to recover the byte information from the 4th index of its array.
cursor = conn.execute("SELECT * from SAFE WHERE FILE_NAME=" + '"' + FILE_ + '"')
file_string = ""
for row in cursor:
file_string += row[4]
if file_type == "mp4" or file_type == "mp3":
with open(file_name + ".txt", 'wb') as f_output:
f_output.write(base64.b64decode(file_string))
# Decodes the requested audio or video file as the text file in which the byte information
# was initially stored using the 'uu' Python library.
uu.decode(file_name + ".txt", FILE_)
os.remove(file_name + ".txt")
else:
# Creates a file in the current working directory
# and writes the decoded string information from the file_string container defined above.
with open(FILE_, 'wb') as f_output:
f_output.write(base64.b64decode(file_string))
# Since this if/else check is repeated in the 'rf' conditional block above, a function can be created for
# ease of readability.
if input_.lower() == "sd":
# Stores all the files found within the directory input into the database.
PATH = input(
"Type in the path to the directory you want to store.\nExample: \\Users\\userName\\Desktop\\myFolder\n")
for root, dirs, files in os.walk(PATH):
for name in files:
# Walks through the directory that was input and creates a PATH name using the directory and file(s)
PATH = os.path.join(root, name)
# Runs the encodeFiles function for each file found in the directory.
encodeFiles(PATH, conn)
if input_.lower() == "sf":
# Stores a single file in the database.
PATH = input(
"Type in the full path to the file you want to store.\nExample: \\Users\\userName\\Desktop\\myFile.py\n")
# Runs the encodeFiles function for the single file that was input in the terminal.
encodeFiles(PATH, conn)
if input_ == "dr":
# Deletes all the recovered files from the current working directory in which this script is executed from.
delete = input(
"\nDelete all files from Recovery Directory? (Y/N)\n"
"(Files will not be deleted from Data Base)\n\n")
if delete.lower().startswith("y"): # In case caps-lock was on
programFiles = ["safe.py", "mySafe.db"] # Ensures the main files (script and database) are not deleted.
for root, dirs, files in os.walk(os.getcwd()):
for name in files:
if name not in programFiles:
# Deletes all files in the directory using the os.remove method.
os.remove(os.path.join(root, name))
if input_ == "df":
# Deletes a single file from the database
PATH = input(
"Type in the file name including the extension of the file you want to delete from the database."
"Note: Case-sensitive"
"\nExample: My_File.txt\n")
PATH = str(PATH)
cursor = conn.cursor()
# Just showing another way in which you can execute a sqlite3 command
deleteFile = "DELETE FROM SAFE WHERE FILE_NAME = " + '"' + PATH + '"'
cursor.execute(deleteFile)
conn.commit()
if input_ == "da":
# Deletes all files from the database
PATH = input("Are you sure you would like to delete all stored files from the database? (Y/N)\n")
if PATH.lower() == "y": # Perform double-check to confirm deletion of all files.
cursor = conn.cursor()
# sqlite3 string command to delete all files from database
deleteFile = "DELETE FROM SAFE"
cursor.execute(deleteFile)
conn.commit()
if input_ == "ls":
# Shows all files/directories currently stored in database.
cursor = conn.cursor()
cursor.execute('SELECT * FROM SAFE')
rows = cursor.fetchall() # fetchall is a built-in method that retrieves all tables within the cursor object.
for row in rows:
print(row[1] + '\\' + row[0]) # Prints directory+filename
|
"""
Helper functions to find files in the various directories
"""
import os
################################################################################
def add_first_date_and_reformat(date_list):
new_list = []
for date in date_list:
year = int(date[:4])
month = int(date[4:6])
day = int(date[6:])
if len(new_list) == 0:
if day > 1:
first_date = f"{year:04}-{month:02}-{(day-1):02}"
else:
first_date = "first"
new_list.append(first_date)
new_list.append(f"{year:04}-{month:02}-{day:02}")
return new_list
|
#!/usr/local/bin/python3
from PIL import Image
import random
# Define the size of the image
width = 800
height = 800
# Create a new image with the given size
img = Image.new('RGB', (width, height))
# Access the pixel data
pixels = img.load()
# Iterate over each pixel
for i in range(width):
for j in range(height):
# Generate random color
r = random.randint(0, 255)
g = random.randint(0, 255)
b = random.randint(0, 255)
# Set the color of the pixel
pixels[i, j] = (r, g, b)
# Save the image
img.save('generative_art.png')
|
#!/usr/local/bin/python3
import os
import random
import argparse
from PIL import Image
def get_palette_from_images(folder):
"""Extract the color palette from the images in a folder."""
palette = []
for filename in os.listdir(folder):
if not filename.endswith(('jpg', 'png', 'jpeg')):
continue
image_path = os.path.join(folder, filename)
image = Image.open(image_path)
color = image.getpixel((0, 0))
palette.append(color)
return palette
def generate_gradient(colors, width, height, direction):
"""Generate a gradient image given a list of colors, size, and direction."""
base = Image.new('RGB', (width, height), colors[0])
top = Image.new('RGB', (width, height), colors[-1])
mask = Image.new('L', (width, height))
mask_data = []
for y in range(height):
for x in range(width):
if direction == 'horizontal':
mask_data.append(int(255 * (x / width)))
else: # vertical
mask_data.append(int(255 * (y / height)))
mask.putdata(mask_data)
base.paste(top, (0, 0), mask)
return base
def main(args):
# Get the color palette
palette = args.palette.split(',')
last_index = 0
for filename in os.listdir(args.output_folder):
if filename.endswith('.png'):
index = int(filename.split('_')[1].split('.')[0]) # Get the index from the filename
last_index = max(last_index, index)
last_index += 1
# Generate the gradient images
for i in range(args.num_images):
chosen_colors = random.sample(palette, args.colors_per_gradient)
image = generate_gradient(chosen_colors, args.width, args.height, args.direction)
image.save(os.path.join(args.output_folder, f'gradient_{last_index + i}.png'))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Generate gradient images.')
parser.add_argument('palette', type=str, help='A comma-separated list of colors')
parser.add_argument('output_folder', type=str, help='The output folder where generated images will be saved.')
parser.add_argument('-n', '--num-images', type=int, default=10, help='The number of gradient images to generate.')
parser.add_argument('-c', '--colors-per-gradient', type=int, default=2, help='The number of colors to include in each gradient.')
parser.add_argument('--direction', type=str, default='horizontal', choices=['horizontal', 'vertical'], help='The direction of the gradient.')
parser.add_argument('--width', type=int, default=3840, help='The width of the generated images.')
parser.add_argument('--height', type=int, default=2160, help='The height of the generated images.')
args = parser.parse_args()
main(args)
|
"""
Chat Server - RSA Assignment.
Beth Cooper
Shawn Zamechek
Qing Xie
Threaded Chat Server. There is a thread to read from the keyboard and
write to the socket and another thread to read from the socket and print to the screen.
The send thread sends the public key to the server while the recv thread receives the client's
public key and assigns the key to the global variable PUBLIC.
"""
import socket, time
import socket
from threading import Thread
import rsa
import bruteforce
PUBLIC = [] #This is the client's public
READ_SIZE = 1024
BLOCK_SIZE = 10
HOST ="localhost"
PORT = 8888
RUNNING = True
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#global socket
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
def myconnect(host, port):
"""Connection function. Just connects to the specified host & port"""
conn.connect((host, port))
def send (conn, public_keys):
"""Called by the send thread. This function sends its own public key to the client. It then enters a loop to read from the keyboard and write to the socket.
It encrypts the message using the client's public key."""
global RUNNING
send_key = str(public_keys[0]) + "," + str(public_keys[1])
totalsent = 0
while (totalsent < len(send_key)):
sent = conn.send(send_key[totalsent:])
if sent == 0:
raise RuntimeError("connection broken")
totalsent = totalsent + sent
print "Public key sent"
time.sleep(.1)#sleep used to clean up printing errors due to thread order.
print "Enter a message: "
while RUNNING:
message = raw_input("")
if message.lower() == "quit":
RUNNING = False
conn.close()
totalsent = 0
encryptedMessage = ''
#Encrypt the message character by character
for c in message:
encryptedChunk = str(rsa.encrypt(c, PUBLIC))
neededZeros = BLOCK_SIZE - len(encryptedChunk)
encryptedMessage += neededZeros * '0' + encryptedChunk
try:
#Try to send the message to the client
while (totalsent < len(encryptedMessage)):
sent = conn.send(encryptedMessage[totalsent:])
if sent == 0:
raise socket.error
totalsent = totalsent + sent
except socket.error:
print "Disconnecting... Goodbye."
conn.close()
conn.close()
def recv(conn, private_keys):
"""Called by the recv thread. This function receives the client's public key. It then enters a loop to read from the socket and write to the screen.
It decrypts the message using its own public key."""
global RUNNING
global PUBLIC
temp_public_key = ""
temp_public_key += conn.recv(READ_SIZE)
k1 = temp_public_key.split(",")
PUBLIC.append(int(k1[0]))
PUBLIC.append(int(k1[1]))
print "Public key Received"
time.sleep(.1)
connDets = conn.getpeername()
remoteIP = connDets[0]
remotePort = str(connDets[1])
print remoteIP + ":" + remotePort + " is connected"
#Use brute force method to crack the client's private key
clientPrivate = bruteforce.findPrivate(PUBLIC)
print "Brute force cracked the client's private key!"
print "Client's private d equals " + str(clientPrivate)
#While the client is connected, wait for messages
while RUNNING:
try:
message = conn.recv(READ_SIZE)
except socket.error:
print "Disconnecting... Goodbye."
conn.close()
#Parse out the decoded message into preset block size
msg_list =[]
for i in range(0, len(message), BLOCK_SIZE):
msg_list.append(message[i: i + BLOCK_SIZE])
decrypted_msg = ""
#Decode the message. Note that decrypt works in blocksize chunks
for msg in msg_list:
decrypted_msg += rsa.decrypt(int(msg), private_keys)
print remoteIP + ":" + remotePort + ": " + decrypted_msg
if decrypted_msg.lower() == "quit":
print "Client exited. Type quit to close the server."
RUNNING = False
conn.close()
#Close the socket if we managed to get out of while loop without closing
conn.close()
def main():
keys = rsa.initializeKeys()
private = keys[1] #I am going to use this to decrypt
public = keys[0] #send this to the client
print "Running the server..."
s.bind((HOST, PORT))
s.listen(1)
conn, address = s.accept()
sendThread = Thread(target=send, args=(conn, public))
recvThread = Thread(target=recv, args=(conn, private))
sendThread.start()
recvThread.start()
sendThread.join()
recvThread.join()
if __name__ == "__main__":
main()
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: Yu Zhou
# ****************
# Descrption:
# 101. Symmetric Tree
# Given a binary tree, check whether it is a mirror of itself
# (ie, symmetric around its center).
# ****************
# 思路:
# 这道题只要知道一个规律,就是左边Child要等于右边Child,就很容易了
# 先解决Root的Edge,之后在对其他进行一个统一处理,我选择写一个Helper,也可以不写
# ****************
# Final Solution *
# Recursive *
# ****************
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
else:
return self.isEqual(root.left, root.right)
def isEqual(self, n1, n2):
if not n1 or not n2:
return n1 == n2
else:
return n1.val == n2.val and self.isEqual(n1.left, n2.right) and self.isEqual(n1.right, n2.left)
|
# --------------
import pandas as pd
import os
import numpy as np
import warnings
warnings.filterwarnings("ignore")
# path_train : location of test file
# Code starts here
#Loading data
df = pd.read_csv(path_train)
print(df.head())
#Function to create new column
def label_race (row):
if row['food'] == "T":
return 'food'
elif row['recharge'] == "T":
return 'recharge'
elif row['support'] == "T":
return 'support'
elif row['reminders'] == "T":
return 'reminders'
elif row['travel'] == "T":
return 'travel'
elif row['nearby'] == "T":
return 'nearby'
elif row['movies'] == "T":
return 'movies'
elif row['casual'] == "T":
return 'casual'
else:
return "other"
# Creating a new column called category which has the column marked as true for that particular message.
df["category"] = df.apply (lambda row: label_race (row),axis=1)
# Dropping all other columns except the category column
drop_col= ["food", "recharge", "support", "reminders", "nearby", "movies", "casual", "other", "travel"]
df = df.drop(drop_col,1)
print("\nUpdated dataframe:\n",df.head())
#Code ends here
# --------------
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.preprocessing import LabelEncoder
# Sampling only 1000 samples of each category
df = df.groupby('category').apply(lambda x: x.sample(n=1000, random_state=0))
# Code starts here
# Converting all messages to lower case and storing it
all_text = df["message"].str.lower()
# Initialising TF-IDF object
tfidf = TfidfVectorizer(stop_words="english")
# Vectorizing data
tfidf.fit(all_text)
# Storing the TF-IDF vectorized data into an array
X = tfidf.transform(all_text).toarray()
# Initiating a label encoder object
le = LabelEncoder()
# Fitting the label encoder object on the data
le.fit(df["category"])
# Transforming the data and storing it
y = le.transform(df["category"])
# --------------
from sklearn.metrics import accuracy_score, classification_report
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
# Code starts here
# Splitting the data into train and test sets
X_train, X_val,y_train, y_val = train_test_split(X,y, test_size = 0.3, random_state = 42)
# Implementing Logistic Regression model
log_reg = LogisticRegression(random_state=0)
log_reg.fit(X_train,y_train)
y_pred = log_reg.predict(X_val)
log_accuracy = accuracy_score(y_val,y_pred)
print (str(log_accuracy)+(" is the accuracy of the logistic regression model"))
# Implementing Multinomial NB model
nb = MultinomialNB()
nb.fit(X_train,y_train)
y_pred = nb.predict(X_val)
nb_accuracy = accuracy_score(y_val,y_pred)
print (str(nb_accuracy)+(" is the accuracy of the Naive Bayes model"))
# Implementing Linear SVM model
lsvm = LinearSVC(random_state=0)
lsvm.fit(X_train, y_train)
y_pred = lsvm.predict(X_val)
lsvm_accuracy = accuracy_score(y_val,y_pred)
print (str(lsvm_accuracy)+(" is the accuracy of the LinearSVC model"))
# --------------
# path_test : Location of test data
#Loading the dataframe
df_test = pd.read_csv(path_test)
#Creating the new column category
df_test["category"] = df_test.apply (lambda row: label_race (row),axis=1)
#Dropping the other columns
drop= ["food", "recharge", "support", "reminders", "nearby", "movies", "casual", "other", "travel"]
df_test= df_test.drop(drop,1)
# Code starts here
all_text = df_test["message"].str.lower()
# Transforming using the tfidf object - tfidf
X_test = tfidf.transform(all_text).toarray()
# Transforming using label encoder object - le
y_test = le.transform(df_test["category"])
# Predicting using the logistic regression model - logreg
y_pred = log_reg.predict(X_test)
log_accuracy_2 = accuracy_score(y_test,y_pred)
print (str(log_accuracy_2)+(" is the accuracy of the logistic regression model"))
# Predicting using the naive bayes model - nb
y_pred = nb.predict(X_test)
nb_accuracy_2 = accuracy_score(y_test,y_pred)
print (str(nb_accuracy_2)+(" is the accuracy of the Naive Bayes model"))
# Predicting using the linear svm model - lsvm
y_pred = lsvm.predict(X_test)
lsvm_accuracy_2 = accuracy_score(y_test,y_pred)
print (str(lsvm_accuracy_2)+(" is the accuracy of the Support Vector model"))
# --------------
from nltk.corpus import stopwords
from nltk.stem.wordnet import WordNetLemmatizer
import string
import gensim
from gensim.models.lsimodel import LsiModel
from gensim import corpora
from pprint import pprint
# import nltk
# nltk.download('wordnet')
# Creating a stopwords list
stop = set(stopwords.words('english'))
exclude = set(string.punctuation)
lemma = WordNetLemmatizer()
# Function to lemmatize and remove the stopwords
def clean(doc):
stop_free = " ".join([i for i in doc.lower().split() if i not in stop])
punc_free = "".join(ch for ch in stop_free if ch not in exclude)
normalized = " ".join(lemma.lemmatize(word) for word in punc_free.split())
return normalized
# Creating a list of documents from the complaints column
list_of_docs = df["message"].tolist()
# Implementing the function for all the complaints of list_of_docs
doc_clean = [clean(doc).split() for doc in list_of_docs]
# Code starts here
# Creating the dictionary id2word from our cleaned word list doc_clean
dictionary = corpora.Dictionary(doc_clean)
# Creating the corpus
doc_term_matrix = [dictionary.doc2bow(doc) for doc in doc_clean]
# Creating the LSi model
lsimodel = LsiModel(corpus=doc_term_matrix, num_topics=5, id2word=dictionary)
pprint(lsimodel.print_topics())
# Code ends here
# --------------
from gensim.models import LdaModel
from gensim.models import CoherenceModel
# doc_term_matrix - Word matrix created in the last task
# dictionary - Dictionary created in the last task
# Function to calculate coherence values
def compute_coherence_values(dictionary, corpus, texts, limit, start=2, step=3):
"""
Compute c_v coherence for various number of topics
Parameters:
----------
dictionary : Gensim dictionary
corpus : Gensim corpus
texts : List of input texts
limit : Max num of topics
Returns:
-------
topic_list : No. of topics chosen
coherence_values : Coherence values corresponding to the LDA model with respective number of topics
"""
coherence_values = []
topic_list = []
for num_topics in range(start, limit, step):
model = gensim.models.ldamodel.LdaModel(doc_term_matrix, random_state = 0, num_topics=num_topics, id2word = dictionary, iterations=10)
topic_list.append(num_topics)
coherencemodel = CoherenceModel(model=model, texts=texts, dictionary=dictionary, coherence='c_v')
coherence_values.append(coherencemodel.get_coherence())
return topic_list, coherence_values
# Code starts here
# Calling the function
topic_list, coherence_value_list = compute_coherence_values(dictionary=dictionary, corpus=doc_term_matrix, texts=doc_clean, start=1, limit=41, step=5)
print(coherence_value_list)
# Finding the index associated with maximum coherence value
max_index=coherence_value_list.index(max(coherence_value_list))
# Finding the optimum no. of topics associated with the maximum coherence value
opt_topic= topic_list[max_index]
print("Optimum no. of topics:", opt_topic)
# Implementing LDA with the optimum no. of topic
lda_model = LdaModel(corpus=doc_term_matrix, num_topics=opt_topic, id2word = dictionary, iterations=10, passes = 30,random_state=0)
# pprint(lda_model.print_topics(5))
lda_model.print_topic(1)
|
# This file reads my name and prints out hello my name
# Author: Lonan Keane
name = input('enter your name:')
print('Hello ' + name + '\nNice to meeet you')
#Modifying to say "nice to meet you" after saying hello
|
class Terrain:
def __init__(self):
self.symbol = '#'
class Map:
def __init__(self, x, y, start_terrain):
self.map_array = []
self.x = x
self.y = y
for i in range(0, y):
self.map_array.append([])
for j in range(0, x):
self.map_array[i].append(start_terrain)
def __str__(self):
outstr = ""
for i in range(0, self.y):
for j in range(0, self.x):
outstr += self.map_array[i][j].symbol
outstr += "\n"
return outstr
|
import unittest
class TreeBase:
"""
Abstract base class
"""
class Position:
def element(self):
raise NotImplementedError
def __eq__(self, other):
raise NotImplementedError
def __ne__(self, other):
return not (self == other)
def root(self):
raise NotImplementedError
def is_root(self, p):
return self.root() == p
def parent(self, p):
raise NotImplementedError
def num_children(self, p):
raise NotImplementedError
def children(self, p):
raise NotImplementedError
def is_leaf(self, p):
return self.num_children(p) == 0
def __len__(self):
raise NotImplementedError
def is_empty(self):
return len(self) == 0
class BinaryTreeBase(TreeBase):
def __init__(self):
super().__init__()
def left(self, p):
raise NotImplementedError
def right(self, p):
raise NotImplementedError
def sibling(self, p):
parent = self.parent(p)
if parent is None:
return None
if self.left(parent) == p:
return self.right(parent)
else:
return self.left(parent)
def children(self, p):
# iterator
if self.left(p) is not None:
yield self.left(p)
if self.right(p) is not None:
yield self.right(p)
class BinaryTree(BinaryTreeBase):
def __init__(self):
super().__init__()
self._root = None
self.size = 0
class _Node:
def __init__(self, data, left=None, right=None, parent=None):
self.data = data
self.left = left
self.right = right
self.parent = parent
class Position:
def __init__(self, node, container):
self.node = node
self.container = container
def element(self):
return self.node.data
def __eq__(self, other):
return type(other) is type(self) and self.node is other.node
def __ne__(self, other):
return not (self == other)
def check_position(self, p):
"""
Positions won't necessarily refer to this particular container so must be validated
:return:
"""
if p.container is not self:
raise ValueError("Position does not belong to this tree")
if not isinstance(p, self.Position):
raise TypeError("Must be Position type")
if p.node.parent is p.node: # when a node is deleted, its child takes its place
raise ValueError("Deleted node")
return p.node
def position(self, node):
if node is None:
return None
return self.Position(node, self)
def root(self):
return self.position(self._root)
def add_root(self, data):
node = self._Node(data)
self._root = node
self.size += 1
return self.position(node)
def parent(self, p):
node = self.check_position(p)
return self.position(node.parent)
def left(self, p):
node = self.check_position(p)
return self.position(node.left)
def right(self, p):
node = self.check_position(p)
return self.position(node.right)
def add_left(self, p, data):
node = self._Node(data)
parent = self.check_position(p)
parent.left = node
node.parent = parent
self.size += 1
return self.position(node)
def add_right(self, p, data):
node = self._Node(data)
parent = self.check_position(p)
parent.right = node
node.parent = parent
self.size += 1
return self.position(node)
def num_children(self, p):
num = 0
if self.right(p):
num += 1
if self.left(p):
num += 1
return num
def delete(self, p):
node = self.check_position(p)
if self.num_children(p) > 1:
raise ValueError("Position has 2 children")
parent = node.parent
if node.right:
child = node.right
else:
child = node.left
if child:
child.parent = parent
if not node.parent: # node is root
self._root = child
else:
if parent.left is node:
parent.left = child
else:
parent.right = child
node.parent = node
self.size -= 1
return node.data
def attach(self, p, left_tree, right_tree):
node = self.check_position(p)
if not self.is_leaf(p):
raise ValueError("Position is not leaf")
self.size += len(left_tree) + len(right_tree)
if type(self) is type(left_tree) is type(right_tree):
raise TypeError("Trees are not of correct type")
if not left_tree.is_empty():
node.left = left_tree._root
node.left.parent = node.left
left_tree._root = None
left_tree.size = None
if not right_tree.is_empty():
node.right = right_tree._root
node.right.parent = node.right
right_tree._root = None
right_tree.size = None
def __len__(self):
return self.size
class BinaryTreeTest(unittest.TestCase):
def test_init(self):
tree = BinaryTree()
with self.assertRaises(AttributeError):
tree.add_left(tree.root(), "root")
tree.add_root("root")
root = tree.root()
self.assertEqual(root.element(), "root")
tree.add_left(root, "left")
tree.add_right(root, "right")
self.assertEqual(tree.left(root).element(), "left")
self.assertEqual(tree.right(root).element(), "right")
def test_size(self):
tree = BinaryTree()
root = tree.add_root("root")
left = tree.add_left(root, "left")
right = tree.add_right(root, "right")
tree.add_left(left, "left-left")
tree.add_right(left, "left-right")
self.assertEqual(len(tree), 5)
def test_children(self):
# create a tree with a child with left and right children
# check no. of children, if they're leaves and siblings
tree = BinaryTree()
root = tree.add_root("root")
left = tree.add_left(root, "left")
child_left = tree.add_left(left, "left-left")
child_right = tree.add_right(left, "left-right")
self.assertEqual(tree.num_children(left), 2)
self.assertEqual(tree.is_leaf(left), False)
self.assertEqual(tree.is_leaf(child_left), True)
children = [i for i in tree.children(left)]
self.assertEqual(children, [child_left, child_right])
self.assertEqual(tree.sibling(child_left), child_right)
def test_delete(self):
tree = BinaryTree()
root = tree.add_root("root")
left = tree.add_left(root, "left")
child_left = tree.add_left(left, "left-left")
child_right = tree.add_right(left, "left-right")
with self.assertRaises(ValueError):
tree.delete(left)
self.assertEqual(tree.delete(child_left), "left-left")
self.assertEqual(len(tree), 3)
self.assertEqual(tree.delete(left), "left")
left = tree.left(tree.root())
self.assertEqual(tree.delete(root), "root")
root = tree.root()
self.assertEqual(tree.delete(root), "left-right")
self.assertEqual(tree.is_empty(), True)
self.assertEqual(len(tree), 0)
def test_attach(self):
tree1 = BinaryTree()
root1 = tree1.add_root("root1")
tree1.add_left(root1, "left1")
tree2 = BinaryTree()
root2 = tree2.add_root("root2")
tree2.add_left(root2, "left2")
tree2.add_right(root2, "right2")
tree = BinaryTree()
root = tree.add_root("root")
tree.attach(root, tree1, tree2)
self.assertEqual(len(tree), 6)
children = [i for i in tree.children(root)]
self.assertEqual(children, [root1, root2])
if __name__ == "__main__":
unittest.main()
|
class ListNode:
prev = None
next = None
data = None
def __init__(self, prev, next, data):
self.prev = prev
self.next = next
self.data = data
class LList:
head = ListNode(None,None,None)
tail = ListNode(None,None,None)
def __init__(self, startdata):
startnode = ListNode(self.tail,self.head,startdata)
self.head.next = startnode
self.tail.prev = startnode
def addFirst(self, data):
node = ListNode(self.head, self.head.next, data)
self.head.next.prev = node
self.head.next = node
def add(self, data):
node = ListNode(self.tail.prev, self.tail, data)
self.tail.prev.next = node
self.tail.prev = node
def addIn(self, index, data):
count = 0
current = self.head.next
while count != index:
current = current.next
count += 1
node = ListNode(current.prev, current, data)
current.prev.next = node
current.prev = node
def addAll(self, collection):
for data in collection:
self.add(data)
def addAllIn(self, index, collection):
for data in collection:
self.add(index, data)
index += 1
def contains(self,data):
current = self.head.next
while current.next != self.tail:
if current.data == data:
return True
current = current.next
return False
def get(self, index):
count = 0
current = self.head.next
while count != index:
current = current.next
count += 1
return current
def getFirst(self):
return self.head.next
def getLast(self):
return self.tail.prev
def indexOf(self, data):
index = 0
current = self.head.next
while current != self.tail:
if current.data == data:
return index
current = current.next
index += 1
return -1
def print(self):
current = self.head.next
while current != self.tail:
print(current.data)
current = current.next
def lastindexOf(self, data):
index = -1
count = 0
current = self.head.next
while current != self.tail:
if data == current.data:
index = count
current = current.next
count += 1
return index
linked = LList(1)
linked.addAll([2,3,4,5,6,7,8,9,10])
linked.print()
|
from matplotlib import pyplot as plt
population_ages=[10,15,20,30,35,45,50]
bins=[10,20,30,40,50,60,70]
plt.hist(population_ages,bins,histtype='bar',rwidth=0.8)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Histogram')
plt.show()
|
#Algoritmo de Huffman
#Carlos Triana - FIME, ITS
def main():
frec = [] #Para poner las frecuencias de los caracteres
newtext = []
corleone = []
'''
El formato de las frecuencias es la frecuencia, seguido del caracter correspondiente
'''
texto = raw_input('Ingresar cadena: ')
print texto
miLista = list(texto)
newtext = miLista[:]
for car in newtext:
#frec.append(car)
c = newtext.count(car)
if c == 1:
frec.append(car)
frec.append(c)
elif c > 1:
if car not in corleone:
corleone.append(car)
corleone.append(c)
santino = [] #Para guardas las listas
corleone2 = corleone[:]
corleone2.reverse()
largo = len(corleone)
for bla in range(largo):
if bla%2 == 0:
li = [corleone2[bla], corleone2[bla+1]]
santino.append(li)
santino.sort()
largo2 = len(santino)
fredo = [] #Esta la la extenderemos a la lista "frec"
for w in range(largo2):
fredo.append(santino[w][0])
fredo.append(santino[w][1])
print frec
frec.reverse()
suma = frec + fredo
print frec
print corleone
#print corleone2
#print santino
#print largo2
print fredo
print suma
main()
|
# valid_list = [':)', ':D', ';-D', ':~)', ';D', ':-D', ':-)', ';~)']
class SmileFace:
def smile_face_check(self, faces_list: list):
_result = 0
for face in faces_list:
if self._has_eyes(face) and self._has_noses(face) and self._has_smile(face):
_result += 1
return _result
def _has_eyes(self, face: str) -> bool:
if ':' in face or ';' in face:
return True
else:
return False
def _has_noses(self, face: str) -> bool:
face = face.strip()
if len(face) == 2:
return True
if '-' in face or '~' in face:
return True
else:
return False
def _has_smile(self, face: str) -> bool:
if 'D' in face or ')' in face:
return True
else:
return False
|
from __future__ import generators
from math import sqrt
from array import array
def is_prime(n):
if n < 0:
n = -n
if n < 2:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0:
return False
limit = int(sqrt(n)+1)
for x in range(3, limit, 2):
if n % x == 0:
return False
return True
def gcd(a, b):
if b > a:
a, b = b, a
r = a % b
while r != 0:
a, b = b, r
r = a % b
return b
def eras(n):
siv=range(n+1)
siv[1]=0
sqn=int(round(n**0.5))
for i in range(2,sqn+1):
if siv[i]!=0:
siv[2*i:n/i*i+1:i]=[0]*(n/i-1)
return filter(None,siv)
def primes_million(limit):
limit = min(1000000, limit)
f = open('primes1.txt')
primes = []
for l in f:
if limit > 0:
primes.append(int(l.strip()))
limit -= 1
else:
break
return primes
def phi(a):
"""
A rather naive method.
"""
p = 1
for x in range(2, a):
if gcd(a, x)==1:
p = p + 1
return p
def factorial(n):
f = 1
for x in range(1, n+1):
f *= x
return f
class polygonal_numbers:
def __init__(self, initial_d, increment_d):
self.initial_d = initial_d
self.increment_d = increment_d
self.p = 1
def __iter__(self):
return self
def next(self):
val = self.p
self.p += self.initial_d
self.initial_d += self.increment_d
return val
class triangle_numbers(polygonal_numbers):
def __init__(self):
polygonal_numbers.__init__(self, 2, 1)
class square_numbers(polygonal_numbers):
def __init__(self):
polygonal_numbers.__init__(self, 3, 2)
class pentagonal_numbers(polygonal_numbers):
def __init__(self):
polygonal_numbers.__init__(self, 4, 3)
class hexagonal_numbers(polygonal_numbers):
def __init__(self):
polygonal_numbers.__init__(self, 5, 4)
class heptagonal_numbers(polygonal_numbers):
def __init__(self):
polygonal_numbers.__init__(self, 6, 5)
class octagonal_numbers(polygonal_numbers):
def __init__(self):
polygonal_numbers.__init__(self, 7, 6)
|
#Gemma Buckle
#18/09/2014
#converting denary to binary to hexadecimal
denary_value = int(input("Please enter a denary integer: "))
binary_string = ""
while denary_value > 0:
denary_string = CStr(denary_value)
binary_string = Cstr(denary_value%2)
denary_value = denary_value//2
endwhile
print("The binary equivalent is {0}".format(binary_string))
|
# Exercise 10
import random
exit_keys = ("n", "e", "ex", "exi", "exit") # Use these keys to exit.
while True: # Loop forever or until exit key is typed.
print(44 * '-')
print('exit keys: ', exit_keys)
print(44 * '-')
print('\nPlease wait while the machine generates two random lists...')
alpha = random.choices(range(0, 100), k=random.randint(0, 100)) # Generate a list of random 'k' length with random integers in range 0-100.
beta = random.choices(range(0, 100), k=random.randint(0, 100)) # Generate a list of random 'k' length with random integers in range 0-100.
print('The machine generated two random lists with integers.')
print(4 * ' ' + 'List alpha ->', alpha)
print(4 * ' ' + 'List beta ->', beta)
user_input = input('\n---> Press enter to continue or one of the exit keys to exit.\n This will return common elements from the above lists, without duplicates: ')
if user_input == '': # Empty 'user_input' means that the user pressed enter without any other input.
common_elements_list = list(dict.fromkeys([alpha_x for alpha_x in alpha if alpha_x in beta])) # Find common elements and remove duplicates.
print('\n---> common elements', common_elements_list)
valid_input = True
while valid_input is True:
user_input = input('Would you like to restart (y/n)? ') # Prompt player to restart the process.
if user_input == 'y':
print('Restarting...')
print(100 * '_')
valid_input = False # Used to break the 'while' loop.
elif user_input == 'n':
print('Exiting...')
print(100 * '_')
exit(0)
else:
print('Sorry I didn\'t get that...') # 'while' loop will continue.
elif user_input in exit_keys: # User just entered on of the exit sequences. ('n', 'e', 'ex', 'exi', 'exit')
user_input_on_exit = input('\nYou just pressed one of the exit keys (n, e, ex, exi, exit)...\nAre you sure you want to exit (y/n)? ')
if user_input_on_exit == 'y':
print('Exiting...')
print(100 * '_' + '\n')
exit(0)
else:
continue
|
import math
from collections import Counter
def combination(n, r, coma=False):
nf = math.factorial(n)
rf = math.factorial(r)
m = n - r
mf = math.factorial(m)
tf = mf * rf
result = nf / tf
if coma: return (f"{int(result):,}")
elif coma == False: return int(result)
def permutationword(word, coma=False):
n = len(word)
fn = math.factorial(n)
x = Counter(word)
result = 1
for j in x.values(): result *= math.factorial(j)
total = fn / result
if coma: return (f"{int(total):,}")
elif coma == False: return int(total)
def permutationint(n, *args, coma=False):
fn = math.factorial(n)
result = 1
for i in args: result *= math.factorial(i)
if coma: return (f"{int(fn / result):,}")
elif coma == False: return int(fn / result)
def circle(n, counterc=False, coma=False):
result = n - 1
x = math.factorial(result)
if counterc:
if coma: return (f"{int(x / 2):,}")
elif coma == False: return int(x / 2)
elif counterc == False:
if coma: return (f"{x:,}")
elif coma == False: return x
def permutationwo(n, r, coma=False):
c = math.factorial(n)
t = n - r
j = math.factorial(t)
p = c / j
if coma: return (f"{int(p):,}")
elif coma == False: return (int(p))
def factorial(n, coma=False):
permu = math.factorial(n)
if coma: return (f"{permu:,}")
elif coma == False: return (permu)
|
# -*- coding: utf8 -*-
import random
import json
#fonction pour lire le fichier characters.json et le convertir en liste
def read_values_from_json(file, key):
values = [] # Create a new empty list
with open(file) as f:# Open a json file with my objects
data = json.load(f) # load all the data it contains. data = entries
for entry in data: # add each item in my list
values.append(entry[key])
return values # return my completed list
def message(character, quote):
n_character = character.capitalize()
n_quote = quote.capitalize()
return "{} a dit : {}".format(n_character, n_quote)
def get_random_item(my_list):
# show random quote
rand_num = random.randint(0, len(my_list) -1)
item = my_list[rand_num] # get a quote from list
return(item) # return the item
# return a random value from a json file - formule générale
# def random_value():
# all_values = read_values_from_json()
# return get_random_item(all_values)
def random_quote():
all_values = read_values_from_json("quotes.json","quote")
return get_random_item(all_values)
def random_character():
all_values = read_values_from_json("characters.json","character")
return get_random_item(all_values)
#Program
user_answer = input("Tapez entrez pour connaitre une autre citation ou B pour quitter le programme")
while user_answer != "B":
print(message(random_character(), random_quote()))
user_answer = input("Tapez entrez pour connaitre une autre citation ou B pour quitter le programme")
#github link https://github.com/OpenClassrooms-Student-Center/demarrez_votre_projet_avec_python/blob/P4C1/san_antonio.py
#-------------------------------------
#fonction exemple de turtle -> rosace
#-------------------------------------
#import turtle
#from turtle import *
#color('red', 'yellow')
#begin_fill()
#while True:
#forward(200)
#left(170)
#if abs(pos()) < 1:
#break
#end_fill()
#done()
|
#!/usr/bin/python3
import random
number = random.randint(-10000, 10000)
last_digit = number % 10
if last_digit > 5:
print("{} and is greater than 5".format(last_digit))
elif last_digit == 0:
print("{} and is 0".format(last_digit))
else:
print("{} and is less than 6 and not 0".format(last_digit))
|
#encoding:UTF-8
class ListNode:
def __init__(self, key, value, prev = None, next = None):
self.key = key
self.value = value
self.prev = prev
self.next = next
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.size = 0
self.head = ListNode(None, None)
self.tail = ListNode(None, None)
self.head.next = self.tail
self.tail.prev = self.head
self.hashmap = {}
def __delete(self, curr):#delte may happen in the list or the tail
curr.prev.next = curr.next
curr.next.prev = curr.prev
self.size -= 1
def __insert(self, curr):#before head
curr.next = self.head.next
curr.prev = self.head
self.head.next.prev = curr
self.head.next = curr
self.size += 1
def get(self, key):
found = False
if key in self.hashmap:
found = True
node = self.hashmap[key]
value = node.value
self.__delete(node)
#newNode = ListNode(key, value)
self.__insert(node)
#self.hashmap[key] = newNode
return value
else:
return -1
def set(self, key, value):
if key in self.hashmap:
node = self.hashmap[key]
self.__delete(node)
newNode = ListNode(key, value)
self.__insert(newNode)
self.hashmap[key] = newNode
if self.size > self.capacity:
del self.hashmap[self.tail.prev.key]
self.__delete(self.tail.prev)
if __name__ == '__main__':
cache = LRUCache(2)
cache.set('one', 1)
cache.set('two', 2)
cache.set('three', 3)
cache.set('four', 4)
#head = cache.head
#while(head):
# print head.key, head.value
# head = head.next
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def fir_order(root,res_list):
if root != None:
res_list.append(root.val)
fir_order(root.left, res_list)
fir_order(root.right, res_list)
else:
return
if __name__ == '__main__':
node1 = TreeNode(1)
node2 = TreeNode(2)
node3 = TreeNode(3)
node1.left = node2
node1.right = node3
rest_list = []
fir_order(node1,rest_list)
for each in rest_list:
print each
|
#encoding:UTF-8
#用到了三向切分,可以过AC快排,但是过不了插入排序,不知道怎么shuffle
from myList import *
from time import clock
import random
def sortList_quick(head, tail):
if head is tail:
return
prev = head
if prev.next == tail or prev.next.next == tail:#0-1 Node
return
else:
curr = prev.next
pivot = curr.val
pivot_pos = curr
prev = curr
curr = curr.next
while curr != tail:
if curr.val < pivot:
prev.next = curr.next
curr.next = head.next
head.next = curr
curr = prev.next
elif curr.val == pivot_pos:
if pivot.next == curr:#without it will cause infinite loop
prev = curr
curr = curr.next
else:
prev.next = curr.next
curr.next = pivot_pos.next
pivot_pos.next = curr
curr = prev.next
else:
prev = curr
curr = curr.next
pivot_last = pivot_pos
while pivot_last.next != None and pivot_last.next.val == pivot:
pivot_last = pivot_last.next
sortList_quick(head,pivot_pos)
sortList_quick(pivot_last,tail)
class Solution():
def sortList(self,head):
before_head = ListNode(1000)
before_head.next = head
sortList_quick(before_head, None)
return before_head.next
if __name__ == "__main__":
ori_list = range(1,5000)
random.shuffle(ori_list)
alist = buildList(ori_list)
#travel(alist)
start = clock()
res = Solution().sortList(alist)
time_cons = clock() - start
#travel(res)
print time_cons
|
dic={'final':['A','B','C'],
'A':['a','b'],
'B':['c','d'],
'a':['aa','bb'],
'C':['a','e'],
'aa':['o','p'],
'p':['hi','h'],
'bb':['5','10'],
'h':['hey'],
'b':['x']
}
l=[]
#root(dic) function is to find the primary target table in the dictionary
def root(dic):
keys=dic.keys()
values=dic.values()
new_list=[]
for i in values:
new_list+=i #forming a single list that holds all the values in the dictionary
#print keys,values
for key in keys:
if key not in new_list:
root=key
init_val=dic[root][:] #creating a copy of the list
init_val.insert(0,root)
#print init_val
l.append(root)
l.append(init_val)
dependant(dic[root])
return root
def dependant(x):
for key in x:
if key in dic.keys():
k=dic[key][:] #creating a copy of list
l.append(k)
l[len(l)-1].insert(0,key)
dependant(dic[key]) #calling a recursive function to create a dependant list
root(dic)
print l
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#--------------------
#Program name:
#N queen solver
#
#import multiprocessing
from board import *
import time
nodos_visitados = 0
def conflict(state,X):
"""This function checks for any conflicts when placing a
Queen on the board.The state variable is a tuple which contains
the postiions of all the queens already placed and X is the
position for which checking is being done.Note here that X also
is X co-ordinate of the piece being placed.Y refers to Y coordinate."""
Y=len(state)
for i in range(Y):
if abs(state[i]-X) in (0, Y-i):
return True
return False
def queens(num,sol,state=()):
"""This generator uses backtracing and recursion to place the
the queens.The result is a generator containing all the possible
solutions."""
global nodos_visitados
for pos in range(num):
estado = state+(pos,)
while len(estado) != num:
estado = estado+(-1,)
nodos_visitados = nodos_visitados + 1
solucion = {"solution": False, "board" : estado}
sol.put(solucion)
if not conflict(state,pos):
if len(state)==num-1:
yield (pos,)
else:
for result in queens(num,sol,state+(pos,)):
yield (pos,)+result
def backtracking(queen_number, uno):
global nodos_visitados
board = [-1 for i in range(queen_number)]
q = Queue()
aux = {"board": board, "solution":False}
q.put(aux)
p2 = Process(target=draw_board, args=(q, queen_number))
p2.start()
t1 = time.time()
for solution in queens(queen_number,q):
solucion = {"solution": True, "board" : solution}
q.put(solucion)
if solution and uno:
break
t2 = time.time()
tiempo = (t2-t1) * 1000
draw_stats(nodos_visitados, round(tiempo, 5))
|
#Words combination
#Create a program that reads an input string and then creates and prints 5 random strings from characters of the input string.
import random
some_str = ''.join((random.choice('abcdefghijklmnopqrstuvwxyz') for i in range(5)))
print(some_str)
|
__author__ = 'Adam'
import sys
import time
from board import Board
from termcolor import colored
from player import Player
from bot3435 import Bot3435
class Game:
def __init__(self):
self.player_1 = Player("white")
self.player_2 = Bot3435("black")
self.board = Board()
self.choices = {
"1": self.board.print_board,
"2": self.round,
"3": self.quit
}
@staticmethod
def show_choices():
print("""
Chess Options
1. Show game board
2. Move a piece
3. Quit
""")
def play(self):
"""Play a game of chess."""
while True:
self.show_choices()
choice = input("Enter an option: ")
action = self.choices.get(choice)
if action:
action()
else:
print("{0} is not a valid choice".format(choice))
# Option 2
def round(self):
is_success, old_posn, piece = self.player_1.move()
if is_success:
self.successful_move_message(old_posn, piece)
self.board.update_board(old_posn, piece)
self.player_2.move()
else:
self.error_message(2)
self.round()
# Option 3
@staticmethod
def quit():
print("Thank you for playing Chess!")
sys.exit(0)
@staticmethod
def error_message(error):
if error == 1:
print(colored("Invalid move. Please try again.", "red"))
if error == 2:
print(colored("You have no piece at this location.", "red"))
@staticmethod
def successful_move_message(old_posn, piece):
for letter in "Moving piece ...":
sys.stdout.write(letter)
sys.stdout.flush()
time.sleep(0.1)
print(colored("\n\nYou successfully moved your {0} from {1}{2} to {3}{4}!".format(
piece.type, old_posn.x, old_posn.y, piece.posn.x, piece.posn.y), "green"))
def update_board(self):
pass
if __name__ == "__main__":
game = Game()
game.play()
|
board=[["X","O","#"],["X","X","X"],["#","#","#"]]
def board_to_string(board):
count=0
result1=''
for i in board:
count=0
for j in i:
if count in range(0,2):
result1+='|'
result1+=' '
result1+=str(j)
result1+=' '
elif count==2:
result1+='|'
result1+=' '
result1+=str(j)
result1+=' '
result1+='|'
result1+='\n'
count+=1
return(result1)
def main():
if __name__=='__main__':
main()
|
n=int(input("Enter count of numbers: "))
count=1
numbers=[]
while count<=n:
number=int(input("Please enter a number: "))
numbers=numbers+[number]
count+=1
numbers.sort()
print(numbers[-1])
|
n=int(input("Enter count of numbers to input: "))
count=1
numbers=[]
while count<=n:
number=int(input("Enter a number: "))
numbers=numbers+[number]
count+=1
print(numbers)
|
word=str(input("Please insert a word to search: "))
n=int(input("Please enter the number of words to search in: "))
count=1
words=[]
founder=0
while count<=n:
wordsEL=input("Please enter a word: ")
words=words+[wordsEL]
count+=1
for i in words:
if i==word:
founder+=1
print("{} if found {} times.".format(word,founder))
|
def is_string_palindrome(string):
strcheck='abcdefghijklmnopqrstuvwxyz'
string=string.lower()
letonly=''
res=''
for i in string:
if i in strcheck:
letonly+=i
res=i+res
return letonly==res
def main():
if __name__=='__main__':
main()
|
import random
a=1
b=int(input("Enter sides: "))
def roll(a,b):
rnd=1
collector=0
while rnd<4:
print()
input("Press ENTER to roll the dice...")
print()
turn=random.randint(a,b)
if rnd==1:
print("First roll: {}".format(turn))
#print(turn)
#rnd+=1
#collector+=turn
elif rnd==2:
print("Second roll: {}".format(turn))
#print(turn)
#rnd+=1
#collector+=turn
elif rnd==3:
print("Third roll: {}".format(turn))
#print(turn)
rnd+=1
collector+=turn
print("Sum is: {}".format(collector))
roll(a,b)
|
n=int(input("Моля въведете броя на блоковете: "))
m=0
blocks=[]
while m<n:
blocks+=[int(input("Моля въведете височината на блоковете:"))]
m+=1
#print(blocks)
highest=0
seen=[]
for i in blocks:
if i>highest:
seen+=[i]
highest=i
print("Блоковете, които ще видите са с височина съответно {}".format(seen))
|
n=int(input("Please insert th number of elements: "))
start=0
items=[]
while start<n:
elem=input("Please insert an element: ")
items+=[elem]
start+=1
def countEL(items):
counter=0
for i in items:
counter+=1
return counter
print("count_elements({}) == {}".format(items,countEL(items)))
|
n=int(input("\nPlease enter a number: "))
m=n
collector=''
while n>0:
collector+=str(n%10)
n=n//10
print("\nThe reverse int of {} without leading zero is :".format(m),end=' '),print(int(collector))
|
print("I will count to 10")
input("press ENTER to start:")
turn=0
while turn<10:
turn+=1
print(turn)
|
#!/bin/env python
""" Advent of code """
def part_1(input_lengths):
"Day 10 Algorithm"
circular_list = list(range(256))
current_position = 0
skip_size = 0
# Knot Hash Algorithm Round
for length in input_lengths:
print_list(circular_list, current_position)
print("\nLength is %d" % length)
if length > 0:
# Find the sublist to be reversed
substr_end = (length + current_position - 1) % len(circular_list)
print_list(circular_list, current_position, substr_end)
# Reverse that section
reverse_sublist(circular_list, current_position, substr_end)
print_list(circular_list, current_position, substr_end)
# Move current position forward
current_position = (current_position + length +
skip_size) % len(circular_list)
skip_size += 1
print_list(circular_list, current_position)
return circular_list[0] * circular_list[1]
def part_2(input_lengths):
"Day 10 Algorithm"
input_lengths = ascii_code(input_lengths)
input_lengths += [17, 31, 73, 47, 23]
print(input_lengths)
# Perform 64 rounds reach sparse_hash
circular_list = list(range(256))
current_position = 0
skip_size = 0
for i in range(64):
# Knot Hash Algorithm Round
for length in input_lengths:
if length > 0:
# Find the sublist to be reversed
substr_end = (length + current_position -
1) % len(circular_list)
# Reverse that section
reverse_sublist(circular_list, current_position, substr_end)
# Move current position forward
current_position = (current_position + length +
skip_size) % len(circular_list)
skip_size += 1
sparse_hash = circular_list
print(sparse_hash)
# Reduce into dense_hash
dense_hash = sparse_to_dense(sparse_hash)
print(dense_hash)
hex_str = ""
for i in dense_hash:
hex_str += "%0.2x" % i
return hex_str
def ascii_code(s):
return [ord(c) for c in s]
def sparse_to_dense(hsh):
dense_hash = []
for i in range(16):
tmp = 0
for j in range(16):
tmp ^= hsh[i * 16 + j]
dense_hash.append(tmp)
return dense_hash
def reverse_sublist(lst, start, end):
if start <= end:
lst[start:end + 1] = lst[start:end + 1][::-1]
else:
sublist = lst[start:] + lst[:end + 1]
sublist = sublist[::-1]
lst[start:] = sublist[:len(lst) - start]
lst[:end + 1] = sublist[len(lst) - start:]
return lst
def print_list(l, current_position, substr_end=-1):
for idx, i in enumerate(l):
if idx == current_position and substr_end == current_position:
print("([%d])" % i, end=' ')
elif idx == current_position and substr_end != -1:
print("([%d]" % i, end=' ')
elif idx == current_position:
print("[%d]" % i, end=' ')
elif idx == substr_end:
print("%d)" % i, end=' ')
else:
print("%d" % i, end=' ')
print()
def main():
"Main Entrypoint"
input_str = open('input_10', 'r').read().strip()
input_lengths = [int(i) for i in input_str.split(',')]
answer = part_1(input_lengths)
print("Part 1 Answer:", answer)
answer = part_2(input_str)
print("Part 2 Answer:", answer)
if __name__ == "__main__":
main()
|
#!/usr/bin/env python3
""" Advent of code """
from collections import defaultdict
def part_1(fh):
two_count, three_count = 0, 0
for line in fh:
c2, c3 = part_1_sub(line)
if c2 == 1:
two_count += 1
if c3 == 1:
three_count += 1
return (two_count, three_count)
def part_1_sub(line):
has_two, has_three = False, False
counts = {}
counts = defaultdict(lambda: 0, counts)
for c in line:
counts[c] += 1
for c, count in counts.items():
if count == 2:
has_two = True
elif count == 3:
has_three = True
return (has_two, has_three)
def part_2(lines):
max_letters_in_common = []
for a in lines:
for b in lines:
if a != b:
letters_in_common = part_2_sub(a, b)
if len(letters_in_common) > len(max_letters_in_common):
max_letters_in_common = letters_in_common
return ''.join(max_letters_in_common)
def part_2_sub(a, b):
letters_in_common = []
for i in range(0, len(a)-1):
if a[i] == b[i]:
letters_in_common.append(a[i])
return letters_in_common
def main():
"Main Entrypoint"
two_count, three_count = part_1(open('input_2', 'r'))
print('Part 1 is: ', two_count * three_count)
print('Part 2 is: ', part_2(open('input_2', 'r').readlines()))
if __name__ == "__main__":
main()
|
# find the i-th smallest element of an array of distinct integers
# where the 0th smallest element is the minimum
import random
def randomized_select(A,p,r,i):
# finds the i'th smallest element A between indices p and r
if p == r:
return A[p]
q = randomized_partition(A,p,r)
#q = partition(A,p,r)
k = q-p+1
if i < k: return randomized_select(A,p,q,i)
else: return randomized_select(A,q+1,r,i-k)
def partition(A,p,r):
# partitions A so that the first j+1 elements are less than A[0]
# and the rest greater than or equal to A[0]. Returns j
x = A[p]
i = p
j = r
while True:
while A[j] > x:
j-=1
while A[i] < x:
i+=1
if i < j:
A[i], A[j] = A[j], A[i]
i+=1
j-=1
else: return j
def randomized_partition(A,p,r):
i = random.randint(p,r)
A[i], A[p] = A[p], A[i]
return partition(A,p,r)
def main():
randomlist = random.sample(range(1, 10), 5) # testing
print(randomlist)
print(randomized_select(randomlist,0,4,1))
if __name__ == "__main__":
main()
|
# insertion sort
def insertion_sort(A,p,r): # sort the list A of integers between indices p and r
for i in range(p+1,r+1):
temp = A[i]
j = i-1
while j >= p and A[j] > temp:
A[j+1] = A[j]
j-=1
A[j+1] = temp
# if instead use the following for loop, merge sort faster than insertion on sorted list
# for j in range(i-1,p-1,-1):
# if A[j] > temp:
# A[j+1] = A[j]
# if j == p:
# A[j] = temp
# else:
# A[j+1] = temp
# break
return A
def main():
import random
randomlist = random.sample(range(0, 20), 10) # testing
print(randomlist)
print(insertion_sort(randomlist,0,9))
if __name__ == "__main__":
main()
|
class Solution(object):
def sortColors(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
if nums == []:
return None
# take pointers for each number
idx0 = 0
idx2 = len(nums) - 1
idx1 = 0
# while 1 pointer is on left of 2 pointer
while idx1 <= idx2:
# if we find 2 , swap with the 2 pointer and stay at the same place
if nums[idx1] == 2:
nums[idx1],nums[idx2] = nums[idx2], nums[idx1]
idx2 -= 1
# if we find 0 swap with the zero pointer and move ahead
elif nums[idx1] == 0:
nums[idx1],nums[idx0] = nums[idx0], nums[idx1]
idx0 += 1
idx1 += 1
# just move ahead, 1s will automatically arrange
elif nums[idx1] == 1:
idx1 += 1
|
class Solution(object):
def isOneBitCharacter(self, bits):
"""
:type bits: List[int]
:rtype: bool
"""
'''
Time Complexity: O(n)
Space Complexity: O(1)
'''
i = 0
flag = True
while i < len(bits):
if bits[i] == 1 and (bits[i+1] == 1 or bits[i+1] == 0):
i += 2
flag = False
elif bits[i] == 0:
i += 1
flag = True
return flag
|
class Solution:
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
'''
Time Complexity: O(v+e)
Space Complexity: O(n)
'''
if root is None:
return False
bfs_nodes = [root]
# set of traversed nodes
traversed = set()
# iterate through all the nodes in the list
for node in bfs_nodes:
# if the required value is in the list
if k - node.val in traversed:
return True
else:
traversed.add(node.val)
# traverse left and right of the tree
if node.left: bfs_nodes.append(node.left)
if node.right: bfs_nodes. append(node.right)
return False
|
'''
Time Complexity: O(n^2)
Space Complexity: O(1)
'''
class Solution(object):
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
# lenght of LPS for every letter would be 1 minimum
max_length = 1
idx = 0
# iterate through all elements taking each as center
for i in range(len(s)):
# Considering the length of palidrome is Even
a = i-1
b = i
even_max = 0
# Moving away from the center
while a >= 0 and b < len(s) and s[a] == s[b]:
# Only change the max_length if a greater palindrome is found
if b - a + 1 > max_length:
idx = a
max_length = b - a + 1
a-=1
b+=1
# Considering the length of palidrome is Odd
a = i - 1
b = i + 1
# Moving away from center
while a >= 0 and b < len(s) and s[a] == s[b]:
# Only change the max_length if a greater palindrome is found
if b - a + 1 > max_length:
idx = a
max_length = b - a + 1
a-=1
b+=1
return s[idx:idx+max_length]
|
"""
Time Complexity: O(n^n)
"""
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort() # time complexity = O(nlogn)
ans = []
for i in xrange(len(nums) - 2):
if i > 0 and nums[i] == nums[i-1]:
continue
left, right = i + 1, len(nums) - 1
while(left<right):
s = nums[i]+nums[left]+nums[right]
if s == 0:
ans.append([nums[i],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 s > 0:
right -= 1
elif s < 0:
left += 1
return ans
|
import sqlite3
class ItemModel:
def __init__(self, name, price):
self.name = name
self.price = price
def json(self):
return {'name': self.name, 'price':self.price}
@classmethod
def find_by_name(cls,name):
connection = sqlite3.connect("mydata.db")
cursor = connection.cursor()
select_sql = "SELECT * FROM items WHERE name = ?"
items = cursor.execute(select_sql, (name,))
row = items.fetchone()
connection.close()
if row:
return cls(*row)
def insert(self):
connection = sqlite3.connect("mydata.db")
cursor = connection.cursor()
insert_sql = "INSERT INTO items VALUES(?,?)"
cursor.execute(insert_sql, (self.name, self.price))
connection.commit()
connection.close()
def update(self):
connection = sqlite3.connect("mydata.db")
cursor = connection.cursor()
upd_sql = "UPDATE items SET price = ? WHERE name = ?"
cursor.execute(upd_sql, (self.price, self.name))
connection.commit()
connection.close()
|
"""
Car类
"""
class Car(object):
description = ['大众','丰田','广本','沃尔沃','凯迪拉克']
def __init__(self, l, w, h, brand):
self.L = l
self.W = w
self.H = h
self.brand = brand
def modify_des(self):
if self.description != None:
return self.description
else:
print('请输入您的车辆描述')
@staticmethod
def basic_parameters():
print('已完成车辆基本参数信息的录入!')
@classmethod
def upkeep(cls, desc):
if desc in cls.description:
print('根据汽车保养的相关经验,{}品牌的车应于5000km/次的频率进行专业性保养'.format(desc))
else:
print('非常抱歉!{}品牌不在我们的保养范围内'.format(desc))
if __name__ == '__main__':
car_1 = Car(3, 2, 1.5, '大众')
car_1.basic_parameters()
if car_1.modify_des():
car_1.upkeep(car_1.brand)
else:
print('请正确填写相关的车辆信息')
|
# @author Alexander Skeba
class Pokemon():
#create an intitialization function for each new pokemon
def __init__(self, name, type, nature, level, attack, defense, speed, max_health, moves = ["-----","-----","-----","-----"]):
"""
Parameters:
name (string): Name of Pokemon
type (string): Type of Pokemon (ex. "water", "fire", "grass")
nature (string): Nature of Pokemon (ex. "Attack", "Defense", "Speed")
level (int): Initial level of Pokemon
attack (int): Attack stat of a pokemon
defense (int): Defense stat of a pokemon
speed (int): Speed stat of a pokemon
max_health (int): Max Health of a pokemon
moves (list): Moveset of a pokemon
move_dict (dict): Dictionary containg moves
"""
self.name = name
self.type = type
self.nature = nature
self.level = level
self.attack = attack
self.defense = defense
self.speed = speed
self.max_health = max_health
self.moves = moves
self.current_health = max_health
# create a string representation of the move set to allow the user to choose a move
self.moveset = " (1) {0:>5} \t (2) {1:>5} \n (3) {2:>5} \t (4) {3:>5} \n".format(self.moves[0], self.moves[1], self.moves[2], self.moves[3])
def __str__(self):
'''Give a string representation of the pokemon for testing purposes'''
return f'Stats: \n Name: {self.name} \n Type: {self.type} \n Nature: {self.nature} \n Level: {self.level} \n Attack: {self.attack} \n Defense: {self.defense} \n Speed: {self.speed} \n Max Health: {self.max_health} \n Moves: {self.moves} \n Current Health: {self.current_health} \n'
#increase the stats of the pokemon after they level up
def level_up(self):
#set a limit of lv. 100 for each pokemon, if pokemon is already lv 100 exit the level up sequence
if self.level <= 100:
self.level += 1
else:
return
self.attack += 1
self.defense += 1
self.speed += 1
#Check its Nature and level up stats accordingly
if self.nature == "attack":
self.attack += 2
if self.nature == "defense":
self.defense += 2
if self.nature == "speed":
self.speed += 2
#choose move
def choose_move(self):
#cast the user's input into an int to be used as the index of the moves array. Subtract '1' to account for lists starting at 0
self.move_int = int((input(self.moveset))) - 1
#function to deal damage
def use_move(self, type, move):
pass
#function to take damge
def take_damage():
pass
class Move():
def __init__(self, name, type, attack, stat_move='None'):
"""
The Move class creates a move object that holds important information on what a move does
Parameters:
name (str) Name of the move
type (str) Type of the move (ex. "water", "grass", fire"
stat_move (str) String affects the users or oppenents stats (ex. "attack_up", "defense_down")
attack (int) Attack power of the move
"""
self.name = name
self.type = type
self.stat_move = stat_move
self.attack = attack
def generate_Moves():
'''
Generates a dictionary from the moveset.csv file located in the same folder.
'''
import pandas as pd
movesets = pd.read_csv("moveset.csv", delimiter = ',')
all_moves = {}
for row, label in movesets.iterrows():
all_moves[label['Name']] = Move(label['Name'],label['Type'],label['Attack'],label['Stat_move'])
return all_moves
def generate_Pokedex():
'''
Generates a dictionary containing attributes for each Pokemon
'''
import pandas as pd
pokedex_csv = pd.read_csv("pokedex.csv", delimiter = ',')
pokedex = {}
for row, label in pokedex_csv.iterrows():
pokedex[label['Name']] = Pokemon(label['Name'], label['Type'], label['Nature'], label['Level'], label['Attack'], label['Defense'], label['Speed'], label['Max_health'], label['Moves'])
return pokedex
squirtle = Pokemon("squirtle", "water", "defense", 5, 10, 15, 10, 15, ["tackle", "growl", "-----", "-----"], )
blank = Pokemon("missingo", "none", "none",0, 0, 0, 0 ,0)
|
import re
def read_template(root):
"""
read a file from a root
give an exception if it not found
"""
try:
with open (root , "r") as file:
content=file.read().strip()
return content
except FileNotFoundError:
raise FileNotFoundError('The file not found')
except Exception as a :
return (f"Error {a}")
def parse_template (text):
"""
• here after we read a file we need to analysis it content.
• origin_value finds all text inside { } from file and store them in array.
• the for loop replace all values above in the text with empty string {} in the text file.
then we have an text and array.
"""
index=0
origin_value=re.findall(r"\{(.*?)\}", text)
for i in origin_value:
text= text.replace(origin_value[index], "",1)
index+=1
return text, tuple(origin_value)
def merge(text,origin_value):
# print(text.format(*origin_value))
updatedText= text.format(*origin_value)
print(updatedText)
with open('assets/make_me_a_video_game_output.txt','w') as output:
output.write(updatedText)
return updatedText
# just merging data using .format we used * to destruct tha array and publish it on {}
def result( text,origin_value):
input_user=[]
for i in origin_value:
input_user.append(input(f"enter an { i} ")) #take the variable in bracket as question to user depends on the origin values .
return merge(text,input_user)
if __name__ == "__main__":
print("""
Welcome to Madlib Game 😉
You will enjoy playing with us 😎
""")
reading_template=read_template('assets/make_me_a_video_game_template.txt')
parse_template (reading_template)
text,origin_value=parse_template (reading_template)
result( text, origin_value)
|
from collections import Counter
from HuffmanCoding import *
if __name__ == '__main__':
frequencies = Counter()
nodes = {}
while raw_input('Enter new word? [y/n] ') == 'y':
word = raw_input('Enter word: ')
for symbol in word:
frequencies[symbol] += 1
for e, f in frequencies.items():
if e not in nodes:
nodes[e] = Node(e, f)
else:
nodes[e]._frequency = f
print nodes
huffman_code = HuffmanCode(nodes.values())
root, codes = huffman_code.huffman_code()
print codes
|
import json
class Config:
'''
Config is a class used to import variables from a JSON config file at runtime.
Attributes:
serverIP (str): IP address of the host computer running the CVSensorSimulator application.
tagID (int): Tag ID number of the AprilTag on this robot.
label (str): This robot's display name.
debug_mode (boolean): Flag enabling debug mode. Debug mode removes calls to Arduino serial port, allows testing in desktop environment.
'''
def __init__(self, filepath):
self.serverIP = "192.168.1.0"
self.tagID = 1
self.label = "Robot1"
self.parse_configs(filepath)
def parse_configs(self, filepath):
with open(filepath, 'r') as jsonFile:
config = json.load(jsonFile)
self.serverIP = config['serverIP']
self.port = config['port']
self.tagID = config['tagID']
self.label = config['label']
self.env = config['env']
self.robotRadius = config['robotRadius']
self.goalTagsRangeStart = config['goalTagsRangeStart']
try:
if(config['goalTag'] >= 0):
self.goalTag = config['goalTag']
print("Goal Tag ({}) Found in Configuration File, Setting Tag Position As Goal!".format(self.goalTag))
else:
raise ValueError
except Exception as e:
print("No Goal Tag Specified in Configuration File, Using Goal From Script!")
self.goalTag = None
|
# This problem was asked by Uber.
# Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
# For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
# Follow-up: what if you can't use division?
current_answer =1
def multiply_array_elements (element_at_index, last_element_at_index) :
premul =1
postmul =1
if (element_at_index != 0):
temp_mul = 1
for j in range (0,element_at_index):
temp_mul = temp_mul * array_of_elements[j]
premul = temp_mul
if (element_at_index != last_element_at_index -1):
temp_mul2 = 1
for k in range (element_at_index + 1,last_element_at_index):
temp_mul2 = temp_mul2 * array_of_elements[k]
postmul = temp_mul2
current_answer = premul * postmul
final_array_of_elements.append(current_answer)
array_of_elements = [1,2,3,4,5]
final_array_of_elements = []
number_of_elements = len(array_of_elements)
if (number_of_elements==0):
print("Length of array too short")
if (number_of_elements==1):
final_array_of_elements = array_of_elements
for i in range (0,number_of_elements):
current_element = array_of_elements[i]
multiply_array_elements(i,number_of_elements)
print ("Final Array is : ")
print(final_array_of_elements)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 13 08:19:03 2020
@author: TokTam
"""
myList = input("Enter a string: ")
abcList=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for i in range(0,26):
print(myList[i]," is: " ,myList.count(abcList[i]))
|
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 26 18:42:45 2020
@author: USER
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode):
s = set()
while head:
if head in s:
return True
s.add(head)
head = head.next
return False
def hasCycleFastSlow(self, head: ListNode):
fast = slow = head
while slow and fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
return True
return False
if __name__ == '__main__':
head = ListNode(3)
node1 = ListNode(0)
node2 = ListNode(2)
node3 = ListNode(-4)
head.next = node1
node1.next = node2
node2.next = node3
s = Solution()
s.hasCycle(head)
print("True" if s.hasCycle(l) else "False")
|
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 22 10:30:31 2020
@author: USER
"""
def permute(nums):
def backtrack(first=0):
# 所有数填完
if first == n:
res.append(nums[:])
for i in range(first, n):
# 做选择
nums[first], nums[i] = nums[i], nums[first]
# 递归下一个数
backtrack(first+1)
# 撤销选择
nums[first], nums[i] = nums[i], nums[first]
n = len(nums)
res = []
backtrack()
return res
|
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 20 15:45:20 2020
@author: USER
"""
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def reverseListIteration(self, head):
pre = None
cur = head
while cur:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
return pre
def reverseListRecursion(self, head):
cur, pre = head, None
while cur:
cur.next, pre, cur = pre, cur, cur.next
return pre
|
# -*- coding: utf-8 -*-
"""
Created on Fri Sep 25 00:35:21 2020
@author: USER
"""
def hasCycle(head, k)
slow = fast = head
while k > 0:
k -= 1
fast = fast.next
// 上面的代码类似 hasCycle 函数
slow = head
while (slow != fast):
fast = fast.next
slow = slow.next
return slow
|
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 2 21:50:10 2020
@author: USER
"""
def searchSmallest(letters, target):
size = len(letters);
l = 0;
r = size - 1;
while (l <= r):
mid = (r + l) // 2
if (target < letters[mid]):
r = mid - 1;
else:
l = mid + 1
return letters[l] if l < r else letters[0]
if __name__ == '__main__':
print(searchSmallest(["c", "f", "j"], 'f'))
|
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import copy
# reading data from csv
def read_data():
df = pd.read_csv("../data/classification.csv", header=None)
X_org = np.array(df.iloc[:, 0:3])
#print(X_org.shape)
X = X_org.reshape(X_org.shape[0],-1).T
#print(X.shape)
Y_org = np.array(df.iloc[:, 3]).T
Y = Y_org.reshape(Y_org.shape[0], -1).T
#print(X_org.shape)
return X, Y
#initializing weights
def initialize_with_zeros(dim):
wt = np.zeros((dim,1))
b = 0
return wt, b
def sigmoid(z):
s = (1 / (1 + np.exp(-z)))
return s
def propagate(X,W,b,Y):
S = np.dot(W.T,X) + b
#A = sigmoid(S)
#print(S.shape)
S[S >= 0.0] = +1
S[S <= 0.0] = -1
#print(S)
# S_list = []
# for i in S:
# for j in i:
# if j < 0.0:
# S_list.append(-1)
# else:
# S_list.append(1)
# S_array = np.array(S_list)
# S = S_array.reshape(S_array[0],-1)
N = X.shape[1]
error = abs(Y - S)
dw = np.dot(X, error.T) / N
#db = np.sum(error) / N
cost = np.sum(error) / N
return dw, error, cost
def main():
X,Y = read_data()
learning_rate = 0.01
no_of_iterations = 1000
#print(X.shape[0])
W, b = initialize_with_zeros(X.shape[0])
#print(W.shape)
for i in range(no_of_iterations):
dw, error, cost = propagate(X,W,b,Y)
W = W - learning_rate * dw
b = b + learning_rate * error
print(cost)
if __name__ == '__main__':
main()
|
"""
# Author: Kwok Moon Ho
# Date: July 14 2020
# Time: 19 mins 42 sec
#Task:
Find non repreated char and arragement
e.g: Bubble -> uleBbb
Quqqltteqa -> uleaQqqttq
Bubbule -> lBuubue
"""
#assume: no empty input and input is string.
def main():
my_dict = {}
my_list = []
user_input = input("Please enter a string: ")
for n in user_input:
if my_dict.get(n.casefold()) == None:
my_dict[n.casefold()] = 1
my_list.append(n)
else:
my_dict[n] += 1
if n.isupper():
if (n in my_list):
my_list.pop(my_list.index(n.upper()))
elif(n.lower() in my_list):
my_list.pop(my_list.index(n.lower()))
elif n.islower():
if n in my_list:
my_list.pop(my_list.index(n.lower()))
elif n.upper() in my_list:
my_list.pop(my_list.index(n.upper()))
#convert user_input ot list
user_list = list(user_input)
for q in my_list:
if q in user_list:
user_list.remove(q)
#combine
answer = my_list + user_list
print("The final answer is: {}".format(''.join(answer)))
if __name__ == "__main__":
main()
|
#!/usr/bin/python3
number_one = int(input("Enter First Number: "))
number_two = int(input("Enter Second Number: "))
addition_numbers = number_one + number_two
number_mean = addition_numbers / 2
print ("The mean of both numbers is: ", number_mean)
|
#!/usr/bin/python3
import pandas as pd
import numpy as np
s = pd.Series(np.random.randn(10))
print (s)
print (s.sample(n=3))
df = pd.DataFrame(np.random.randn(10, 4), columns=list('ABCD'))
print (df)
# remember frac is float, percentage :)
print (df.sample(frac=0.1, replace=True))
|
"""
Module to deal with base operating system.
Programmed by: Dante Signal31
email: [email protected]
"""
import sys
def verify_python_version(major_version, minor_revision):
""" Check if current python interpreter version is what we need.
Compare current interpreter version with the one is provided as needed one.
If not over needed one version abort execution gracefully warning user
she is trying to use an unsupported python interpreter.
:param major_version: Needed major version for Python interpreter.
:type major_version: int
:param minor_revision: Needed minor version for Python interpreter.
:type minor_revision: int
:return: None
"""
if (major_version, minor_revision) > sys.version_info:
message = "This program can only be run on Python {0}.{1} or newer, " \
"you are trying to use Python {2}.{3} instead.\nAborting " \
"execution.".format(major_version, minor_revision,
sys.version_info[0], sys.version_info[1])
sys.exit(message)
|
#
# @lc app=leetcode id=979 lang=python3
#
# [979] Distribute Coins in Binary Tree
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def distributeCoins(self, root: TreeNode) -> int:
ans = 0
def move(root: TreeNode) -> int:
nonlocal ans
if not root: return 0
left, right = move(root.left), move(root.right)
ans = ans + abs(left) + abs(right)
return root.val + left + right - 1
move(root)
return ans
|
#
# @lc app=leetcode id=865 lang=python3
#
# [865] Smallest Subtree with all the Deepest Nodes
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def subtreeWithAllDeepest(self, root: TreeNode) -> TreeNode:
def depth(root):
if not root: return (0, root)
left, right = depth(root.left), depth(root.right)
d = max(left[0], right[0]) + 1
node = root if left[0] == right[0] else (left[1] if left[0] > right[0] else right[1])
return (d, node)
return depth(root)[1]
|
print('программа для расчёта прогресса в днях')
day_start = int(input('введите текущий результат в км.'))
day_success = int(input('введите желаемый результат в км.'))
count = 1
while day_success > day_start:
day_start *= 1.1
count += 1
print(count)
|
import csv
import math
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time
import numpy as np
# read the data
csvfile=open("weightedX.csv", 'r')
x = list(csv.reader(csvfile))
csvfile=open("weightedY.csv", 'r')
y = list(csv.reader(csvfile))
m=len(x)
n=1
x3=[]
y2=[]
for i in range(m):
x3.append(float(x[i][0]))
y2.append(float(y[i][0]))
# normalise the data
meanx=sum(x3)/m
v=0 # variance
for i in range(m):
t=x3[i]-meanx
v+=t*t
v/=m
v=math.sqrt(v)
for i in range(m):
x3[i]=(x3[i]-meanx)/v
x2=[]
for i in range(m):
x2.append(np.array([1,x3[i]]))
X=np.array(x2)
Y=np.array(y2)
xvalues=np.linspace(min(x3),max(x3),100)
plt.ion()
fig=plt.figure()
ax1 = fig.add_subplot(1,1,1)
# plots Training data &
# straight line from linear regression
def pl(th):
ax1.clear()
ax1.scatter(x3, y2, label= "Training Data", color= "r",
marker= ".", s=10)
the=list(th)
yvalues=the[1]*xvalues+the[0]
ax1.plot(xvalues, yvalues, label="Hypothesis function learned",color ='b')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.title('Q2 (a)')
plt.show()
plt.pause(0.001)
# All weights same
# theta= inv(X'*X)*X'*Y
theta = np.dot(np.dot(np.linalg.inv(np.dot(X.T ,X)) , np.transpose(X)) , Y)
print("theta=",theta)
plt.ioff()
pl(theta)
# Part (b)
fig=plt.figure()
ax1 = fig.add_subplot(1,1,1)
# change value of tau for part (c)
tau=0.8
tau2=tau*tau
# plots the hypothesis function learned
def plot_2():
ax1.clear()
ax1.scatter(x3, y2, label= "Training Data", color= "r",
marker= ".", s=10)
# calculate the yaxis values for corresponding xaxis values
yvalues=[]
for i in range(len(xvalues)):
weights=[]
for j in range(m):
c=xvalues[i]-X[j][1]
power=-(c*c)/(2*tau2)
weights.append(math.exp(power))
# convert np array to diagonal matrix
# W is m*m matrix
W=np.diag(np.array(weights))
# theta=inv(X'*W*X)*X'*W*Y
the = np.dot(np.dot(np.dot(np.linalg.inv(np.dot(np.dot(X.T ,W),X)) , X.T), W) , Y)
yvalues.append(the[1]*xvalues[i]+the[0])
ax1.plot(xvalues, yvalues, label="Hypothesis function learned",color ='b')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.title('Q2 tau={}'.format(tau))
plt.show()
plt.pause(0.001)
plt.ioff()
plot_2()
|
#!usr/bin/python3
'''
計算固定中的支出,媽媽每天會將家裡的花費記錄下來,並且計算本週的花費總和
顯示:
請輸入星期1 的支出567
請輸入星期2 的支出456
請輸入星期3 的支出567
請輸入星期4 的支出890
請輸入星期5 的支出345
請輸入星期6 的支出534
請輸入星期日 的支出678
本星期的支出為:4037元
'''
sum = 0;
i = 1;
while(True):
if(i==7):
n = int(input('請輸入星期日的支出:'))
break
else:
output = "請輸入星期" + str(i) + "的支出:"
n = int(input(output))
sum += n
i += 1
print("本星期的支出為:",sum,"元")
|
learning_map_dict= {}
def run():
x = True
while True:
ui()
def ui():
a = input('What do you want to do? \n Select \n "1" to add \n "2" to view: ')
if a == "1":
user_input1 = input('Do You want to add a new skill or add a studied skill? \n Select \n "1" to add new skill \n "2" to add studied skill: ')
if user_input1 == "1":
new_skill = input('Add your new skill:')
learning_map_dict[new_skill] = 0
ui()
elif user_input1 == "2":
studied_skill = input("Add a studied skill:")
learning_map_dict[studied_skill]=1
ui()
else:
print("Invalid Selection")
elif a == "2":
user_input2 = input('Select \n "1" to view all skills \n "2" to view studied skills \n "3" to view unstudied skills \n "4" to view progress: ')
if user_input2 == "1":
print("View All Skills: ")
learning_list=[]
for skill in learning_map_dict.keys():
learning_list.append(skill)
print(learning_list)
|
from random import randint
exp = [
'GVG',
'TGT',
'OG',
'MSG',
'JTU',
'KFT',
'KNC',
'WW',
'BDP',
'RR',
'ROE',
]
num = len(exp)
block = []
while len(block) < 3:
r = randint(0, num)
if r not in block:
block.append(r)
for (b in block):
print(exp[b])
|
"""
Binary Trees
author: Chris Lee
created: October 11, 2013
"""
"""
Implementing Binary Trees
"""
import numpy.random as rand
import itertools
class BinaryTree:
def __init__ (self, depth = 0, parent = None):
self.depth = depth
self.assignValue()
self.parent = parent
self.left = BinaryTree(depth = depth - 1, parent = self) if depth > 0 else None
self.right = BinaryTree(depth = depth - 1, parent = self) if depth > 0 else None
#Assign unique value to node
def assignValue(self):
index = rand.randint(len(uniqueList))
self.value = uniqueList[index]
del(uniqueList[index])
#Find common parent without storing nodes
def getRandomNodes(self, number):
nodes = []
for _ in itertools.repeat(None,number):
node = self
for _ in itertools.repeat(None,rand.randint(self.depth)):
node = node.left if rand.randint(2) == 0 else node.right
nodes.append(node)
return nodes
def commonParent(self, nodes):
print "="*(50 + 2*len(nodes)), "\n Searching for a common parent for nodes:", ",".join([str(x.value) for x in nodes]), "\n", "="*(50 + 2*len(nodes))
#Check Node inputs
if None in [x.parent for x in nodes]:
print "Warning: root node has no parent."
if len(set(nodes)) != len(nodes):
print "Warning: nodes are identical"
#Bring to the same depth
maxDepth = max([x.depth for x in nodes])
while min([x.depth for x in nodes]) != maxDepth:
nodes = [x.parent if x.depth < maxDepth else x for x in nodes]
#Set for uniqueness
nodes = set(nodes)
while len(nodes) > 1:
nodes = set([x.parent for x in list(nodes)])
print "Common Parent:"
return list(nodes)[0]
"""
Printing Binary Trees
Simple Printer - up to 5
"""
def buildTree(self, treeBuilder = dict()):
treeBuilder[self.depth] = treeBuilder.get(self.depth,[]) + [str(self.value)]
treeBuilder = self.left.buildTree(treeBuilder = treeBuilder) if self.left != None else treeBuilder
treeBuilder = self.right.buildTree(treeBuilder = treeBuilder) if self.right != None else treeBuilder
return treeBuilder
def lineBuilder(self,integers, spaces):
tabs = (spaces - sum([len(str(x)) for x in integers]))/(len(integers) + 1)
return "".join([tabs*" " + str(x) for x in integers])
def printTree(self):
printDict = self.buildTree()
spaces = 88
for depth in range(self.depth,0,-1):
print self.lineBuilder(printDict[depth],spaces)
return 1
if __name__ == "__main__":
global uniqueList
depth = 5
uniqueList = range(pow(2,depth + 1))
tree = BinaryTree(depth = depth)
#nodeA,nodeB = tree.getRandomNodes(number = 2)
#print nodeA.value
print "==========================\n Here's the tree!\n=========================="
tree.printTree()
print tree.commonParent(tree.getRandomNodes(number = 5)).value
|
#
##################################################
# Author: Leyla Saadi
# Copyright: Copyright 2020, IAAC
# Credits: [Institute for Advanced Architecture of Catalonia - IAAC, Advanced Architecture group]
# License: Apache License Version 2.0
# Version: 1.0.0
# Maintainer: Leyla Saadi
# Email: [email protected]
# Status: development
##################################################
# End of header section
Arm_desired_distance = 4
Arm_Current_Distance = 6
if Arm_Current_Distance > 10:
print('Move faster')
print('Move 3 Forward')
elif (Arm_Current_Distance > 5) & (Arm_Current_Distance <= 10):
print('Move at the same speed')
print('Move 3 Forward')
elif 5 > Arm_Current_Distance > Arm_desired_distance:
print('Reduce the speed')
if Arm_Current_Distance < 3:
move = (Arm_desired_distance - Arm_desired_distance) / 2
elif Arm_Current_Distance < Arm_desired_distance:
print('STOP')
#If distance is bigger than 10 cm then move faster
#If distance is bigger than 5 cm then move at the same speed
#If distance is between the desired distance and 5cm then reduce the speed
#if distance is less than the desired one then stop
|
##################################################
# Author: Alberto Browne
# Copyright: Copyright 2020, IAAC
# Credits: [Institute for Advanced Architecture of Catalonia - IAAC, Advanced Architecture group]
# License: Apache License Version 2.0
# Version: 1.0.0
# Maintainer: Alberto Browne
# Email: [email protected]
# Status: development
##################################################
print('These are prime numbers: \n')
for i in range(2, 100):
number = 2
prime = True
while prime and number < i:
if i % number == 0:
prime = False
else:
number = 1
if prime:
print(i, 'es primo')
|
import matplotlib.pylab as plt
import datetime
class Solution:
"""This code will import the list models, which contains model objects
created in model.py and graph the solution by calling the function graph.
:param models: list[Model] contain models to be graphed.
Each model will have attributes associated with it such as sol (solution)
and protocol."""
def __init__(self, models, no_graph=False):
self.models = models
self.no_graph = no_graph
self.graph()
def graph(self):
"""Function graph will use the for loop to go through the list of models.
If the model used the two compartment models, it will plot two lines,
which represents the quantity of drugs in the main compartment and the
peripheral compartmentat all time points.
If the model used the three compartment model, the plot contain extra
information, and it will contain an extra line, which will represnt
the quantity of drugs in the third comparment (e.g. subcutaneous
scenario) at all time points. """
for model in self.models:
dose_type = self.get_dose_type(model)
if model.protocol.comps == 2:
model_type = ", IV"
plt.plot(model.sol.t, model.sol.y[0, :],
label=model.protocol.label + model_type + ', ' + dose_type
+ '- q_c')
plt.plot(model.sol.t, model.sol.y[1, :],
label=model.protocol.label + model_type + ', ' + dose_type
+ '- q_p1')
elif model.protocol.comps == 3:
model_type = ", SC"
plt.plot(model.sol.t, model.sol.y[0, :],
label=model.protocol.label + model_type + ', ' + dose_type
+ '- q_o')
plt.plot(model.sol.t, model.sol.y[1, :],
label=model.protocol.label + model_type + ', ' + dose_type
+ '- q_c')
plt.plot(model.sol.t, model.sol.y[2, :],
label=model.protocol.label + model_type + ', ' + dose_type
+ '- q_p1')
plt.legend()
plt.title("The change in drug quantity")
plt.ylabel('drug mass [ng]')
plt.xlabel('time [h]')
now = datetime.datetime.now()
plt.savefig("Outputs/PK-Modelling-" + str(now.strftime("%Y%m%d_%H-%M-%S")) + ".png")
if not self.no_graph:
plt.show()
def get_dose_type(self, model):
if model.protocol.dose_on == 0:
return "Instantaneous"
elif model.protocol.dose_off == 0:
return "Continuous"
else:
return "Intermittent"
|
# Time Complexity : O(logn)
#
# Space Complexity : O(1)
#
# Did this code successfully run on Leetcode : Yes
#
# Any problem you faced while coding this : It took me a lot of time develop get the intution that we can solve this using Binary Serach
#
# Problem Approach
# 1. Check if the first element is the peak or not
# 2. Check if the last element is peak or not
# 2. During each iteration we find mid and move to to the unsorted half of the array. This is followed until we enconter a situation where either (nums[mid] > nums[mid+1]) or (nums[mid] < nums[mid-1])
# /\
# / \
# / \ /\
# / \/ \
class Solution:
def findPeakElement(self, nums: List[int]) -> int:
numslen = len(nums)
if 1 == numslen: # if only one element then there is no peak
return 0
if nums[0] > nums[1]: # The first element is one of the peak (1 0 2 3 5 4)
return 0
if nums[numslen-1] > nums[numslen-2]: # The last element is one of the peak (0 2 3 5 4 6)
return (numslen-1)
start, end = 0, len(nums)-1
while start <= end:
mid = start + (end-start) // 2
if nums[mid] > nums[mid - 1] and nums[mid] > nums[mid + 1]:
return mid
elif nums[mid] < nums[mid - 1]: # mid lies on the right valley of the peak (0 2 5 4 3 6 1)
end = mid-1
else: # mid lies on the left valley of the peak (0 2 3 4 5 6 1)
start = mid+1
|
#!/usr/bin/env python3
import socket
import sys
def printUsage():
print("[ERROR]: Invalid number of arguments!")
print(
"\nUSAGE:\n"+
"______\n\n"+
"$ ./client.py [Host IP to connect to] [port to connect to]\n"+
"[NOTE] You need to be root for using port below 1025\n\n")
sys.exit()
def errorExit():
client_socket.close()
sys.exit()
if len(sys.argv) != 3:
printUsage()
#check if the port number entered by user is numeric or not
try:
port = int(sys.argv[2])
except ValueError:
print("Invalid value of port! Port must be numeric!")
sys.exit()
#host to connect to
host = sys.argv[1]
#creating socket
try:
client_socket = socket.socket(socket.AF_INET , socket.SOCK_STREAM , 0)
except socket.error:
print("Error occured in socket.socket() : " , socket.error)
client_socket = None
sys.exit()
else:
print("[+]TCP IPV4 socket created")
#connecting to server
try:
client_socket.connect((host , port))
except socket.error:
print("Error occured in connect() : " , socket.error)
errorExit()
else:
print("[+]Connected to remote host" , host)
#talking to server
server_message = ""
while True:
try:
server_message = client_socket.recv(1024)
if len(server_message) == 0: #0 bytes received
print("\n\nConnection closed by the server!")
errorExit()
except socket.error:
print("[ERROR]: recv(): " , socket.error)
errorExit()
except:
print("\n[+]Connection closed!")
errorExit()
else:
print("\nThey:")
#data received is of type 'byte'. Decode it in either ASCII or UTF-8
print(server_message.decode("ascii"))
print("\nYou:")
try:
#the data must be sent in the form of byte string and not string
#To convert data to byte string, encode() is used
client_socket.sendall(input().encode())
except socket.error:
print("\n\n[ERROR]: sendall(): " , socket.error)
errorExit()
except:
print("\n[+]You closed the connection!\n")
errorExit()
#closing the socket
client_socket.close()
|
def trim(s):
l=len(s)
if len(s) == 0:
return s
if s[0] != ' ' and s[-1] != ' ':
return s
i=0
while i < len(s)-1 and s[i] == ' ' :
i = i + 1
if s[0] == ' ':
s = s[i:]
j=-1
while len(s) > 0 and len(s) >= abs(j) and s[j] == ' ' :
j = j - 1
if s[-1] == ' ':
s = s[:j+1]
return s
if trim('hello ') != 'hello':
print('测试失败!')
elif trim(' hello') != 'hello':
print('测试失败!')
elif trim(' hello ') != 'hello':
print('测试失败!')
elif trim(' hello world ') != 'hello world':
print('测试失败!')
elif trim('') != '':
print('测试失败!')
elif trim(' ') != '':
print('测试失败!')
else:
print('测试成功!')
|
from datetime import datetime, timedelta, timezone
#获取当前日期和时间
now = datetime.now()
print(now)
print(type(now))
# 获取指定日期和时间
dt = datetime(2018, 8, 13, 16, 51, 33)
print(dt)
#datetime转换为timestamp
ts = dt.timestamp()
print(ts)
# timestamp转换为datetime
t = now.timestamp()
print(datetime.fromtimestamp(t))
print(datetime.utcfromtimestamp(t))
# str转换为datetime
cday = datetime.strptime('2018-8-13 16:58:32', '%Y-%m-%d %H:%M:%S')
print(cday)
# datetime转换为str
now = datetime.now()
print(now.strftime('%a, %b %d %H:%M'))
# datetime加减
now = datetime.now()
print(now)
print(now + timedelta(hours=10))
print(now - timedelta(days=1))
print(now + timedelta(days=2, hours=12))
#本地时间转换为UTC时间
print('本地时间转换为UTC时间')
tz_utc_8 = timezone(timedelta(hours=8))
now = datetime.now()
print(now)
dt = now.replace(tzinfo=tz_utc_8)
print(dt)
#时区转换
print('时区转换')
utc_dt = datetime.utcnow().replace(tzinfo=timezone.utc)
print(utc_dt)
bj_dt = utc_dt.astimezone(timezone(timedelta(hours=8)))
print(bj_dt)
tokyo_dt = utc_dt.astimezone(timezone(timedelta(hours=9)))
print(tokyo_dt)
tokyo_dt2 = bj_dt.astimezone(timezone(timedelta(hours=9)))
print(tokyo_dt2)
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
def run(self):
print('Dog is running...')
def eat(self):
print('Dog is eating...')
class Cat(Animal):
def run(self):
print('Cat is running...')
dog = Dog();
dog.run()
cat = Cat()
cat.run()
def run_twice(aaaaa):
aaaaa.run()
aaaaa.run()
run_twice(dog)
run_twice(cat)
class Tortoise(Animal):
def run(self):
print('Tortoise is running slowly...')
run_twice(Tortoise())
#print(type(dog))
print(isinstance(dog, Dog))
print(isinstance(dog, Animal))
print(isinstance(dog, Cat))
print(dir(Tortoise()))
string = 'AAA20180809bcd'
print(dir(string))
print(string.__len__())
print(string.__contains__('0809'))
print(string.index('0809'))
print(string.upper())
print(dir(dog))
class MyObject(object):
def __init__(self):
self.x = 9
def power(self):
return self.x * self.x
obj = MyObject()
hasattr(obj, 'x')
print(obj.x)
hasattr(obj, 'y')
setattr(obj, 'y', 19)
hasattr(obj, 'y')
print(getattr(obj, 'y'))
print(obj.y)
|
class Vehicle:
def __init__(self, make, model, fuel="gas"):
self.make = make
self.model = model
self.fuel = fuel
def __str__(self):
return f"I drive {self.make} {self.model}. It runs on {self.fuel}."
class Car(Vehicle):
number_of_wheels = 4
class Truck(Vehicle):
number_of_wheels = 6
def __init__(self, make, model, fuel="diesel"):
super().__init__(make, model, fuel)
daily = Vehicle("Subaru", "Crosstrek")
print(daily)
# print("for Class", Vehicle.number_of_wheels)
# print("for Instance", daily.number_of_wheels)
# daily.number_of_wheels = 3
# print("for Class", Vehicle.number_of_wheels)
# print("for this instance (daily)", daily.number_of_wheels)
# Run python in interactive mode (nice for debugging)
# python -i class_example.py
# $ python -i class_example.py
# I drive Subaru Crosstrek. It runs on gas.
# >>> daily = Car("Subaru", "Crosstrek")
# >>> print(f"I drive {daily.make} {daily.model}. It uses {daily.fuel} and drives on {daily.number_of_wheels} wheels.")
# I drive Subaru Crosstrek. It uses gas and drives on 4 wheels.
# >>> truck = Truck("Ford", "F350")
# >>> truck.make
# 'Ford'
# >>> truck.model
# 'F350'
# >>> truck.fuel
# 'diesel'
# >>> type(truck)
# <class '__main__.Truck'>
# >>> type(daily)
# <class '__main__.Car'>
# >>> isinstance(daily, Car)
# True
# >>> isinstance(truck, Truck)
# True
# >>> issubclass(Truck, Vehicle)
# True
# >>> issubclass(Car, Vehicle)
# True
# >>> issubclass(Vehicle, Car)
# False
class GitHubRepo:
def __init__(self, name, language, num_stars):
self.name = name
self.language = language
self.num_stars = num_stars
def __str__(self):
return f"{self.name} is a {self.language} repo with {self.num_stars}."
vue = GitHubRepo(name="Vue", language="JavaScript", num_stars=50000)
print(vue)
|
SUM=0
n=0
status=True
while status == True:
x=float(input())
if x == -1:
status = False
else:
SUM+=x
n+=1
if n==0:
print("No Data")
else:
print(SUM/n)
|
class Card:
def __init__(self, value, suit):
self.value=value
self.suit=suit
self.Index=["3","4","5","6","7","8","9","10","J","Q","K","A","2"]
self.IndexSuit=["club","diamond","heart","spade"]
def __str__(self):
return "("+self.value+" "+self.suit+")"
def next1(self):
if self.IndexSuit.index(self.suit)==3:
if self.Index.index(self.value)==12:
return Card(self.Index[0],self.IndexSuit[0])
else:
return Card(self.Index[self.Index.index(self.value)+1],self.IndexSuit[0])
else:
return Card(self.value,self.IndexSuit[self.IndexSuit.index(self.suit)+1])
def next2(self):
if self.IndexSuit.index(self.suit)==3:
if self.Index.index(self.value)==12:
self.value=self.Index[0]
self.suit=self.IndexSuit[0]
else:
self.value=self.Index[self.Index.index(self.value)+1]
self.suit=self.IndexSuit[0]
else:
self.value=self.value
self.suit=self.IndexSuit[self.IndexSuit.index(self.suit)+1]
n = int(input())
cards = []
for i in range(n):
value, suit = input().split()
cards.append(Card(value, suit))
for i in range(n):
print(cards[i].next1())
print("----------")
for i in range(n):
print(cards[i])
print("----------")
for i in range(n):
cards[i].next2()
cards[i].next2()
print(cards[i])
|
x=int(input())-543
print("29" if (x%4==0 and x%100!=0) or x%400==0 else "28")
|
data=[set([i.strip() for i in input().strip().split()]) for i in range(int(input().strip()))]
if data==[]:
print("0")
print("0")
else:
Union=data[0]
Intersection=data[0]
for i in range(1,len(data)):
Union=Union.union(data[i])
Intersection=Intersection.intersection(data[i])
print(len(Union))
print(len(Intersection))
|
x=int(input())
for i in range(2,(x//2)+1):
st=False
for j in range(2,(i//2)+1):
if i%j == 0 and i!=j :
st=True
if st==False and x%i==0:
print(i,end=" ")
st=False
for i in range(2,(x//2)+1):
if x%i == 0 and x!=i :
st=True
if st==False and x>1:
print(x,end=" ")
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
l = []
def increasingBST(self, root: TreeNode) -> TreeNode:
self.l = []
if not root:return None
self.inorder(root)
self.l = self.l[::-1]
pre = None
for i in self.l:
node = TreeNode(i)
node.right = pre
pre = node
return pre
def inorder(self, root):
if not root:
return None
self.inorder(root.left)
self.l.append(root.val)
self.inorder(root.right)
'''
方法二:中序遍历 + 更改树的连接方式
和方法一类似,我们在树上进行中序遍历,但会将树中的节点之间重新连接而不使用额外的空间。
具体地,当我们遍历到一个节点时,把它的左孩子设为空,并将其本身作为上一个遍历到的节点的右孩子。
'''
class Solution:
def increasingBST(self, root):
def inorder(node):
if node:
inorder(node.left)
node.left = None
self.cur.right = node
self.cur = node
inorder(node.right)
ans = self.cur = TreeNode(None)
inorder(root)
return ans.right
|
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
h = ListNode(None)
ph = h
while head and head.next:
f = False
while head.val == head.next.val:
f = True
head = head.next
if f:
ph.next = head.next
else:
ph.next = head
ph = ph.next
head = head.next
return h.next
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def averageOfLevels(self, root: TreeNode) -> List[float]:
if not root:return []
res = []
cur_level = [root]
while cur_level:
tmp = []
next_level = []
for node in cur_level:
tmp.append(node.val)
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
res.append(tmp)
cur_level = next_level
ans = []
for r in res:
ans.append(sum(r)/len(r))
return ans
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.