text
stringlengths 37
1.41M
|
---|
board = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
# Copy your logic functions from part A below:
# This file contains the core functions needed to validate moves in the Tic Tac Toe game
# Implement each function and choose "Run Tests" from the drop down menu to see how you did.
# Once you pass all the tests, you can move on to the next part of the project (user interaction).
# For all functions, "board" is assumed to be a nested list representing your Tic Tac Toe board.
# The board should be 3x3 and each spot should have an "X", "O" or " " (single space).
# N - is_board_full
# P - Checks if there are any open spaces on the board
# I - board: a 3x3 representation of the board as a nested list
# R - True if the board is full, False if there is at least one open space
def is_board_full(board):
for lists in board:
for item in lists:
if item == " ":
return False
return True
# N - is_valid_move
# P - Checks if a mark can be placed at the location on the board
# I - board: a 3x3 representation of the board as a nested list
# location: an int (1-9) indicating where the user wants to place a mark
# R - True if the location is open on the board, False if it is already taken.
def is_valid_move(board, location):
# Check if location is in range
if location not in range(1, 10):
return False
row = (location - 1) // len(board)
col = (location - 1) % len(board[row])
if board[row][col] == " ":
return True
else:
return False
# N - winning_move
# P - Checks if the previous move resulted in the user winning the game
# I - board: a 3x3 representation of the board as a nested list
# R - True if the user now has 3 marks in a row, False if the user does not
# Old code
'''
for i in range (0,3):
if board[i][i + 1] == "X" or board[i][i + 1] == "O":
return True
elif board[i + 1][i] == "X" or board[i + 1][i] == "O":
return True
elif board[i + 1][i - 1] == "X" or board[i + 1][i - 1] == "O":
return True
elif board[i + 1][i + 1] == "X" or board[i + 1][i + 1] == "O":
return True
return False
'''
def winning_move(board):
# Check for horizontals
for row in range(0, 3):
if board[row][0] == board[row][1] and board[row][1] == board[row][2] and board[row][0] != " ":
return True
# Check for verticals
for col in range(0, 3):
if board[0][col] == board[1][col] and board[1][col] == board[2][col] and board[2][col] != " ":
return True
# Check for diagonals
# Diagonal top left to bottom right
if board[0][0] == board[1][1] and board[1][1] == board[2][2] and board[2][2] != " ":
return True
# Diagonal top right to bottom left
if board[0][2] == board[1][1] and board[1][1] == board[2][0] and board[2][0] != " ":
return True
return False
# Extra Credit: uncomment the following line and implement the function
# N - winning_move_possible
# P - Determines if the game is an inevitable tie or if someone can still win
# I - board: a 3x3 representation of the board as a nested list
# R - True if there's at least one combination of moves that would let a player win, False if the game must tie
# def winning_move_possible(board):
# Write your test code here:
'''
def winning_move_possible():
#still working on it (temporarily moved on to part B)
'''
|
class RadioStation:
def __init__(self, frequency):
self.frequency = frequency
def get_frequency(self):
return self.frequency
class StationList:
def __init__(self):
self.stations = []
self.counter = 0
def add_station(self, station):
self.stations.append(station)
def remove_station(self, to_remove):
to_remove_frequency = to_remove.get_frequency()
self.stations = [s for s in self.stations if
s.get_frequency() != to_remove_frequency]
def count(self):
return len(self.stations)
def current(self):
return self.stations[self.counter]
def key(self):
return self.counter
def next(self):
self.counter += 1
def rewind(self):
self.counter = 0
if __name__ == '__main__':
station_list = StationList()
station_list.add_station(RadioStation(89))
station_list.add_station(RadioStation(101))
station_list.add_station(RadioStation(102))
station_list.add_station(RadioStation(103.2))
for i in range(station_list.count(), 0, -1):
print(station_list.current().get_frequency())
station_list.next()
# 89
# 101
# 102
# 103.2
station_list.remove_station(RadioStation(89))
station_list.rewind()
for i in range(station_list.count(), 0, -1):
print(station_list.current().get_frequency())
station_list.next()
# 101
# 102
# 103.2
|
#%%
# Add the dependencies.
import pandas as pd
import numpy as np
import os
#%%
# Files to load
school_data_to_load = os.path.join("Resources", "schools_complete.csv")
student_data_to_load = os.path.join("Resources", "students_complete.csv")
#%%
# Read the school data file and store it in a Pandas DataFrame.
school_data_df = pd.read_csv(school_data_to_load)
school_data_df
#%%
# Read the student data file and store it in a Pandas DataFrame.
student_data_df = pd.read_csv(student_data_to_load)
student_data_df.head()
#%%
# Determine if there are any missing values in the school data.
school_data_df.count()
# %%
# Determine if there are any missing values in the student data.
student_data_df.count()
# %%
# Determine if there are any missing values in the school data.
school_data_df.isnull()
#%%
# Determine if there are any missing values in the student data.
student_data_df.isnull()
# %%
# Determine if there are any missing values in the student data.
student_data_df.isnull().sum()
# %%
# Determine if there are not any missing values in the school data.
school_data_df.notnull()
# %%
# Determine if there are not any missing values in the student data.
student_data_df.notnull().sum()
#%%
# Determine data types for the school DataFrame.
school_data_df.dtypes
#%%
# Determine data types for the student DataFrame.
student_data_df.dtypes
# %%
# Add each prefix and suffix to remove to a list.
prefixes_suffixes = ["Dr. ", "Mr. ","Ms. ", "Mrs. ", "Miss ", " MD", " DDS", " DVM", " PhD"]
#%%
# Iterate through the words in the "prefixes_suffixes" list and replace them with an empty space, "".
for word in prefixes_suffixes:
student_data_df["student_name"] = student_data_df["student_name"].str.replace(word,"")
#the student_data_df should be clean at this point
student_data_df.head(8)
# %%
# Combine the data into a single dataset.
school_data_complete_df = pd.merge(student_data_df, school_data_df, on=["school_name", "school_name"])
school_data_complete_df.head()
# %%
# Get the total number of students.
student_count = school_data_complete_df["Student ID"].count()
student_count
#%%
# Calculate the total number of schools.
school_count = school_data_df["school_name"].count()
school_count
# %%
# Calculate the total number of schools
school_count_2 = school_data_complete_df["school_name"].unique()
school_count_2
# %%
# Calculate the total budget.
total_budget = school_data_df["budget"].sum()
total_budget
# %%
# Calculate the average reading score.
average_reading_score = school_data_complete_df["reading_score"].mean()
average_reading_score
# %%
# Calculate the average math score.
average_math_score = school_data_complete_df["math_score"].mean()
average_math_score
#%%
passing_math = school_data_complete_df["math_score"] >= 70
passing_reading = school_data_complete_df["reading_score"] >= 70
# %%
# Get all the students who are passing math in a new DataFrame.
passing_math = school_data_complete_df[school_data_complete_df["math_score"] >= 70]
passing_math.head()
#%%
# Get all the students that are passing reading in a new DataFrame.
passing_reading = school_data_complete_df[school_data_complete_df["reading_score"] >= 70]
passing_reading.head()
# %%
# Calculate the number of students passing.
passing_math_count = passing_math["student_name"].count()
print("Math: " + str(passing_math["student_name"].count()))
# Calculate the number of students passing reading.
passing_reading_count = passing_reading["student_name"].count()
print("Reading: " + str(passing_reading["student_name"].count()))
#%%
# Calculate the percent that passed math.
passing_math_percentage = passing_math_count / float(student_count) * 100
print(passing_math_percentage)
#%%
# Calculate the percent that passed reading.
passing_reading_percentage = passing_reading_count / float(student_count) * 100
print(passing_reading_percentage)
#%%
# Calculate the overall passing percentage.
overall_passing_percentage = (passing_math_percentage + passing_reading_percentage ) / 2
print(overall_passing_percentage)
#%%
# Adding a list of values with keys to create a new DataFrame.
district_summary_df = pd.DataFrame(
[{"Total Schools": school_count,
"Total Students": student_count,
"Total Budget": total_budget,
"Average Math Score": average_math_score,
"Average Reading Score": average_reading_score,
"% Passing Math": passing_math_percentage,
"% Passing Reading": passing_reading_percentage,
"% Overall Passing": overall_passing_percentage}])
district_summary_df
# %%
# Format the "Total Students" to have the comma for a thousands separator.
district_summary_df["Total Students"] = district_summary_df["Total Students"].map("{:,}".format)
district_summary_df["Total Students"]
# %%
# Format "Total Budget" to have the comma for a thousands separator, a decimal separator, and a "$".
district_summary_df["Total Budget"] = district_summary_df["Total Budget"].map("${:,.2f}".format)
district_summary_df["Total Budget"]
# %%
# Format the columns.
district_summary_df["Average Math Score"] = district_summary_df["Average Math Score"].map("{:.1f}".format)
district_summary_df["Average Reading Score"] = district_summary_df["Average Reading Score"].map("{:.1f}".format)
district_summary_df["% Passing Math"] = district_summary_df["% Passing Math"].map("{:.0f}".format)
district_summary_df["% Passing Reading"] = district_summary_df["% Passing Reading"].map("{:.0f}".format)
district_summary_df["% Overall Passing"] = district_summary_df["% Overall Passing"].map("{:.0f}".format)
#%%
# Display the Dataframe
district_summary_df
# %%
# Reorder the columns in the order you want them to appear.
new_column_order = ["Total Schools", "Total Students", "Total Budget","Average Math Score", "Average Reading Score", "% Passing Math", "% Passing Reading", "% Overall Passing"]
# Assign district summary df the new column order.
district_summary_df = district_summary_df[new_column_order]
district_summary_df
# %%
# Determine the school type.
per_school_types = school_data_df.set_index(["school_name"])["type"]
per_school_types
#%%
# Add the per_school_types into a DataFrame for testing.
df = pd.DataFrame(per_school_types)
df
# %%
# Calculate the total student count.
per_school_counts = school_data_df["size"]
per_school_counts
# %%
# Calculate the total student count.
per_school_counts = school_data_df.set_index(["school_name"])["size"]
per_school_counts
# %%
# Calculate the total student count.
per_school_counts = school_data_complete_df["school_name"].value_counts()
per_school_counts
# %%
# Calculate the total school budget.
per_school_budget = school_data_df.set_index(["school_name"])["budget"]
per_school_budget
#%%
# Calculate the per capita spending.
per_school_capita = per_school_budget / per_school_counts
per_school_capita
# %%
# Calculate the math scores.
student_school_name = student_data_df.set_index(["school_name"])["math_score"]
student_school_name
#%%
# Calculate the average math scores.
per_school_averages = school_data_complete_df.groupby(["school_name"]).mean()
per_school_averages
#%%
# Calculate the average test scores.
per_school_math = school_data_complete_df.groupby(["school_name"]).mean()["math_score"]
print("Average math scores per school")
print(per_school_math)
print("")
print("Average reading scores per school")
per_school_reading = school_data_complete_df.groupby(["school_name"]).mean()["reading_score"]
print(per_school_reading)
# %%
# Calculate the passing scores by creating a filtered DataFrame.
per_school_passing_math = school_data_complete_df[(school_data_complete_df["math_score"] >= 70)]
per_school_passing_reading = school_data_complete_df[(school_data_complete_df["reading_score"] >= 70)]
#%%
## Calculate the number of students passing math and passing reading by school.
per_school_passing_math = per_school_passing_math.groupby(["school_name"]).count()["student_name"]
per_school_passing_reading = per_school_passing_reading.groupby(["school_name"]).count()["student_name"]
# %%
per_school_passing_math
#%%
per_school_passing_reading
#%%
# Calculate the percentage of passing math and reading scores per school.
per_school_passing_math = per_school_passing_math / per_school_counts * 100
per_school_passing_reading = per_school_passing_reading / per_school_counts * 100
# %%
#By Percentage
per_school_passing_math
#%%
#By Percentage
per_school_passing_math
#%%
# Calculate the overall passing percentage.
per_overall_passing_percentage = (per_school_passing_math + per_school_passing_reading ) / 2
per_overall_passing_percentage
# %%
# Adding a list of values with keys to create a new DataFrame.
per_school_summary_df = pd.DataFrame({
"School Type": per_school_types,
"Total Students": per_school_counts,
"Total School Budget": per_school_budget,
"Per Student Budget": per_school_capita,
"Average Math Score": per_school_math,
"Average Reading Score": per_school_reading,
"% Passing Math": per_school_passing_math,
"% Passing Reading": per_school_passing_reading,
"% Overall Passing": per_overall_passing_percentage})
per_school_summary_df.head()
# %%
# Format the Total School Budget and the Per Student Budget columns.
per_school_summary_df["Total School Budget"] = per_school_summary_df["Total School Budget"].map("${:,.2f}".format)
per_school_summary_df["Per Student Budget"] = per_school_summary_df["Per Student Budget"].map("${:,.2f}".format)
# Display the data frame
per_school_summary_df.head()
# %%
# Reorder the columns in the order you want them to appear.
new_column_order = ["School Type", "Total Students", "Total School Budget", "Per Student Budget", "Average Math Score", "Average Reading Score", "% Passing Math", "% Passing Reading", "% Overall Passing"]
# Assign district summary df the new column order.
per_school_summary_df = per_school_summary_df[new_column_order]
per_school_summary_df.head()
# %%
# Sort and show top five schools.
top_schools = per_school_summary_df.sort_values(["% Overall Passing"], ascending=False)
top_schools.head()
#%%
# Sort and show bottom five schools.
bottom_schools = per_school_summary_df.sort_values(["% Overall Passing"], ascending=True)
bottom_schools.head()
# %%
# Create a grade level DataFrames.
ninth_graders = school_data_complete_df[(school_data_complete_df["grade"] == "9th")]
tenth_graders = school_data_complete_df[(school_data_complete_df["grade"] == "10th")]
eleventh_graders = school_data_complete_df[(school_data_complete_df["grade"] == "11th")]
twelfth_graders = school_data_complete_df[(school_data_complete_df["grade"] == "12th")]
# %%
ninth_graders.head()
#%%
# Group each school Series by the school name for the average math score.
ninth_grade_math_scores = ninth_graders.groupby(["school_name"]).mean()["math_score"]
tenth_grade_math_scores = tenth_graders.groupby(["school_name"]).mean()["math_score"]
eleventh_grade_math_scores = eleventh_graders.groupby(["school_name"]).mean()["math_score"]
twelfth_grade_math_scores = twelfth_graders.groupby(["school_name"]).mean()["math_score"]
#%%
eleventh_grade_math_scores
#%%
# Group each school Series by the school name for the average reading score.
ninth_grade_reading_scores = ninth_graders.groupby(["school_name"]).mean()["reading_score"]
tenth_grade_reading_scores = tenth_graders.groupby(["school_name"]).mean()["reading_score"]
eleventh_grade_reading_scores = eleventh_graders.groupby(["school_name"]).mean()["reading_score"]
twelfth_grade_reading_scores = twelfth_graders.groupby(["school_name"]).mean()["reading_score"]
#%%
twelfth_grade_reading_scores
#%%
# Combine each Series for average math scores by school into single DataFrame.
math_scores_by_grade = pd.DataFrame({
"9th": ninth_grade_math_scores,
"10th": tenth_grade_math_scores,
"11th": eleventh_grade_math_scores,
"12th": twelfth_grade_math_scores})
math_scores_by_grade.head()
#%%
# Combine each Series for average reading scores by school into single DataFrame.
reading_scores_by_grade = pd.DataFrame({
"9th": ninth_grade_reading_scores,
"10th": tenth_grade_reading_scores,
"11th": eleventh_grade_reading_scores,
"12th": twelfth_grade_reading_scores})
reading_scores_by_grade.head()
#%%
# Format each grade column for math.
math_scores_by_grade["9th"] = math_scores_by_grade["9th"].map("{:.1f}".format)
math_scores_by_grade["10th"] = math_scores_by_grade["10th"].map("{:.1f}".format)
math_scores_by_grade["11th"] = math_scores_by_grade["11th"].map("{:.1f}".format)
math_scores_by_grade["12th"] = math_scores_by_grade["12th"].map("{:.1f}".format)
# Make sure the columns are in the correct order.
math_scores_by_grade = math_scores_by_grade[
["9th", "10th", "11th", "12th"]]
# Remove the index name.
math_scores_by_grade.index.name = None
# Display the DataFrame.
math_scores_by_grade.head()
#%%
# Format each grade column for reading.
reading_scores_by_grade["9th"] = reading_scores_by_grade["9th"].map("{:,.1f}".format)
reading_scores_by_grade["10th"] = reading_scores_by_grade["10th"].map("{:,.1f}".format)
reading_scores_by_grade["11th"] = reading_scores_by_grade["11th"].map("{:,.1f}".format)
reading_scores_by_grade["12th"] = reading_scores_by_grade["12th"].map("{:,.1f}".format)
# Make sure the columns are in the correct order.
reading_scores_by_grade = reading_scores_by_grade[
["9th", "10th", "11th", "12th"]]
# Remove the index name.
reading_scores_by_grade.index.name = None
# Display the data frame.
reading_scores_by_grade.head()
# %%
# Get the descriptive statistics for the per_school_capita.
per_school_capita.describe()
#%%
# Cut the per_school_capita into the spending ranges.
spending_bins = [0, 585, 615, 645, 675]
pd.cut(per_school_capita, spending_bins)
#%%
# Count the per_school_capita into the spending ranges.
spending_bins = [0, 585, 630, 645, 675]
per_school_capita.groupby(pd.cut(per_school_capita, spending_bins)).count()
#%%
# Establish the spending bins and group names.
spending_bins = [0, 585, 630, 645, 675]
group_names = ["<$584", "$585-629", "$630-644", "$645-675"]
#%%
# Categorize spending based on the bins.
per_school_summary_df["Spending Ranges (Per Student)"] = pd.cut(per_school_capita, spending_bins, labels=group_names)
per_school_summary_df
#%%
# Calculate averages for the desired columns.
spending_math_scores = per_school_summary_df.groupby(["Spending Ranges (Per Student)"]).mean()["Average Math Score"]
spending_reading_scores = per_school_summary_df.groupby(["Spending Ranges (Per Student)"]).mean()["Average Reading Score"]
spending_passing_math = per_school_summary_df.groupby(["Spending Ranges (Per Student)"]).mean()["% Passing Math"]
spending_passing_reading = per_school_summary_df.groupby(["Spending Ranges (Per Student)"]).mean()["% Passing Reading"]
#%%
# Calculate the overall passing percentage.
overall_passing_percentage = (spending_passing_math + spending_passing_reading) / 2
#%%
overall_passing_percentage
# %%
# Assemble into DataFrame.
spending_summary_df = pd.DataFrame({
"Average Math Score" : spending_math_scores,
"Average Reading Score": spending_reading_scores,
"% Passing Math": spending_passing_math,
"% Passing Reading": spending_passing_reading,
"% Overall Passing": overall_passing_percentage})
spending_summary_df
#%%
# Formatting
spending_summary_df["Average Math Score"] = spending_summary_df["Average Math Score"].map("{:.1f}".format)
spending_summary_df["Average Reading Score"] = spending_summary_df["Average Reading Score"].map("{:.1f}".format)
spending_summary_df["% Passing Math"] = spending_summary_df["% Passing Math"].map("{:.0f}".format)
spending_summary_df["% Passing Reading"] = spending_summary_df["% Passing Reading"].map("{:.0f}".format)
spending_summary_df["% Overall Passing"] = spending_summary_df["% Overall Passing"].map("{:.0f}".format)
spending_summary_df
#%%
# Establish the bins.
size_bins = [0, 1000, 2000, 5000]
group_names = ["Small (<1000)", "Medium (1000-2000)", "Large (2000-5000)"]
#%%
# Categorize spending based on the bins.
per_school_summary_df["School Size"] = pd.cut(per_school_summary_df["Total Students"], size_bins, labels=group_names)
per_school_summary_df.head()
#%%
# Calculate averages for the desired columns.
size_math_scores = per_school_summary_df.groupby(["School Size"]).mean()["Average Math Score"]
size_reading_scores = per_school_summary_df.groupby(["School Size"]).mean()["Average Reading Score"]
size_passing_math = per_school_summary_df.groupby(["School Size"]).mean()["% Passing Math"]
size_passing_reading = per_school_summary_df.groupby(["School Size"]).mean()["% Passing Reading"]
size_overall_passing = (size_passing_math + size_passing_reading) / 2
# %%
# Assemble into DataFrame.
size_summary_df = pd.DataFrame({
"Average Math Score" : size_math_scores,
"Average Reading Score": size_reading_scores,
"% Passing Math": size_passing_math,
"% Passing Reading": size_passing_reading,
"% Overall Passing": size_overall_passing})
size_summary_df
#%%
# Formatting.
size_summary_df["Average Math Score"] = size_summary_df["Average Math Score"].map("{:.1f}".format)
size_summary_df["Average Reading Score"] = size_summary_df["Average Reading Score"].map("{:.1f}".format)
size_summary_df["% Passing Math"] = size_summary_df["% Passing Math"].map("{:.0f}".format)
size_summary_df["% Passing Reading"] = size_summary_df["% Passing Reading"].map("{:.0f}".format)
size_summary_df["% Overall Passing"] = size_summary_df["% Overall Passing"].map("{:.0f}".format)
size_summary_df
#%%
# Calculate averages for the desired columns.
type_math_scores = per_school_summary_df.groupby(["School Type"]).mean()["Average Math Score"]
type_reading_scores = per_school_summary_df.groupby(["School Type"]).mean()["Average Reading Score"]
type_passing_math = per_school_summary_df.groupby(["School Type"]).mean()["% Passing Math"]
type_passing_reading = per_school_summary_df.groupby(["School Type"]).mean()["% Passing Reading"]
type_overall_passing = (type_passing_math + type_passing_reading) / 2
#%%
# Assemble into DataFrame.
type_summary_df = pd.DataFrame({
"Average Math Score" : type_math_scores,
"Average Reading Score": type_reading_scores,
"% Passing Math": type_passing_math,
"% Passing Reading": type_passing_reading,
"% Overall Passing": type_overall_passing})
type_summary_df
# %%
# Formatting
type_summary_df["Average Math Score"] = type_summary_df["Average Math Score"].map("{:.1f}".format)
type_summary_df["Average Reading Score"] = type_summary_df["Average Reading Score"].map("{:.1f}".format)
type_summary_df["% Passing Math"] = type_summary_df["% Passing Math"].map("{:.0f}".format)
type_summary_df["% Passing Reading"] = type_summary_df["% Passing Reading"].map("{:.0f}".format)
type_summary_df["% Overall Passing"] = type_summary_df["% Overall Passing"].map("{:.0f}".format)
type_summary_df
#%%
########## challenge #################
#%%
# Creating a dataframe to hold the new values
altered_school_data_df = school_data_complete_df
# Create for loop to iterate through only 9th graders from Thomas High School
for record in range(len(altered_school_data_df)):
if altered_school_data_df.loc[record].grade == '9th' and altered_school_data_df.loc[record].school_name == 'Thomas High School':
# Math and Reading score replacement with NaN
altered_school_data_df.loc[record,'reading_score']=np.nan
altered_school_data_df.loc[record,'math_score']=np.nan
#%%
altered_school_data_df
#%%
# Calculate the average reading score.
altered_average_reading_score = altered_school_data_df["reading_score"].mean()
altered_average_reading_score
#%%
# Calculate the average math score.
altered_average_math_score = altered_school_data_df["math_score"].mean()
altered_average_math_score
#%%
#Boolean who passed
altered_passing_math = altered_school_data_df["math_score"] >= 70
altered_passing_reading = altered_school_data_df["reading_score"] >= 70
#%%
# Get all the students who are passing math in a new DataFrame.
altered_passing_math = altered_school_data_df[altered_school_data_df["math_score"] >= 70]
# Get all the students who are passing reading in a new DataFrame.
altered_passing_reading = altered_school_data_df[altered_school_data_df["reading_score"] >= 70]
#%%
# Number of Students who passed
# Calculate the number of students passing math.
altered_passing_math_count = altered_passing_math["student_name"].count()
# Calculate the number of students passing reading.
altered_passing_reading_count = altered_passing_reading["student_name"].count()
print("Math: " + str(altered_passing_math_count))
print("Reading: " + str(altered_passing_reading_count))
# %%
#Passing Percentage
# Calculate the percent that passed math.
a_passing_math_percentage = altered_passing_math_count / float(student_count) * 100
af_passing_math_percentage = "{:.2f}".format(a_passing_math_percentage)
print("Math: " + str(af_passing_math_percentage))
# Calculate the percent that passed reading.
a_passing_reading_percentage = altered_passing_reading_count / float(student_count) * 100
af_passing_reading_percentage = "{:.2f}".format(a_passing_reading_percentage)
print("Reading: " + str(af_passing_reading_percentage))
# %%
# Calculate the overall passing percentage.
a_overall_passing_percentage = (a_passing_math_percentage + a_passing_reading_percentage ) / 2
af_overall_passing_percentage = "{:.2f}".format(a_overall_passing_percentage)
print(af_overall_passing_percentage)
# %%
# Charting average math and reading scores per school.
a_per_school_averages = altered_school_data_df.groupby(["school_name"]).mean()
a_per_school_averages
# %%
# Calculate the average test scores.
a_per_school_math = altered_school_data_df.groupby(["school_name"]).mean()["math_score"]
print("Average math scores per school")
print(a_per_school_math)
print("")
print("Average reading scores per school")
a_per_school_reading = altered_school_data_df.groupby(["school_name"]).mean()["reading_score"]
print(a_per_school_reading)
#%%
# Calculate the passing scores by creating a filtered DataFrame.
a_per_school_passing_math = altered_school_data_df[(altered_school_data_df["math_score"] >= 70)]
a_per_school_passing_reading = altered_school_data_df[(altered_school_data_df["reading_score"] >= 70)]
#%%
a_per_school_passing_math
#%%
a_per_school_passing_reading
#%%
# Calculate the number of students passing math and passing reading by school.
a_per_school_passing_math = a_per_school_passing_math.groupby(["school_name"]).count()["student_name"]
a_per_school_passing_reading = a_per_school_passing_reading.groupby(["school_name"]).count()["student_name"]
#%%
a_per_school_passing_math
#%%
a_per_school_passing_reading
# %%
# Calculate the percentage of passing math and reading scores per school.
a_percent_school_passing_math = a_per_school_passing_math / per_school_counts * 100
a_percent_school_passing_reading = a_per_school_passing_reading / per_school_counts * 100
#%%
#Percentaga Passing Math
a_percent_school_passing_math
#%%
#Percentaga Passing Reading
a_percent_school_passing_reading
# %%
# Calculate the overall passing percentage.
a_overall_passing_percentage = (a_percent_school_passing_math + a_percent_school_passing_reading ) / 2
a_overall_passing_percentage
# %%
# Adding a list of values with keys to create a new DataFrame.
new_summary_df = pd.DataFrame({
"School Type": per_school_types,
"Total Students": per_school_counts,
"Total School Budget": per_school_budget,
"Per Student Budget": per_school_capita,
"Average Math Score": a_per_school_math,
"Average Reading Score": a_per_school_reading,
"% Passing Math": a_percent_school_passing_math,
"% Passing Reading": a_percent_school_passing_reading,
"% Overall Passing": a_overall_passing_percentage})
new_summary_df.head()
# %%
# Format the Total School Budget and the Per Student Budget columns.
new_summary_df["Total School Budget"] = new_summary_df["Total School Budget"].map("${:,.2f}".format)
new_summary_df["Per Student Budget"] = new_summary_df["Per Student Budget"].map("${:,.2f}".format)
# Reorder the columns in the order you want them to appear.
a_new_column_order = ["Total Students", "Average Math Score", "Average Reading Score", "% Passing Math", "% Passing Reading", "% Overall Passing","School Type", "Total School Budget", "Per Student Budget"]
# Assign district summary df the new column order.
new_summary_df = new_summary_df[a_new_column_order]
# Display the data frame
new_summary_df.head()
# %%
# Sort and show top five schools.
a_top_schools = new_summary_df.sort_values(["% Overall Passing"], ascending=False)
a_top_schools.head()
# %%
# Sort and show bottom five schools.
a_bottom_schools = new_summary_df.sort_values(["% Overall Passing"], ascending=True)
a_bottom_schools.head()
|
"""
Python program that takes in a spreadsheet of medical terminology and makes flash cards
author: Erica J. Lee
updated: June 13,2016
"""
import random
dict= {
'a(n)':'absence of a major part of the brain, skull, scalp',
'ab':'removal of diseased organ away from the body',
'acr(o)':'increased production of growth hormone in the body',
'ad':'towards the center of the body'}
def flashcard(dict):
key_list = dict.keys()
rand_keys = random.choice(key_list)
print rand_keys, ':', dict[rand_keys]
flashcard(dict)
|
S = "Xavier2.0"
print("True" if len([s for s in S if s.isalnum()]) > 0 else "False")
print("True" if len([s for s in S if s.isalpha()]) > 0 else "False")
print("True" if len([s for s in S if s.isdigit()]) > 0 else "False")
print("True" if len([s for s in S if s.islower()]) > 0 else "False")
print("True" if len([s for s in S if s.isupper()]) > 0 else "False")
|
##large number##
num=[any]
print(num)
num=int(input("num:"))
for i in range(2,num):
if num%i==0:
print("large numer:")
break
else:
print("oh!small number")
|
# s = 'azcbobobegghakl'
vowelCount = 0
for char in s:
if char in ["a", "e", "i", "o", "u"]:
vowelCount += 1
print("Number of vowels: " + str(vowelCount))
|
num=0
while num<=9:
num=num+1
print (num)
|
import turtle;
def janela():
lapis = turtle.Pen()
lapis.color('black', 'blue')
lapis.begin_fill()
for x in range(4):
lapis.forward(50)
lapis.right(90)
lapis.penup()
lapis.left(180)
lapis.pendown()
for x in range(4):
lapis.forward(50)
lapis.left(90)
lapis.penup()
lapis.right(90)
lapis.pendown()
for x in range(4):
lapis.forward(50)
lapis.left(90)
for x in range(4):
lapis.forward(50)
lapis.right(90)
lapis.end_fill()
def porta():
lapis = turtle.Pen()
lapis.color('black', 'brown')
lapis.begin_fill()
for x in range(4):
if x%2==0 :
lapis.forward(50)
else:
lapis.forward(100)
lapis.right(90)
lapis.end_fill()
lapis.right(90)
lapis.penup()
lapis.forward(50)
lapis.left(90)
lapis.forward(10)
lapis.pendown()
lapis.color('black', 'black')
lapis.begin_fill()
lapis.circle(5)
lapis.end_fill()
#janela()
porta()
input()
|
import pygame
import random
import os
import numpy as np
# initialize
pygame.init()
pygame.mixer.pre_init()
pygame.mixer.init()
def init_variables():
"""Initialize all the required variables for the game to start."""
# Game speed
speed = 200
# We add a ticking event for the snake to move automatically
MOVEEVENT = pygame.USEREVENT+1
t = speed
pygame.time.set_timer(MOVEEVENT, t)
# We define basic colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (140, 255, 0)
RED = (255, 0, 0)
BLUE = (137, 207, 240)
# puts the window of the game in the center of the screen
os.environ['SDL_VIDEO_CENTERED'] = '0'
# defines the size of one cell
width = 35
height = width
# number of rows and columns
grid_size = 20
# margin between the different cells of the grid
margin = 1
# Compute the size of the grid
max_x_screen_size = grid_size*(width+margin) + margin
max_y_screen_size = grid_size*(height+margin) + margin
# We give pygame the size of our game window
screen = pygame.display.set_mode((max_x_screen_size, max_y_screen_size))
# inital settings
# snake defines the size of the snake
snake = [1]
# snake moves records all the snake moves
snake_moves = []
# Edit score
score = 0
# If the game is in superspeed mode
superspeed = False
return speed,MOVEEVENT,t,BLACK,WHITE,GREEN,RED,BLUE,width,height,grid_size,margin,max_x_screen_size,max_y_screen_size,screen,snake,snake_moves,score, superspeed
def load_sprites():
"""Load the sprites into the game"""
# We import the mushroom
apple = pygame.image.load("mushroom.jpg")
apple = pygame.transform.scale(apple, (width, height))
apple_rect = apple.get_rect()
# We need to import the bomb image
bomb = pygame.image.load("bomb_2.jpg")
bomb = pygame.transform.scale(bomb, (width, height))
bomb_rect = bomb.get_rect()
return apple,apple_rect, bomb, bomb_rect
def start_music():
"""Start the music"""
# We define the first song
filename = "03 Chibi Ninja.mp3"
volume = 5
# We load the sound
pygame.mixer.music.load(filename) #music player
pygame.mixer.music.set_volume(volume)
pygame.mixer.music.play(-1)
# We load the sound effects
eat_sound = pygame.mixer.Sound("apple-crunch.wav")
boom_sound = pygame.mixer.Sound("boom.wav")
return eat_sound, boom_sound
def show_rendert_txt(text, color, y, font_size):
"""Use to display text in a Game like font
Args:
text (string): text string
color (rgb): rgb color e.g. (255,0,0)
text (string): text string
text (string): text string
Returns:
None
"""
txt_to_display_font = pygame.font.Font('techkr/TECHKR__.TTF', font_size)
txt_to_display = txt_to_display_font.render(text,0,color)
txt_to_display_rect = txt_to_display.get_rect()
txt_to_display_rect.center = (max_x_screen_size/2, y)
txt_to_display_rect.y = y
screen.blit(txt_to_display, txt_to_display_rect)
def intro():
"""Show the intro screen."""
screen.fill(BLACK)
show_rendert_txt("SnakeHSG", (255, 179, 0), 30, 250)
intro = pygame.image.load("snake_intro.png")
intro = pygame.transform.scale(intro, (200, 200))
intro_rect = intro.get_rect()
intro_rect.center = (max_x_screen_size/2, 400)
show_rendert_txt("please press SPACE...", (255, 255, 255), 490, 60)
show_rendert_txt("(C) 2019, Chantal, Anna-Maria, Ylli, Fabio and Mr. Bastien", (255, 255, 255), 670, 40)
screen.blit(intro, intro_rect) # prints/renders the apple on new position
pygame.display.flip()
def game_over():
"""Shows the game_over screen and set the score"""
screen.fill(BLACK) # Change to a black screen
# Show the text
show_rendert_txt("YOU DIED!", (255,0,0), 60, 250)
show_rendert_txt(f"Score {score}", (255,255,255), 260, 80)
show_rendert_txt("Try again?...LOSER!", (255,255,255), 400, 80)
show_rendert_txt("(Y)es?...(N)o?", (255,255,255), 500, 80)
pygame.display.flip()
def show_snake(x_snake,y_snake, snake, snake_moves):
"""Display the snake on the grid
Args:
x_snake (int) : x position of snake
y_snake (int) : y position of snake
snake (list) : snake size
snake_moves (list) : list of past moves of the snake
Returns:
None
"""
# For the size of the snake we draw circle.
for i in range(len(snake)):
# If snake is 1 then it is part of the snake
if snake[i] == 1:
# We define the position of the snake by using the snake_moves at index
pos = (snake_moves[i][0], snake_moves[i][1])
# If it is superspeed the colors are randomly selected, like the star in mario
if superspeed:
red = random.randint(0,255)
green = random.randint(0,255)
blue = random.randint(0,255)
# Else we use standard green shades to color the snake
else:
green = 255
green = green - i * 10
if green < 0:
green = 255
red = 140
blue = 0
pygame.draw.ellipse(screen, (red,green,blue), pygame.Rect(snake_moves[i][0], snake_moves[i][1], width, height))
def show_eyes(pos_eyes_1, pos_eyes_2):
"""Display the eyes of the snake
Args:
pos_eyes_1 (int): position of the first eye
pos_eyes_2 (int): position of the first eye
"""
color_eyes = BLACK
radius = 4
pygame.draw.circle(screen,color_eyes, pos_eyes_1, radius)
pygame.draw.circle(screen,color_eyes, pos_eyes_2, radius)
def show_tongue(x_tongue, y_tongue, width, height):
"""Display the tongue of the snake
Args:
x_tongue (int): x positon of the tongue
y_tongue (int): y positon of the tongue
width (int): width of the tongue
heigh (int): height of the tongue
"""
color_tongue = RED
pygame.draw.rect(screen,color_tongue, pygame.Rect(x_tongue, y_tongue, width, height))
def record_snake_position(x_snake, y_snake):
"""Record the postion of the snake
Args:
x_snake (int): x position of the snake
y_snake (int): y position of the snake
Returns:
snake_moves (list): list of the past snake moves
"""
# We append the moves
snake_moves.append((x_snake,y_snake))
return snake_moves
def show_apple(x_apple,y_apple):
"""Display the apple at given x and y
Args:
x_apple (int) : X position of the apple
y_apple (int) : y position of the apple
"""
apple_rect.x = x_apple
apple_rect.y = y_apple
color_apple = BLACK
def show_obstacle(x_obstacle,y_obstacle):
"""Display the bomb at given x and y
Args:
x_bomb (int) : X position of the bomb
y_bomb (int) : y position of the bomb
"""
bomb_rect.x = x_obstacle
bomb_rect.y = y_obstacle
def show_grid():
"""Display the grid"""
for row in range(grid_size):
for column in range(grid_size):
color = BLACK
pygame.draw.rect(screen,color,[(margin + width) * column + margin,(margin + height) * row + margin,width,height])
# if the postion of the apple and the snake incl. body are the same, then change the x and y positoin of the apple
def create_random_position_apple(snake,snake_moves,grid_size, width, height, margin):
"""Create a new apple at a random position
Args:
snake (list) : list of the body of the snake
snake_moves (list) : list of snake's past moves
grid_size (tuple) : tuple of width / height
height (int) : height of the window size
width (int) : width of the window size
Returns:
x_apple_new (int) : the new apple x position
y_apple_new (int) : the new apple y position
"""
x_apple_new = margin + (random.randint(0,grid_size-1)*(width+margin))
y_apple_new = margin + (random.randint(0,grid_size-1)*(height+margin))
for i in range(len(snake)):
if snake[i] == 1:
if snake_moves==[]:
pass
else:
if (x_apple_new, y_apple_new) in snake_moves:
x_apple_new = margin + (random.randint(0,grid_size-1)*(width+margin))
y_apple_new = margin + (random.randint(0,grid_size-1)*(height+margin))
return x_apple_new, y_apple_new
def create_random_position_obstacle(snake,snake_moves,grid_size, width, height, margin):
"""Create a new bomb at a random position
Args:
snake (list) : list of the body of the snake
snake_moves (list) : list of snake's past moves
grid_size (tuple) : tuple of width / height
height (int) : height of the window size
width (int) : width of the window size
Returns:
x_obstacle_new (int) : the new obstacle x position
y_obstacle_new (int) : the new obstacle y position
"""
x_obstacle_new = margin + (random.randint(0,grid_size-1)*(width+margin))
y_obstacle_new = margin + (random.randint(0,grid_size-1)*(height+margin))
for i in range(len(snake)):
if snake[i] == 1:
if snake_moves==[]:
pass
else:
if (x_obstacle_new, y_obstacle_new) in snake_moves:
x_obstacle_new = margin + (random.randint(0,grid_size-1)*(width+margin))
y_obstacle_new = margin + (random.randint(0,grid_size-1)*(height+margin))
return x_obstacle_new, y_obstacle_new
def update_speed(speed):
"""update the speed of the snake """
pygame.time.set_timer(MOVEEVENT, speed)
def change_music(filename):
"""Changes the background music"""
pygame.mixer.music.stop()
pygame.mixer.music.load(filename) #music player
pygame.mixer.music.play(-1)
def eat_apple_and_define_new(x_head, y_head, x_apple, y_apple, score, grid_size, width, height, margin, snake,snake_moves, speed, eat_sound):
"""Create a new apple at a random position
Args:
x_head (int) : x position of the snake
y_head (int) : y position of the snake
x_apple (int) : y position of the apple
y_apple (int) : y position of the apple
score (int) : current score of the game
grid_size (tuple) : width and height
width (int) : width of a grid bloc
height (int) : height of a grid bloc
margin (int) : margin of a grid
snake (list) : position of the body
snake_moves (list) : past position of the snake's body
speed (int) : game's speed
eat_sound (pygame.Sound) : Eat an apple sound
Returns:
x_apple (int) : the x positon of the apple
y_apple (int) : the y positon of the apple
score (int) : game's score
snake (list) : list of the snake position
snake_moves (list) : the list snake moves
speed (int) : game's speed
"""
if (x_head == x_apple) and (y_head == y_apple):
snake.append(1)
if superspeed:
score +=5
else:
score+=1
if speed > 100:
speed -= 20
update_speed(speed)
eat_sound.play()
x_apple, y_apple = create_random_position_apple(snake, snake_moves, grid_size, width, height, margin)
snake, snake_moves = cut_lenght_of_list(snake, snake_moves)
else:
snake.insert(0,0)
return x_apple, y_apple, score, snake, snake_moves, speed
def cut_lenght_of_list(snake, snake_moves):
snake_new = []
snake_moves_new = []
for i in range(len(snake)):
if snake[i] == 1:
snake_new.append(snake[i])
snake_moves_new.append(snake_moves[i])
return snake_new, snake_moves_new
def reinitialize_game():
# define start position for the snake --> center
rect_xp = int(margin + (grid_size/2*(width+margin)))
rect_yp = int(margin + (grid_size/2*(height+margin)))
# define by how many pixel the snake shall move up, down, left or right when hiting the button (one cell)
rect_change_xp = width+margin
rect_change_yp = width+margin
# defines the size of the snake's tongue
tong_width = 5
tong_height = 15
# defines the position of the snake's tongue depended from the position of the snake
x_tongue = rect_xp + 15
y_tongue = rect_yp + 25
# defines the position of the eyes depended from the position of the snake
pos_eyes_1 = (rect_xp + 10, rect_yp + 10)
pos_eyes_2 = (rect_xp - 10 + width, rect_yp + 10)
# define the initial position of the 1st apple
x_apple_random, y_apple_random = create_random_position_apple(snake, snake_moves, grid_size, width, height, margin)
x_obstacle, y_obstacle = create_random_position_obstacle(snake, snake_moves, grid_size, width, height, margin)
# record inital snake position in the histroy log
snake_moves.append((rect_xp, rect_yp))
# records initial timer (start ticker)
start_ticks=pygame.time.get_ticks()
change_music("03 Chibi Ninja.mp3")
done = False
direction_state = "RIGHT"
do_again = True
gameover = False
return rect_xp,rect_yp,rect_change_xp,rect_change_yp,tong_width,tong_height,x_tongue,y_tongue,pos_eyes_1,pos_eyes_2,x_apple_random,y_apple_random, x_obstacle, y_obstacle, snake_moves,start_ticks,done,direction_state,do_again,gameover
def move_snake(direction, rect_xp, rect_yp):
"""Returns the next move that the snake has to do"""
if direction == "UP":
rect_yp=-rect_change_yp+rect_yp
x_tongue = rect_xp + 15
y_tongue = rect_yp - 5
tong_width = 5
tong_height = 15
pos_eyes_1 = (rect_xp + 10, rect_yp - 10 + height)
pos_eyes_2 = (rect_xp - 10 + width, rect_yp - 10 + height)
return rect_xp, rect_yp, x_tongue, y_tongue, tong_width, tong_height, pos_eyes_1,pos_eyes_2
elif direction == "DOWN":
rect_yp=rect_change_yp+rect_yp
x_tongue = rect_xp + 15
y_tongue = rect_yp + 25
tong_width = 5
tong_height = 15
pos_eyes_1 = (rect_xp + 10, rect_yp + 10)
pos_eyes_2 = (rect_xp - 10 + width, rect_yp + 10)
return rect_xp, rect_yp, x_tongue, y_tongue, tong_width, tong_height, pos_eyes_1,pos_eyes_2
elif direction == "LEFT":
rect_xp = rect_xp - rect_change_xp
x_tongue = rect_xp - 5
y_tongue = rect_yp + 15
tong_width = 15
tong_height = 5
pos_eyes_1 = (rect_xp - 10 + width, rect_yp - 10 + height)
pos_eyes_2 = (rect_xp - 10 + width, rect_yp + 10)
return rect_xp, rect_yp, x_tongue, y_tongue, tong_width, tong_height, pos_eyes_1,pos_eyes_2
else:
rect_xp=rect_change_xp+rect_xp
x_tongue = rect_xp + 25
y_tongue = rect_yp + 15
tong_width = 15
tong_height = 5
pos_eyes_1 = (rect_xp + 10, rect_yp + 10)
pos_eyes_2 = (rect_xp + 10, rect_yp - 10 + height)
return rect_xp, rect_yp, x_tongue, y_tongue, tong_width, tong_height, pos_eyes_1,pos_eyes_2
speed,MOVEEVENT,t,BLACK,WHITE,GREEN,RED,BLUE,width,height,grid_size,margin,max_x_screen_size,max_y_screen_size,screen,snake,snake_moves,score, superspeed = init_variables()
eat_sound, boom_sound = start_music()
apple, apple_rect, bomb, bomb_rect = load_sprites()
rect_xp,rect_yp,rect_change_xp,rect_change_yp,tong_width,tong_height,x_tongue,y_tongue,pos_eyes_1,pos_eyes_2,x_apple_random,y_apple_random, x_obstacle, y_obstacle, snake_moves,start_ticks,done,direction_state,do_again,gameover = reinitialize_game()
intro()
start = False
while done == False:
for event in pygame.event.get(): # check for any events
if event.type == pygame.QUIT:
done = True
# Kill game if snake leaves boundries
if rect_xp>max_x_screen_size or rect_xp<0:
gameover = True
if rect_yp>max_y_screen_size or rect_yp<0:
gameover = True
# Kill game if snake hits its body
if (rect_xp, rect_yp) in snake_moves:
idx = snake_moves.index((rect_xp, rect_yp))
if (snake[idx]) == 1 and (idx < len(snake)-1):
gameover = True
# Kill game if snake hits its obstacle
if (x_obstacle, y_obstacle) == (rect_xp, rect_yp):
boom_sound.play()
pygame.time.delay(1000)
gameover = True
# act upon key events and sets new x and y positions for snake, tongue, eyes
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
start = True
#Ture superspeed on
if event.key == pygame.K_0:
superspeed = True
change_music("superspeed.mp3")
if event.key == pygame.K_1:
change_music("thriller.mp3")
if event.key == pygame.K_2:
change_music("tetris.mp3")
if event.key == pygame.K_3:
change_music("imblue.mp3")
if event.key == pygame.K_4:
change_music("another_one_bites.mp3")
if event.key == pygame.K_5:
change_music("mchammer.mp3")
if event.key == pygame.K_m:
pygame.mixer.music.stop()
# Change the direction state when a key is pressed then the snake moves at ticks.
if event.key == pygame.K_LEFT:
direction_state = "LEFT"
if event.key == pygame.K_RIGHT:
direction_state = "RIGHT"
if event.key == pygame.K_UP:
direction_state = "UP"
if event.key == pygame.K_DOWN:
direction_state = "DOWN"
if event.key == pygame.K_n and gameover == True:
pygame.quit()
if event.key == pygame.K_y and gameover == True:
speed,MOVEEVENT,t,BLACK,WHITE,GREEN,RED,BLUE,width,height,grid_size,margin,max_x_screen_size,max_y_screen_size,screen,snake,snake_moves,score, superspeed = init_variables()
apple, apple_rect,bomb, bomb_rect = load_sprites()
rect_xp,rect_yp,rect_change_xp,rect_change_yp,tong_width,tong_height,x_tongue,y_tongue,pos_eyes_1,pos_eyes_2,x_apple_random,y_apple_random, x_obstacle, y_obstacle, snake_moves,start_ticks,done,direction_state,do_again,gameover = reinitialize_game()
if event.type == MOVEEVENT and start==True: # is called every 't' milliseconds
# If superspeed => Increase the speed
if superspeed == True:
update_speed(50)
rect_xp, rect_yp, x_tongue, y_tongue, tong_width, tong_height, pos_eyes_1,pos_eyes_2 = move_snake(direction_state, rect_xp, rect_yp)
pygame.display.update()
record_snake_position(rect_xp, rect_yp) # adds the latest position to a list (--> snake_move)
x_apple_random, y_apple_random, score, snake, snake_moves, speed = eat_apple_and_define_new(rect_xp, rect_yp,x_apple_random, y_apple_random, score,grid_size, width, height, margin, snake, snake_moves,speed,eat_sound)
if gameover:
game_over()
else:
if start:
screen.fill(pygame.Color('WHITE'))
show_grid()
show_snake(rect_xp,rect_yp, snake, snake_moves)
show_tongue(x_tongue, y_tongue, tong_width, tong_height)
show_eyes(pos_eyes_1, pos_eyes_2)
show_apple(x_apple_random, y_apple_random) # renders new position of apple
screen.blit(apple, apple_rect) # prints/renders the apple on new position
show_obstacle(x_obstacle, y_obstacle)
screen.blit(bomb, bomb_rect) # prints/renders the apple on new position
#show timer & score
font=pygame.font.SysFont("Verdana",30)
time_display=font.render(f"Time: {int((pygame.time.get_ticks()-start_ticks)/1000)} s",1,WHITE)
screen.blit(time_display,(510,0)) #prints the timer on the screen
score_display=font.render(f"Score: {score}",1,WHITE)
screen.blit(score_display,(510,36)) #prints the timer on the screen
score_display=font.render(f"Speed: {1/speed*1000}",1,WHITE)
screen.blit(score_display,(510,72)) #prints the timer on the screen
pygame.display.update()
|
# -*- coding: utf-8 -*-
"""Object to read lines from a stream using an arbitrary delimiter"""
from math import ceil
__all__ = ['ReadLines']
# the default amount of data to read on a buffer fill
DEFAULT_BLOCK_SIZE = 1048756
class ReadLines: # pylint: disable=too-few-public-methods, too-many-instance-attributes
"""Iterator to read lines from a stream using an arbitrary delimiter"""
def peek(self, size=None):
"""Peek into the stream/buffer without advancing the current state
Arguments
---------
size : integer
The amount of data to read
Returns
-------
If size is specified then the returned amount is the same as if the
stream were being peek()'ed directly, i.e. the amount will include upto
the amount requested depending on how much data there is. If size is
omitted or None, the next delimited line will be returned but it will
not be consumed.
"""
if size is None: # request to peek at a line
try:
return self.__next__(consume=False)
except StopIteration:
return ''
buf = self._buf
idx = self._idx
if not self._eof and len(buf) - idx < size:
# the stream is not known to be exhausted and the existing buffer
# will not satisfy the request
read = self._read
block_size = self._block_size
# truncate the buffer
buf = buf[idx:]
self._idx = idx = 0
chunks = []
amount_needed = size - len(buf)
while amount_needed > 0:
# read in the number of blocks necessary to fulfill the request
data = read(ceil(amount_needed / block_size) * block_size)
if not data:
self._eof = True
break
chunks.append(data)
amount_needed = max(amount_needed - len(data), 0)
buf += self._empty.join(chunks)
self._buf = buf
return buf[idx:idx + size]
def __iter__(self):
return self
# pylint: disable=too-many-branches,too-many-locals
def __next__(self, consume=True):
"""Get the next line
Arguments
---------
consume : boolean
Indicator on whether the line is to be consumed
Returns
-------
The next line in the stream
"""
buf = self._buf
eof = self._eof
delimiter = self.delimiter
read = self._read
block_size = self._block_size
# searching starts at the idx
search_idx = idx = self._idx
delimiter_is_fixed = isinstance(delimiter, (str, bytes))
if delimiter_is_fixed:
delimiter_length = len(delimiter)
# if a match is not found then the buffer is expanded and another
# search is performed starting with the new data
# if the delimiter has multiple characters then the possibility
# exists that the delimiter has been split between reads so an
# offset is used to start the search within the buffer that was
# already searched
search_offset = delimiter_length - 1
elif not hasattr(delimiter, 'search'):
raise TypeError('invalid delimiter type: {}'
.format(delimiter.__class__))
while True:
if delimiter_is_fixed:
delimiter_start = buf.find(delimiter, search_idx)
if delimiter_start != -1:
# the length of the delimiter is added to where the
# delimiter starts to get the index of where it ends
end = delimiter_start + delimiter_length
break
else:
result = delimiter.search(buf, # pylint: disable=no-member
search_idx)
if result:
delimiter_start = result.start()
end = result.end()
if end != result.endpos:
# if the match is not at the end of the buffer then it
# is treated as an exact match
break
# if the match is at the end of the buffer then reading
# more could result in a better match
# since a match was found, searching can begin at the point
# where the match started
search_offset = end - delimiter_start
else:
# the delimiter was not found in the buffer
delimiter_start = -1
# the buffer needs to be scanned from the beginning
search_offset = len(buf) - idx
if eof: # no more data is forth-coming
end = len(buf)
if idx < end:
# there is data in the buffer to return
# it is possible that a match exists but an attempt is
# being made to find a better match
if delimiter_start == -1:
# if there was no previous delimiter match then the
# final line contains no delimiter
delimiter_start = end
break
raise StopIteration
# truncate the buffer
buf = buf[idx:]
idx = 0
# searching should commence with the new data that will be added
# to the buffer minus any offset that was previously provided
search_idx = max(len(buf) - search_offset, 0)
# get more data
more = read(block_size)
if not more:
self._eof = eof = True
buf += more
self._buf = buf
# set the _idx attribute to the end of the line being returned if it is
# being consumed otherwise set it to the local idx, which may have been
# updated if data was added to the buffer
self._idx = end if consume else idx
if self.strip_delimiter:
return buf[idx:delimiter_start]
return buf[idx:end]
# pylint: enable=too-many-branches,too-many-locals
def __init__(self, fobj, *, delimiter='\n', strip_delimiter=False,
block_size=DEFAULT_BLOCK_SIZE):
"""
Arguments
----------
fobj : stream
Stream from which to read
delimiter : str, bytes, or regex
Criteria for how a line is terminated
strip_delimiter : boolean
Indicator on whether the delimiter should be included
in a returned line
block_size : integer
Size to use for reading from the stream
Attributes
----------
delimiter : str, bytes, or regex
Criteria for how a line is terminated
strip_delimiter : boolean
Indicator on whether the delimiter should be included
in a returned line
The stream must be opened for reading and should be blocking.
The *delimiter* type should match the mode of *fobj*. If *delimiter* is
str/bytes then the find() method of the internal buffer will be used.
If *delimiter* is regex then its search() method will be used.
The *delimiter* should match one or more characters.
Searching is performed incrementally against blocks read from the
stream. While accommodations are made to allow regex delimiters to
match as much as possible, as would be necessary if matching text is
split between blocks, caution is advised in using regular expressions
that assume all of the text is present during a search.
"""
self._read = fobj.read
self.delimiter = delimiter
self.strip_delimiter = strip_delimiter
self._block_size = block_size
buf = fobj.read(block_size)
self._empty = b'' if isinstance(buf, bytes) else ''
self._buf = buf
self._idx = 0
self._eof = not buf
|
import nltk
from nltk.corpus import wordnet
word = 'suit'
def wordnet_get(word):
x = wordnet.synsets(word)
if x == []:
print('Sorry, we can\'t find this word, you might want to check the spelling')
definition = [i.definition() for i in x]
pos=[p.pos() for p in x]
# synonyms=[s.synonyms() for s in x]
hyponyms=[h.hyponyms()for h in x]
hypernyms=[hpr.hypernyms()for hpr in x]
n=0
number=[n+1 for num in x]
intro = 'The word {} has the following meanings:'.format(word)
everything = [definition, pos, hyponyms, hypernyms, number]
for output in everything:
print('{}{}\n It has the following synonyms:{}\n ' \
'Hypernyms:{}' \
'\n Hyponyms:{}\n'.format(number, definition,'',hypernyms,hyponyms))
print(''.join(output))
wordnet_get(word)
|
def bottles_of_beer():
i = 99
while i > 0:
if i > 1:
print(str(i) + " bottles of beer \n")
else:
print(str(i) + " bottle of beer")
i -= 1
bottles_of_beer()
|
import random
import time
def convert(unconverted_input):
string_user_word = ""
for letter in unconverted_input:
string_user_word += letter
return string_user_word
def letter_duplicates(word, letter): # to enable to guess multiple letters with one guess
start_at = -1
duplicate_list = []
while True:
try:
duplicate_item = word.index(letter, start_at+1)
except ValueError:
break
else:
duplicate_list.append(duplicate_item)
start_at = duplicate_item
return duplicate_list
print("Welcome to Leon Orou's Hangman game! Enjoy!")
random_words = ('alarm', 'apple', 'human', 'chair', 'smile', 'birth', 'brain', 'super', 'breed', 'dream',
'delay', 'enjoy', 'start', 'force', 'funny', 'great', 'heavy', 'image', 'lough', 'level',
'media', 'major', 'offer', 'ocean', 'piece', 'proud', 'score', 'smart', 'think', 'times',
'train', 'video', 'virus', 'write', 'world', 'value')
in_game = True
while in_game:
guess_word = random.choice(random_words)
print('Guess the word!')
attempts_left = 11
converted_user_word = ""
playing = True
guess0 = "_ "
guess1 = "_ "
guess2 = "_ "
guess3 = "_ "
guess4 = "_ "
guess5 = "_ "
while playing:
unconverted_user_word = [guess0, guess1, guess2, guess3, guess4]
print(f"{guess0} {guess1} {guess2} {guess3} {guess4}")
guess = input("Guess a character: ").lower()
if guess in guess_word:
index_list = letter_duplicates(guess_word, guess)
guess_index = index_list
if 0 in guess_index:
guess0 = guess
if 1 in guess_index:
guess1 = guess
if 2 in guess_index:
guess2 = guess
if 3 in guess_index:
guess3 = guess
if 4 in guess_index:
guess4 = guess
unconverted_user_word = [guess0, guess1, guess2, guess3, guess4]
converted_user_word = convert(unconverted_input=unconverted_user_word)
else:
attempts_left -= 1
print(f"Ops! '{guess}' was not a character of the word! Attempts left : {attempts_left}")
if attempts_left < 1:
print("""
You lost all lives, try again?""")
break
if converted_user_word == guess_word:
print(f"{guess0} {guess1} {guess2} {guess3} {guess4}")
print(f"""
Congratulations! You guessed '{guess_word}' right!
You were {attempts_left} attempts close to death!""""")
print('Play again? [y] or [n]')
chosen = False
while not chosen:
play_again = input('>> ')
if play_again == 'y':
print(' ') # for a new line to show that it's a new game
break
if play_again == 'n':
print('Thank you for playing!')
time.sleep(3)
exit()
else:
print('Please enter a valid answer!')
|
# マージO(n)かかっちゃうやつ
class union_find(object):
"""union-find tree"""
def __init__(self, length):
self.length = length
self.unionnumber=0
self.unionlist=[[]]
self.num=list(-1 for i in range(length))
def unite(self,i,j):
if self.num[i]==-1:
if self.num[j]==-1:
self.unionlist[self.unionnumber].extend([i,j])
self.num[i]=self.unionnumber
self.num[j]=self.unionnumber
self.unionnumber+=1
self.unionlist.append([])
else:
tmp=i
i=j
j=tmp
if self.num[i]!=-1:
if self.num[j]!=-1:
if self.num[i]==self.num[j]:
pass
else:
self.unionlist[self.num[i]].extend(self.unionlist[self.num[j]])
tmp=self.num[j]
for k in self.unionlist[self.num[j]]:
self.num[k]=self.num[i]
self.unionlist[tmp]="del"
else:
self.num[j]=self.num[i]
self.unionlist[self.num[i]].append(j)
def same(self,i,j):
return(self.num[i]==self.num[j])
|
#
#
#
'''
A -> B
B -> C
B -> D
B -> E
C -> B
D -> B
E -> B
'''
graph = {'Birth Spring': ['B'],
'B': ['C', 'D', 'E'],
'C': ['B'],
'D': ['B'],
'E': ['B']}
def find_path(graph, start, end, path=[]):
path = path + [start]
if start == end:
print "no need"
return path
if not graph.has_key(start):
return None
for node in graph[start]:
if node not in path:
newpath = find_path(graph, node, end, path)
if newpath: return newpath
return None
int1 = 0
int2 = 0
int3 = 0
class Player(object):
trav = 0
def __init__(self):
self.location = 'Birth Spring'
def where(self):
print "Currently in %s" % self.location
'''def go(self, graph, start, end, path=[]):
global int3
int3 += 1
print int3
path = path + [start]
if start == end:
print "You're there!"
self.location = end
return path
if not graph.has_key(start):
print "graph has key"
return None
for node in graph[start]:
global int1
int1 += 1
print "for iter: %s" % int1
if node not in path:
global int2
int2 += 1
print "if iter: %s" % int2
newpath = self.go(graph, node, end, path)
if newpath: return newpath
return None
'''
def look(self):
start = self.location
if not graph.has_key(start):
print "graph doesn't have key error"
return None
print "Nearby accessible locations: "
for node in graph[start]:
print node
def go(self, end, path=[]):
start = self.location
path.append(start)
if start == end:
print "You are there."
return path
if not graph.has_key(start):
print "graph doesn't have key error"
return None
for node in graph[start]:
print "Debug: %s" % node
if node in end:
print "Going to %s" % node
self.location = node
break
p = Player()
|
import requests
import json
def main():
url = "https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22"
# Requests will allow you to send HTTP requests using Python.
read = requests.get(url)
# Json converts the variable read which contains the URL into a format which
# can be read and interpreted by python.
api = json.loads(read.content)
cordinates = api["coord"]
quality = api["weather"]
trial = quality[0]
weather = trial["description"]
# By extracting relevant information from the api, we can finally print
# out the result.
print("Cordinates: " + str(cordinates) + " " + "Air Quality:" + " " + str(weather))
if __name__== "__main__":
main()
|
#Linklist
class Node():
def __init__(self,data, next_node=None):
self.data = data
self.next = next_node
def append_node(self, data):
if self.next == None:
self.next = Node(data)
return
self.next.append_node(data)
def insert_node(self,index, data):
if index == 1:
new = Node(data)
new.next = self.next
self.next = new
return
if self.next == None:
self.next = Node(data)
return
self.next.insert_node(index-1, data)
def pop(self, index):
if self.next == None:
raise IndexError('LinkList index out range')
if index == 1:
node = self.next
self.next = node.next
node.next = None
return node.data
self.next.pop(index-1)
def __len__(self):
if self.next == None:
return 1
return 1 + len(self.next)
def __contains__(self,key):
if self.data == key:
return True
if self.next == None:
return False
return key in self.next
def find_max(self):
if self.next == None:
return self.data
curr_max = self.next.find_max()
if curr_max < self.data:
return self.data
return curr_max
def reverse(self):
if self.next == None:
return self
head_node = self.next.reverse()
self.next.next = self
self.next = None
#head_node.append_node(self.data) #build new node
return head_node
def __repr__(self):
if self.next == None:
return str(self.data) + ' -> None'
s = str(self.data) + ' -> '
return s + str(self.next)
#############################################################################
class LinkNode():
def __init__(self,data,next_node=None):
self.data = data
self.next = next_node
class LinkList():
def __init__(self):
self.head = None
def append(self, data):
if self.head == None:
self.head = LinkNode(data)
return
curr = self.head
while curr.next != None:
curr = curr.next
curr.next = LinkNode(data)
def insert(self, index, data):
if self.head == None:
self.head = LinkNode(data)
return
if index == 0:
old = self.head
new = LinkNode(data)
new.next = old
self.head = new
return
parent = self.head
curr = self.head.next
while curr != None and index != 1:
parent = curr
curr = curr.next
index -= 1
new = LinkNode(data)
parent.next = new
new.next = curr
def remove(self, data):
if self.head == None:
return
if self.head.data == data:
old = self.head
self.head = self.head.next
old.next = None
return
parent = self.head
curr = self.head.next
while curr != None:
if curr.data == data:
parent.next = curr.next
curr.next = None
return
parent = curr
curr = curr.next
def pop(self, index):
if self.head == None:
raise IndexError("Linklist index out range")
if index == 0:
old = self.head
self.head = old.next
old.next = None
return old.data
parent = self.head
curr = self.head.next
curr_index = 1
while curr != None:
if curr_index == index:
parent.next = curr.next
curr.next = None
return curr.data
parent = curr
curr = curr.next
curr_index += 1
raise IndexError("Linklist index out range")
def __len__(self):
t = 0
if self.head == None:
return t
curr = self.head
while curr != None:
curr = curr.next
t += 1
return t
def __contains__(self,key):
if self.head == None:
return False
curr = self.head
while curr != None:
if curr.data == key:
return True
curr = curr.next
return False
def find_min(self):
if self.head == None:
return None
curr = self.head
min_v = curr.data
while curr != None:
if curr.data < min_v:
min_v = curr.data
curr = curr.next
return min_v
def reverse(self):
if self.head == None:
return
head = None
curr = self.head
while curr != None:
curr_next = curr.next
curr.next = head
head = curr
curr = curr_next
self.head = head
def __repr__(self):
if self.head == None:
return 'None'
s = ''
curr = self.head
while curr != None:
s += str(curr.data) + ' -> '
curr = curr.next
s += 'None'
return s
ll = LinkList()
ll.append('a')
ll.append('b')
ll.append('c')
ll.append('b')
ll.append('d')
#####################################\
def merge(n1,n2): # l1 and l2 are node
if n1 == None:
return n2
elif n2 == None:
return n1
new_n1 = n1.next
new_n2 = n2.next
head = n1
n1.next = n2
n2.next = merge(new_n1,new_n2)
return head
|
import random
#1
def load_map(filename):
'''
(str) -> list of lists
Read data from the file with the given filename
and return it as a nested list of strings.
e.g. if the file had a map like this:
1 2 5
3 -1 4
this function would return [['1','2','5'], ['3','-1','4']]
The given 'filename' is a string that gives name of text file
in which map data is located. Remember, you have to open the
file with this filename first before you can read it.
'''
acc= []
f = open(filename)
line = f.readline()
while line:
lst = line.strip().split()
acc.append(lst)
line = f.readline()
f.close()
return acc
def mapfile_hight(filename):
f = open(filename)
acc = 0
line = f.readline()
while line != '':
acc += 1
line = f.readline()
return acc
def mapfile_width(filename):
f = open(filename)
acc = 0
lst = f.readline().strip().split()
for item in lst:
if item != '':
acc += 1
return acc
#2 done
def generate_map(map_data, p_x, p_y, player_id):
'''
(list of lists, int, int, str) -> list of lists, dict
Given a list of lists representing map data, generate
and return the following:
(1) a list of lists that provides a visual representation
of the map, and
(2) a dictionary where the keys are tuples of two ints that are
(x, y) coordinates, and the associated values are the int location
ids that are at that position.
In the visual representation, each blank space should be
(_), every blocked area (represented as -2 in the map data)
should be (x), and the player's location at (p_x, p_y) should be
(*) where * is actually the player's id.
e.g.
if the player_id was the letter 's' and
if the original map file had a map like this:
1 2 -2
3 -1 4
the map data would be [['1','2','-2'], ['3','-1','4']]
and its visual representation would be:
[['(s)','(_)','(x)'],['(_)','(_)','(_)']]
and the coordinates dictionary would be:
{(0, 0): 1, (0, 1): 3, (1, 0): 2, (1, 1): -1, (2, 0): -2, (2, 1): 4}
'''
map_visual = []
map_coors = {}
for i in range(len(map_data)):
map_visual.append([])
for i2 in range(len(map_data[i])):
if map_data[i][i2] == '-2':
map_visual[i].append('(x)')
else:
map_visual[i].append('(_)')
map_visual[p_y][p_x] = '(' +player_id +')'
for index in range(len(map_data)):
for ind in range(len(map_data[0])):
key = (ind,index)
map_coors[key] = float(map_data[index][ind])
return map_visual, map_coors
#3 done!!!!!!
def load_items(filename):
'''
(str) -> dict
Read data from the file with the given filename and
create and return a dictionary with item data, structured
as described in the assignment handout, Part 2 Section III.
'''
acc= {}
f = open(filename)
line = f.readline()
while line:
lst = line.strip().split(',')
acc[lst[0]] = lst[1:]
line = f.readline()
f.close()
return acc
#4 done!!!!!!!!
def load_locations(filename):
'''
(str) -> dict
Read data from the file with the given filename and create
and return a dictionary with location data, structured as
described in the assignment handout, Part 2 Section III.
'''
Dict = {}
f = open(filename)
line = f.readline().strip()# output is 0
new_key = float(line) #new_key = 0
line = f.readline() #begin description
while line:
line = line.strip('\n')
if line == '[BEGIN DESCRIPTION]':
line = f.readline().strip()#description
acc = []
acc.append(line)
acc.append([]) #acc = [description,[]]
line = f.readline().strip()#end description
line = f.readline().strip()#either new ID or begin action #the func.
if line == '[BEGIN ACTIONS]':#begin action
line = f.readline() #first action
while line != '[END ACTIONS]':#use loop to get every line of actions
lst = line.strip().split(',')
lst[1] = float(lst[1])
acc[1].append(tuple(lst))#acc = [description,[(action,ID)]]
Dict[float(new_key)] = acc #{0:[action,[(description,ID)]]}
line = f.readline().strip()#end actions # how to get to 2.1 and loop
line = f.readline().strip() #2.1
new_key = line
line = f.readline()#begin description
elif line != '[BEGIN ACTIONS]': #new id, 1
Dict[float(new_key)] = acc
new_key = line.strip()# 1,2
line = f.readline()
f.close()
return Dict
#5 done!!!!!
def get_indices(lst, elm):
'''
(list of lists, object) -> tuple of two ints
Given a list of lists and an element, find the first
pair of indices at which that element is found and return
this as a tuple of two ints. The first int would be the
index of the sublist where the element occurs, and the
second int would be the index within this sublist where
it occurs.
>>> get_indices([[1, 3, 4], [5, 6, 7]], 1)
(0, 0)
>>> get_indices([[1, 3, 4], [5, 6, 7]], 7)
(1, 2)
'''
for i1 in range(len(lst)):
for i2 in range(len(lst[i1])):
if elm == lst[i1][i2]:
return(i1,i2)
#6 done!!
def update_map(map_visual, map_coors, player_id, px, py, dx, dy):
'''
(list of lists, dict, str, int, int, int, int) -> None or tuple of two ints
This function is very similar to update_grid from
Part 1, but there are few IMPORTANT differences.
Read the description below carefully!
Given the player's current position as px and py,
and the directional changes in dx
and dy, update "map_visual" to change the player's
x-coordinate by dx, and their y-coordinate by dy.
The player's position should be represented as (*)
where * is their given player id.
Notes:
This time, we don't have a w and h representing the grid,
as the map's width and height may vary depending on the
file that we read. So, you should figure out the width
and height using the len function and the given map_visual.
If the move is NOT valid (not within the map's area) OR
it would involve moving to a coordinate in which the
location ID is -2 (which is the ID representing all
inaccessible locations), then NO change occurs to the map_visual.
The map_visual stays the same, and nothing is returned.
If the move IS possible, the grid is updated just like it was
for Part 1, and the new x- and y- coordinates of the player
are returned as a tuple.
'''
if px + dx >= len(map_visual[0]) or px +dx < 0 or \
py + dy >= len(map_visual) or py + dy < 0:
return (px,py)
elif map_visual[py+dy][px+dx] == '(x)':
return (px,py)
else:
map_visual[py][px] = '(_)'
map_visual[py+dy][px+dx] = '(' +player_id +')'
return(px+dx,py+dy)
#7 done!
def check_items(current_location, game_items, inventory):
'''
(int, dict) -> None
Given an int location id and a dict of game items where the keys are the
item names, and the values are lists with the following
information in this order: [description of item, starting
location where item is found, location where item should be
dropped of], check if any of the game items are found in the current
location provided. If they are, add them to the inventory.
You should be modifying the variable 'inventory',
within this function, and NOT returning anything.
'''
keys = list(game_items.keys())
values = list(game_items.values())
index = None
for i in range(len(values)):
if float(current_location) == float(values[i][1]) or \
float(current_location) == float(values[i][2]):
index = i #to record the index
if index != None:
if keys[index] not in inventory:
inventory = inventory.append(keys[index])
#8
def check_game_won(game_data, inventory, p_x, p_y):
'''
(dict, list, int, int) -> bool
Return True iff the player is at the goal location, and all
goal items are in the player's inventory.
'''
for item in list(game_data["game_items"].keys()):
if item not in inventory:
return False
if game_data["goal_location"][0] == p_y and \
game_data["goal_location"][1] == p_x:
return True
#9
def do_action(decision, game_data, current_location, inventory):
'''
(int, dict, float, list) -> str
Given the game data dict, and the current location ID, get
all the possible actions at that location.
If the decision number given as 'decision' falls outside the number
of allowed actions at this location, then return the string
"Invalid decision. Please select choice from the decisions listed."
Make sure this string is EXACTLY as above.
Else, if the decision is valid, then figure out the location information
of the new location ID that the player should end up at after
doing this decision (use game_data, current_location, and the decision
chosen to figure this out).
Check for any items at this new location and add to inventory (remember you
can call already existing functions to make your code shorter
and less repetitive).
Return the text description of the new location ID where you end up
after doing this action (e.g. the same way that visit_location function
returns text description of visited location).
'''
for key in game_data["location_data"]:
if current_location == key:
new_key = key
values = game_data["location_data"][new_key]
if decision > len(values[1]):
return "Invalid decision. Please select choice from the decisions listed."
elif decision <= len(values[1]):
new_location_id = values[1][decision-1][1]
check_items(new_location_id, game_data["game_items"], inventory)
return game_data["location_data"][new_location_id][0]
# --------------------------------------------------------------------------------------#
# --- EVERYTHING BELOW IS COMPLETED FOR YOU. DO NOT MAKE CHANGES BEYOND THIS LINE. ---- #
# --------------------------------------------------------------------------------------#
def check_inventory(inventory):
'''
(list) -> None
Print out the contents of the inventory.
NOTE:
THIS FUNCTION IS ALREADY COMPLETE.
YOU DO NOT NEED TO CHANGE THIS FUNCTION.
'''
if len(inventory) == 0:
print("You have nothing in" \
"your inventory.")
print("Items in your inventory: " + str(inventory))
def visit_location(game_data, current_location):
'''
(dict, int) -> str
Visit the current location data by printing out the map,
checking if any items are found at that location,
and then returning the text associated with this current location.
NOTE:
THIS FUNCTION IS ALREADY COMPLETE.
YOU DO NOT NEED TO CHANGE THIS FUNCTION.
'''
print_map(game_data["map_visual"])
check_items(current_location, game_data["game_items"], inventory)
return game_data["location_data"][current_location][0]
def show_actions(actions):
'''
(list) -> None
Given a list of special actions, print out all these actions (if any),
and other basic actions that are possible.
NOTE:
THIS FUNCTION IS ALREADY COMPLETE.
YOU DO NOT NEED TO CHANGE THIS FUNCTION.
'''
print("-------------------------")
for i in range(len(actions)):
print(i+1, actions[i][0])
print("Type N, S, E, or W to move, or inventory to check inventory. Type quit to exit the game.")
print("-------------------------")
def print_map(map_data):
'''
(list of lists) -> None
Print out the map represented by the given list of lists map_data.
NOTE:
THIS FUNCTION IS ALREADY COMPLETE.
YOU DO NOT NEED TO CHANGE THIS FUNCTION.
'''
s = ''
for row in range(len(map_data)):
s += ''.join(location for location in map_data[row]) + "\n"
print(s)
def get_moves(d):
'''
(str) -> tuple of two ints
Given a direction that is either 'N', 'S', 'E' or 'W'
(standing for North, South, East or West), return
a tuple representing the changes that would occur
to the x- and y- coordinates if a move is made in that
direction.
e.g. If d is 'W', that means the player should move
to the left. In order to do so, their x-coordinate should
decrease by 1. Their y-coordinate should stay the same.
These changes can be represented as the tuple (-1, 0),
because the x-coordinate would have -1 added to it,
and the y-coordinate would have 0 added to it.
>>> get_moves('W')
(-1, 0)
>>> get_moves('E')
(1, 0)
NOTE:
THIS FUNCTION IS ALREADY COMPLETE.
YOU DO NOT NEED TO CHANGE THIS FUNCTION.
'''
if (d == "N"):
return (0,-1)
elif (d == "S"):
return (0,1)
elif (d == "E"):
return (1,0)
else:
return (-1,0)
def print_help():
'''
() -> None
Print out possible decisions that can be made.
This function is called if the user provides an invalid decision.
NOTE:
THIS FUNCTION IS ALREADY COMPLETE.
YOU DO NOT NEED TO CHANGE THIS FUNCTION.
'''
print("Type N, S, E or W to move North, South, East or West. \n" \
"Type inventory to check inventory. \n" \
"Type quit to quit the game.")
print("If special actions are listed, you may type the number beside that action to choose that action.")
def set_game_data(map_file, item_file, location_file):
'''
(str, str, str) -> dict
Read data from the given files and return a dictionary
of all game data.
NOTE:
THIS FUNCTION IS ALREADY COMPLETE.
YOU DO NOT NEED TO CHANGE THIS FUNCTION.
'''
map_data = load_map(map_file)
map_visual, map_coors = generate_map(map_data, p_x, p_y, player_id)
game_items = load_items(item_file)
location_data = load_locations(location_file)
# The lines below use list comprehensions again!
# As stated in Part 1 starer code, this is not covered in 108
# but I'm showing this to you anyway because it can come in handy for shortening code.
# You can achieve the same thing without using this technique though, so no worries
# if you're not fully comfortable with it.
# More info here about what this means: http://blog.teamtreehouse.com/python-single-line-loops
game_overs = [k for k, v in location_data.items() if v[0].lower().startswith("game over")]
goal_items = [k for k, v in game_items.items() if v[2] == -1]
goal_location = get_indices(map_data, "-1")
return {"map_data": map_data, "map_visual": map_visual, "map_coors": map_coors,
"game_items": game_items, "location_data": location_data,
"goal_items": goal_items, "goal_location": goal_location,
"game_overs": game_overs, "won": False, "lost": False}
# ==== Finish the functions above according to their docstrings ==== #
# ==== The program starts here. ==== #
# ==== Do NOT change anything below this line. ==== #
if __name__ == "__main__":
player_id = input("Choose any letter other than 'x' to represent you: ")
while len(player_id) != 1 or not player_id.isalpha() or player_id.lower() == 'x':
print("Invalid input.")
player_id = input("Choose any letter other than 'x' to represent you: ")
# initialize current player info
w = mapfile_hight('map.txt')
h = mapfile_width('map.txt')
p_x = random.randint(0,w-1)
p_y = random.randint(0,h-1)
# player's starting point will be randomized on the map.
inventory = []
game_data = set_game_data("map.txt", "items.txt", "locations.txt")
# show map and location data
current_location = game_data["map_coors"][(p_x, p_y)]
result = visit_location(game_data, current_location)
while not game_data["won"] and not game_data["lost"]:
show_actions(game_data["location_data"][current_location][1])
decision = input("What do you want to do? > ")
if decision.upper() in 'NSEW':
dx, dy = get_moves(decision.upper())
new_xy = update_map(game_data["map_visual"], game_data["map_coors"], player_id, p_x, p_y, dx, dy)
if not new_xy:
print("You can't go there.")
else:
p_x, p_y = new_xy
current_location = game_data["map_coors"][(p_x, p_y)]
result = visit_location(game_data, current_location)
print(result)
elif decision.isdigit():
result = do_action(int(decision), game_data, current_location, inventory)
print(result)
elif "inventory" in decision:
check_inventory(inventory)
elif decision == 'quit':
print('Game Over!')
exit(1)
game_data["lost"] = result.lower().startswith("game over")
game_data["won"] = check_game_won(game_data, inventory, p_x, p_y)
if game_data["won"]:
print("Congratulations! You found your way back home!")
|
Handout, Question 1
class Node:
def __init__(self, value):
self.value = value
self.next = None
a = Node(4)
a.next = Node(5)
b = Node(6)
c = a.next
c.next = b
The resulting list is:
4->5->6->None
Variable 'a' refers to the head of this list.
-----
Handout, Question 2
class Node:
def __init__(self, value):
self.value = value
self.next = None
def mystery1(lnk): # purpose???
while lnk and lnk.next:
lnk.next = lnk.next.next
lnk = lnk.next
Purpose of mystery1:
lnk is left with only the final element
lnk ends up with the final element or is empty.
lnk is left with only the third element.
If lnk has even number of elements, it ends up empty; if odd number of elements, only last element is left.
The above are all incorrect!
Correct ones:
Alternate between dropping and keeping the list elements. (OK, but not precise enough.)
Remove every element with an odd index. (Indexes aren't well-defined for linked lists...)
I would say that the next two are best:
Starting from the second element in linked list lnk, remove every other element.
Remove elements 2, 4, 6, 8, ... from the linked list lnk
def mystery2(lnk): # purpose???
if not lnk:
return
lnk = lnk.next
start = lnk
while lnk and lnk.next:
lnk.next = lnk.next.next
lnk = lnk.next
return start
What does mystery2 do:
Starting from the first element of linked list lnk,
remove every other element. Return the beginning of the linked list.
One final question: why doesn't mystery1 have a return, but mystery2 does???
#第二个是变成了2 4 6 8,return start, start就被重新赋值了新的linked list,1就直接不要了
-----
Handout, Question 3
The reverse function is correct! Take some time to understand it.
A few traces should help give you the intuition/insight into why it works.
|
# This question ended up being a bit too tricky in light of the test 1 grades
# I accepted the 'helper' code as a correct solution
# even though it does not always place chr correctly.
# But as a student has asked for the full deal, here it is
# The full solution removes chr, permutes the string,
# then puts chr in the proper place
def divide(s: str, chr: str) -> str:
'''
Precondition: chr is a character that appears in string s.
Precondition: Every character in s is unique and lowercase.
Return a new string where all characters that are alphabetically less
than chr come first, then chr, then all characters alphabetically
greater than chr.
>>> divide('jkldcf', 'f')
'dcflkj'
>>> divide('xyzdabc', 'd')
'abcdzyx'
>>> divide('abde', 'b')
'abed'
'''
index = s.find(chr)
s = s[:index] + s[index+1:]
s = helper(s, chr)
i = 0
while i < len(s) and s[i] < chr:
i = i + 1
return s[:i] + chr + s[i:]
def helper(s, chr):
if s == '':
return s
if s[0] < chr:
return s[0] + helper(s[1:], chr)
else:
return helper (s[1:], chr) + s[0]
import doctest
doctest.testmod()
|
"""Test module Queue.
Authors: Francois Pitt, January 2013,
Danny Heap, September 2013, February 2014
"""
import unittest
from linked_list import Queue
class EmptyTestCase(unittest.TestCase):
"""Test behaviour of an empty Queue.
"""
def setUp(self):
"""Set up an empty queue.
"""
self.queue = Queue()
def tearDown(self):
"""Clean up.
"""
self.queue = None
def testIsEmpty(self):
"""Test is_empty() on empty Queue.
"""
self.assertTrue(
self.queue.is_empty(),
'is_empty returned False on an empty Queue!')
class SingletonTestCase(unittest.TestCase):
"""Check whether enqueueing a single item makes it appear at the front.
"""
def setUp(self):
"""Set up a queue with a single element.
"""
self.queue = Queue()
self.queue.enqueue('a')
def tearDown(self):
"""Clean up.
"""
self.queue = None
def testIsEmpty(self):
"""Test is_empty() on non-empty Queue.
"""
self.assertFalse(
self.queue.is_empty(),
'is_empty returned True on non-empty Queue!')
def testFront(self):
"""Test front() on a non-empty Queue.
"""
front = self.queue.front()
self.assertEqual(
front, 'a',
'The item at the front should have been "a" but was ' +
front + '.')
def testDequeue(self):
"""Test dequeue() on a non-empty Queue.
"""
front = self.queue.dequeue()
self.assertEqual(
front, 'a',
'The item at the front should have been "a" but was ' +
front + '.')
self.assertTrue(
self.queue.is_empty(),
'Queue with one element not empty after dequeue().')
class TypicalTestCase(unittest.TestCase):
"""A comprehensive tester of typical behaviour of Queue.
"""
def setUp(self):
"""Set up an empty queue.
"""
self.queue = Queue()
def tearDown(self):
"""Clean up.
"""
self.queue = None
def testAll(self):
"""Check enqueueing and dequeueing several items.
"""
for item in range(20):
self.queue.enqueue(item)
self.assertFalse(
self.queue.is_empty(),
'Queue should not be empty after adding item ' +
str(item))
item = 0
while not self.queue.is_empty():
front = self.queue.dequeue()
self.assertEqual(
front, item,
'Wrong item at the front of the Queue. Found ' +
str(front) + ' but expected ' + str(item))
item += 1
class MutableTestCase(unittest.TestCase):
"""Test adding a mutable object. Make sure the Queue adds the object,
and does not make a copy.
"""
def setUp(self):
"""Set up an empty queue.
"""
self.queue = Queue()
def tearDown(self):
"""Clean up.
"""
self.queue = None
def testMutable(self):
"""Test with a list.
"""
item = [1, 2, 3]
self.queue.enqueue(item)
item.append(42)
self.assertEqual(self.queue.front(), item,
'mutable item did not change!')
self.assertEqual(self.queue.dequeue(), item,
'mutable item did not change!')
if __name__ == '__main__':
unittest.main(exit=False)
|
#带壳的双向linked list
class Node():
def __init__(self, data, next_node=None, prev=None):
'''双向linked list,有next也有previous指向。'''
self.data = data
self.next = next_node
self.prev = prev
def __str__(self):
return str(self.data)
class EmptyError(Exception):
pass
class LinkedList_2():
def __init__(self):
self.head = None
self.tail = None #with pointer to the last 添加东西到linked list最末尾的时候也会快很多,不用再loop一遍找末尾
self.size = 0
#在这里添加个attribute记录size,当问这个linked list
#的长度时就不用每次loop一遍
#现在每加进一个data,self.size就加1
#问linked list的长度时直接return self.size就会快很多,runtime就是constant
def __len__(self):
return self.size
def append(self, data):
'''Add a new data to the end of the linked list.'''
new = Node(data)
self.size += 1
if self.head == None:
self.head = new
self.tail = new
return
self.tail.next = new #注意:现在要更改的就是3层链接
new.prev = self.tail
self.tail = new
return
def pop(self, index):
'''Delete the data with given index from the linked list.
这个pop其实建议写helper function来写,太长了。'''
#如果是个空的linked list 或者 index大于liked list的长度
if self.head == None or index >= self.size:
raise EmptyError()
#如果要删除的是第一位元素
if index == 0:
old = self.head#记录下这个node方便之后断开链接
self.head = old.next
old.next = None#断开要删除的node与linked list的链接
self.head.prve = None
self.size -= 1
return old.data
#如果要删除的是最后一位元素
if index == self.size-1:
old = self.tail
self.tail = old.prev
old.prev = None#断开链接
self.tail.next = None
self.size -= 1
return old.data
#如果given index在linked list的前半段(more efficient)
if index < self.size//2:
curr = self.head
curr_index = 0
while curr != None:
if curr_index == index:
prev_node = curr.prev#这里就可以call个帮助删除和创建链接的function
next_node = curr.next
prev_node.next = next_node#跳过要删除元素把两个node连接起来
next_node.prev = prev_node
curr.next = None#断开删除元素与linked list的链接
curr.prev = None
#这里不用多加一行写self.size -= 1,
#因为我们loop的方式会进到base case里
#也就是index==0和index=size-1时,在上面那两个if里会减的
return curr.data
curr = curr.next#循环起来
curr_index += 1
else:#如果given index在linked list的后半段(more efficient)
curr = self.tail
curr_index = self.size - 1
while curr != None:
if curr_index == index:
prev_node = curr.prev
next_node = curr.next
prev_node.next = next_node#跳过删除元素链接相邻两个node
next_node.prev = prev_node
curr.next = None#断开删除元素与linked list的链接
curr.prev = None
return curr.data
curr = curr.prev
curr_index -= 1
|
def percentage(raw_mark, max_mark):
''' (float, float) -> float
Return the percentage mark on a piece of work that received a mark of
raw_mark where the maximum possible mark is max_mark.
>>> percentage(15, 20)
75.0
'''
return ((raw_mark / max_mark) * 100)
def contribution(mark_as_percent, weight):
''' (float, float) -> float
Given a piece of work that earned mark_as_percent percent and was
worth weight marks in the marking scheme, return the number of marks it
contributes to the final course mark.
>>> contribution(50, 12.5)
6.25
'''
return (weight * (mark_as_percent / 100))
def raw_contribution(raw_mark, max_mark, weight):
''' (float, float, float) -> float
Given a piece of work where the student earned raw_mark marks out of a
maximum of max_marks marks possible, return the number of marks it
contributes to the final course mark if this piece of work is worth weight
marks in the course marking scheme.
>>> raw_contribution(13.5, 15, 10)
9.0
'''
return (percentage(raw_mark, max_mark) * weight / 100)
def assignments_contribution(a1, a2, a3):
'''
Given raw marks a1, a2 and a3 for the three course assignments,
calculate the contribution to the final course grade.
Assume each assignment is marked out of 50.
The assignments are worth 10%, 15%, and 15%, respectively.
>>> assignments_contribution(40, 42, 40)
32.6
'''
return ((a1 / 50 * 10) + (a2 / 50 * 15) + (a3 / 50 * 15))
def term_work_mark(assignments, quizzes_and_exercises, labs, midterm):
'''(float, float, float, float, float) -> float
Given the contribution of:
assignments (out of 40)
quizzes and mini-exercises (out of 5)
labs (out of 10)
and midterm (as a percentage out of 100),
return the term mark grade.
The midterm is worth 10%, so
the returned mark represents a mark out of 65.
>>> term_work_mark(28, 4.5, 7, 73.5)
46.85
'''
assignments = assignments_contribution(a1, a2, a3)
quizes_and_ecercises =
labs = labs * 10
midterm =
return
def exam_required(term_work, desired_grade):
''' (float, int) -> float
Given a term work mark of term_work representing 65% of the points in the
grading scheme, calculate and return the percentage required on the exam for
the final mark to be desired_grade.
>>> exam_required(54, 82)
80.0
'''
|
"""Incomplete Binary Search Tree implementation.
Author: Francois Pitt, March 2013,
Danny Heap, October 2013.
"""
class BST:
"""A Binary Search Tree."""
def __init__(self: 'BST', container: list =[]) -> None:
"""
Initialize this BST by inserting the values from container (default [])
one by one, in the order given.
"""
# Initialize empty tree.
self.root = None
# Insert every value from container.
for value in container:
self.insert(value)
def __str__(self: 'BST'):
"""
Return a "sideways" representation of the values in this BST, with
right subtrees above nodes above left subtrees and each value preceded
by a number of TAB characters equal to its depth.
"""
# Tricky to do iteratively so we cheat,
# You could take up the challenge...
return BST._str("", self.root)
# Recursive helper for __str__.
def _str(indent: str, root: '_BSTNode') -> str:
"""
Return a "sideways" representation of the values in the BST rooted at
root, with right subtrees above nodes above left subtrees and each
value preceded by a number of TAB characters equal to its depth, plus
indent.
"""
if root:
return (BST._str(indent + "\t", root.right) +
indent + str(root.value) + "\n" +
BST._str(indent + "\t", root.left))
else:
return ""
def insert(self: 'BST', value: object) -> None:
"""
Insert value into this BST.
"""
# Find the point of insertion.
parent, current = None, self.root
while current:
if value < current.value:
parent, current = current, current.left
else: # value > current.value
parent, current = current, current.right
# Create a new node and link it in appropriately.
new_node = _BSTNode(value)
if parent:
if value < parent.value:
parent.left = new_node
else: # value > parent.value
parent.right = new_node
else:
self.root = new_node
def count_less(self: 'BST', value: object) -> int:
"""
Return the number of values in this BST that are strictly less than
value.
"""
# ridiculous stub value --- fix this!
return -42
def size(self: 'BST') -> int:
"""Return number of nodes in BST self"""
stack = Stack()
count = 0
stack.push(self.root)
while not stack.is_empty():
node = stack.pop()
if node: # only count non-empty nodes
count += 1
stack.push(node.left)
stack.push(node.right)
return count
class _BSTNode:
"""A node in a BST."""
def __init__(self: '_BSTNode', value: object,
left: '_BSTNode' =None, right: '_BSTNode' =None) -> None:
"""
Initialize this node to store value and have children left and right.
"""
self.value, self.left, self.right = value, left, right
'''Stack ADT.
Operations:
pop: remove and return top item
push(item): store item on top of stack
is_empty: return whether stack is empty.
'''
class Stack:
'''A last-in, first-out (LIFO) stack of items'''
def __init__(self):
'''A new empty Stack.'''
self._data = []
def pop(self):
'''Remove and return the top item.'''
return self._data.pop()
def is_empty(self):
'''Return whether the stack is empty.'''
return self._data == []
def push(self, o):
'''Place o on top of the stack.'''
self._data.append(o)
|
class BTNode:
"""Binary Tree node."""
def __init__(self: 'BTNode', data: object,
left: 'BTNode'=None, right: 'BTNode'=None) -> None:
"""Create BT node with data and children left and right."""
self.data, self.left, self.right = data, left, right
def __repr__(self: 'BTNode') -> str:
"""Represent this node as a string."""
return ('BTNode(' + str(self.data) + ', ' + repr(self.left) +
', ' + repr(self.right) + ')')
#################################outsize the class############################################
def find_min(t):#t is a node
'''这相当于是在binary tree里找最小值,
我们写helper function是为了判断bst!
所以现在还不能直接使用bst的性质来找最小值!'''
ans = t.data
if t.left:
ans = min(ans, find_min(t.left))
if t.right:
ans = min(ans, find_min(t.right))
return ans #这里不用再对ans作比较是因为他自己已经刷新成最小的值了
def find_max(t):
ans = t.data
if t.left:
ans = max(ans, find_max(t.left))
if t.right:
ans = max(ans, find_max(t.right))
return ans
def is_bst(t):
if not t:
return True
return (not t.left or find_max(t.left) < t.data) and \
(not t.right or find_min(t.right) > t.data) and \
is_bst(t.left) and is_bst(t.right)
t = BTNode(5, BTNode(4, BTNode(3, BTNode(1))), BTNode(90))
print(is_bst(t))
|
'''
#############################################################################################################
##Be able to write all three class questions incliding the __main__ function. Practice! Practice! Practice!##
#############################################################################################################
Question 1
Write one or more classes for the following specification. Begin by carrying out an object-oriented
analysis to determine the classes, methods, attributes, and interactions.
Context: An airline reservation system
3 main classes:
供给端:seats(economy & business)
需求端:passenger
控制台:ReserveSys
Each seat on a plane is classified as business class or economy, and has a unique name (like
“17C”). Passengers have booking IDs (a mix of letters and numbers). When they book a seat, they
request their preferred class (business or economy) and are given any seat in that class. If the chosen
class is full, then their booking is unsuccessful. This airline gives passengers no choice about their
specific seat. We want to be able to report on how full a flight is: the percentage of seats that are
booked in economy, in business class, and overall.
'''
#should have writen these two classes as a whole class named Seat
class Business():
def __init__(self,num, seats):
self.num = num #total number of seats
self.seats = seats#list of seats
def percentage(self):#seats booked %
return (1 - len(self.seats)/self.num)*100 ##不在这里写string representation,在main里才写
def book_seat(self):
if self.seats != []:
return self.seats.pop(0)
else:
print('Booking is unsuccessful. All the seats are full. Choose another class.')
return None
class Economy(Business):
pass
class Passenger:
def __init__(self,ID, seat_type, seat):
self.ID = ID
self.t = seat_type
self.seat = seat
def __str__(self):
s = 'Passenger: {}\nClass: {}\nSeat: {}\n'.format(self.ID, self.t, self.seat)
return s
class ReserveSys(): #big class that stores all the information
def __init__(self, seatsList_e, seatsList_b, eco_seat_num, business_seat_num):
self.passengerList = []
self.economy = Economy(eco_seat_num, seatsList_e)
self.business = Business(business_seat_num, seatsList_b)
#在这里就创建好了两个舱型的座位信息
def book_seat(self, c, ID):
if c == 'business':
seat = self.business.book_seat() #self.business这个instance去book seat
if seat != None:
passenger = Passenger(ID, c, seat)#在这里才创建passenger,相当于这个passenger才上了飞机
self.passengerList.append(passenger)
print('successful\n')
print(passenger)
else:
seat = self.economy.book_seat()
if seat != None:#seat class里的book seat method,若seat满了,return None
passenger = Passenger(ID, c, seat)
self.passengerList.append(passenger)
print('Booking successful!\n')
print(passenger)#__str__应该是在passenger里写成个method的,不应该在ReserveSys里hard code文字进去
def how_full(self, c):
if c == 'business':
return self.business.percentage()
return self.economy.percentage()
def how_full_overall(self):
return len(self.passengerList)/(self.business.num + self.economy.num)
if __name__ == '__main__':
plane1 = ReserveSys(['1E','2E','3E'],['1B','2B','3B'], 3, 3)
menu = '"b" to book a seat\n' + \
'"ce" to check economy capacity\n' + \
'"cb" to check business capacity\n' + \
'"c" to check the plane capacity\n' + \
'"q" to quit the system'
print(menu)
order = input('Input an order: ')
## while order not in ['b','ce','cb','c','q']:
## print('invalid input, please re-enter again.')
## order = input('Input an order: ')
#在main里的最后一个else有包裹invalid input,这里不用check
while order != 'q':
if order == 'b':
c = input('Do you want to book seat from business class or economy class? ')
while c not in ['business','economy']:
print('Invalid Class, please re-enter again.')
c = input('Do you want to book seat from business class or economy class? ')
ID = input('Input your Booking ID [a mix of letters and numbers]: ')
while not ID.isalnum():#alnum()的用法!
print('Invalid ID')
ID = input('Input your Booking ID [a mix of letters and numbers]: ')
plane1.book_seat(c,ID)
elif order == 'ce':
p = plane1.how_full('economy')
print('The economy capacity is: {}'.format(p))
elif order == 'cb':
p = plane1.how_full('business')
print('The business capacity is: {}'.format(p))
elif order == 'c':
p = plane1.how_full_overall()
print('The plane capacity is: {}'.format(p))
else:
print('Invalid order! input again.....')
print(menu)
order = input('Input an order: ')
'''
Question 2
Write one or more classes for the following specification. Begin by carrying out an object-oriented
analysis to determine the classes, methods, attributes, and interactions.
Context: an inventory system
3 main classes:
供给端:items
需求端: None
控制台:InventorySys
Items are for sale, each at its own price. Items are identified by their item number, and they also
have a text description, such as “bath towel”. There are categories that items belong to, such as
“housewares” and “books”. We need to be able to print a suitable price tag for an item (you can decide
exactly the format). Sometimes an item is discounted by a certain percentage. We need to be able to
compare two items to see which is cheaper.
'''
class InventorySys:
def __init__(self,goods=[]):
self.inventory = {}
for good in goods:
self.inventory[good.number] = good
def sold(self,num):
g = self.inventory.pop(num)
print(g)
print('item sold')
def show(self):
s = ''
for num in self.inventory:
s += '{}: {}\n'.format(num, str(self.inventory[num]))
print(s)
def discount(self, num, p):
good = self.inventory[num]
new = good.price*p
good.change_price(new)
def compare(self, n1,n2):
g1 = self.inventory[n1]
g2 = self.inventory[n2]
if g1 > g2:
return g2
elif g2 > g1:
return g1
else:
return None
class items:
def __init__(self, number, description, category, price):
self.number = number
self.description = description
self.category = category
self.price = price
def __str__(self):
return 'Item {} is worth {} dollars.'.format(self.number, self.price)
def discount(self, discount):
self.price = self.price*discount
def cheaper(self, item1,item2):
if item1.price < item2.price:
return item1.number
elif item1.price > item2.price:
return item2.number
else:
return 'Both items are same price.'
def change_price(self, new):
self.price = new
def __gt__(self, other):
return self.price > other.price
if __name__ == '__main__':
g1 = items(2001,'notebook','book',10)
g2 = items(2002,'mark pen','pen',15)
g3 = items(2003,'newbook','book',12)
goods = [g1,g2,g3]
s = InventorySys(goods)
menu = 'show\nsold\ndiscount\ncompare\nquit'
print(menu)
order = input('input an order: ')
while order != 'quit':
if order == 'show':
s.show()
elif order == 'sold':
num = int(input('good num: '))
s.sold(num)
elif order == 'discount':
num = int(input('good num: '))
p = float(input('discount: '))
s.discount(num,p)
elif order == 'compare':
n1 = int(input('good1 num: '))
n2 = int(input('good2 num: '))
g = s.compare(n1, n2)
if g == None:
print('same price')
else:
print(g)
print('------------------\n')
print(menu)
order = input('input an order: ')
'''
Q3
A To Do List has a name (an arbitrary string), and a list of tasks, provided when the list is created.
New tasks can be added to the To Do List, but the total number of tasks in the list must be 50 or less.
Attempting to add more than 50 tasks to a list should raise the TaskOverloadError.
Each task has a date, month and year, provided when the task is created.
The date must be an integer between 1 and 31, the month must be an integer between 1 and 12,
and the year must be 2016 or greater. An invalid date, month or year should raise the InvalidDateError
A task also has details about the task in the format of a string (e.g. "date with Jane"),
provided when the task is created.
Write code to perform the following:
Create a To Do List named "School" with an empty list of tasks
Prompt the user for a date
Prompt the user for a month
Create a task for "Ace CSC108 test" using the given date, month and 2018 as the year, and add the task to the to do list that was created
If this raises an InvalidDateError, print "invalid date"
If this raises a TaskOverloadError, print "too many tasks"
'''
class ToDoList:
def __init__(self,name, tasklist=[]):
self.name = name
self.tasklist = tasklist
def add_task(self,task):
if len(self.tasklist) == 50:
raise TaskOverloadError
#('To do list is full. Cannot add new task.') 不在这里加,main里得接住这个error然后才print这句话
else:
self.tasklist.append(task)
class Task:
def __init__(self, date, month, year, task):
if not (1 <= date <= 31) or not (1 <= month <= 12) or year < 2016:
raise InvalidDateError
#else:
self.date = date
self.month = month
self.year = year
self.task = task
class TaskOverloadError(Exception):
print('too many tasks')
class InvalidDateError(Exception):
print('invalid data')
if __name__ == '__main__':
school = ToDoList('School') #with empty task list
date = input('Please enter a date.')
while not date.isdigit():
print('Invalid date! Please enter again.')
date = input('Please enter a date.')
##WRONG!! while date is not <=1 and date is not <= 31:
## raise InvalidDateError("invalid date")
month = input('Please enter a month.')
while not month.isdigit():
print('Invalid month! Please enter again.')
date = input('Please enter a month.')
try:
task = Task(int(d),int(m),2016,'Ace CSC148 test')
school.add_task(task)
|
class LinkedNode():
def __init__(self,data, next_node=None):
self.data = data
self.next = next_node
class LinkedList():
'''把一些基本的queue会用到的method添加进来。'''
def __init__(self):
self.head = None
def append(self, data):
if self.head == None:
self.head = LinkedNode(data)
return
curr = self.head
while curr.next != None:
curr = curr.next#找到linked list的最末端
curr.next = LinkedNode(data)
def pop(self, index):
if self.head == None:
raise IndexError("Linked list index out of range")
if index == 0:
old = self.head
self.head = old.next
old.next = None
return old.data
parent = self.head
curr = self.head.next
curr_index = 1
while curr != None:
if curr_index == index:
parent.next = curr.next
curr.next = None
return curr.data
parent = curr
curr = curr.next
curr_index += 1
raise IndexError("Linked list index out of range")
def __len__(self):
t = 0
if self.head == None:
return t
curr = self.head
while curr != None:
curr = curr.next
t += 1
return t
class EmptyQueueError(Exception):
"""An exception raised when attempting to dequeue from an empty queue.
"""
pass
class Queue():
'''这个装data的容器是个linked list而已,只是尊崇了Queue先进先出的性质而已。'''
def __init__(self):
self.items = LinkedList()#建立个queue就是建立个空的linked list,不需要加什么parameters,之后可以慢慢加元素进去
def enqueue(self, data):
self.items.append(data)#append东西进linked list时会在linked list里创建node的,只用给data就好
def dequeue(self):
if self.is_empty():
raise EmptyQueueError()
return self.items.pop(0)#先进先出
def is_empty(self):
return self.items.head == None#这里self.items就是个linked list
def front(self):
if self.is_empty():
raise EmptyQueueError()
return self.items.head.data#若一开始linked list没有东西,第一个加进去的东西会自动被设为head的
|
import random
#1
def make_grid(w, h, player_coord, gold_coord):
'''
(int, int, tuple of two ints, tuple of two ints) -> None
Given two integers width w and height h, append
sublists into the variable "grid" to make a maze
of the specified width and height.
The coordinates for the player and the gold
is also given as two two-element tuples. For each tuple,
the first element has the x-coordinate and the
second element has the y-coordinate. The player
and the gold should be included in the grid in
the positions specified by these tuples.
The player is represented with the string '(o)'
The gold is represented with the string '(*)'
All other spaces are represented with the string '(_)'
This function does not return anything.
It just modifies the "grid" list, by appending to it.
>>> make_grid(2, 3, (0, 0), (1, 2))
>>> print(grid)
[['(o)', '(_)'], ['(_)','(_)'], ['(_)', '(*)']]
'''
for i in range(h):
grid.append([])
for i1 in range(w):
grid[i].append('(_)')
player_x = player_coord[0]
player_y = player_coord[1]
gold_x = gold_coord[0]
gold_y = gold_coord[1]
grid[player_y][player_x] = '(o)'
grid[gold_y][gold_x] = '(*)'
def print_grid():
'''
() -> None
Print out the grid stored in the variable "grid".
It should print out as described in the assignment
instructions.
e.g. if grid = [['(o)', '(_)'], ['(_)','(_)'], ['(_)', '(*)']]
this function should print out:
(o)(_)
(_)(_)
(_)(*)
NOTE:
THIS FUNCTION IS ALREADY COMPLETE.
YOU DO NOT NEED TO CHANGE THIS FUNCTION.
P.S. The code below uses something called list comprehensions,
to shorten lines of code. This is something we don't officially
cover in 108, but it can come in handy! So, if you're comfortable
with it, you're welcome to use it. If not, no worries. You can
stick to what you're most comfortable with.
More about how this works here:
http://blog.teamtreehouse.com/python-single-line-loops
'''
s = ''
for row in range(len(grid)):
s += ''.join(element for element in grid[row]) + "\n"
print(s)
#2
def update_grid(w, h, px, py, dx, dy):
'''
(int, int, int, int, int, int) -> None or tuple of two ints
Given the player's current position as px and py,
and the directional changes in dx
and dy, update the "grid" to change the player's
x-coordinate by dx, and their y-coordinate by dy.
More information:
Use the given w and h (representing the grid's width
and height) to figure out whether or not the move is valid.
If the move is not valid (that is, if it is outside
of the grid's boundaries), then NO change occurs to the grid.
The grid stays the same, and nothing is returned.
If the move IS possible, then the grid is updated
by adding dx to the player's x-coordinate,
and adding dy to the player's y-coordinate.
The new position in the grid is changed to the player
icon '(o)', and the old position the player used to be in
is changed to an empty space '(_)'. The new x- and y- coordinates
of the player is returned as a tuple.
This function does NOT create a new grid.
It modifies the "grid" variable that was defined at the top of this file.
>>> update_grid(2, 3, 0, 0, 1, 0)
(1,0)
>>> update_grid(2, 3, 0, 0, 0, 1)
(0,1)
>>> update_grid(2, 3, 0, 0, -1, 0)
(0,0)
'''
if px + dx >= w or px + dx < 0 or py + dy >= h or py + dy < 0:
return (px,py)
else:
grid[py][px] = '(_)'
grid[py+dy][px+dx] = '(o)'
return (px+dx,py+dy)
def get_moves(d):
"""
(str) -> tuple of two ints
Given a direction that is either 'N', 'S', 'E' or 'W'
(standing for North, South, East or West), return
a tuple representing the changes that would occur
to the x- and y- coordinates if a move is made in that
direction.
e.g. If d is 'W', that means the player should move
to the left. In order to do so, their x-coordinate should
decrease by 1. Their y-coordinate should stay the same.
These changes can be represented as the tuple (-1, 0),
because the x-coordinate would have -1 added to it,
and the y-coordinate would have 0 added to it.
>>> get_moves('W')
(-1, 0)
>>> get_moves('E')
(1, 0)
NOTE:
THIS FUNCTION IS ALREADY COMPLETE.
YOU DO NOT NEED TO CHANGE THIS FUNCTION.
"""
if (d == "N"):
return (0,-1)
elif (d == "S"):
return (0,1)
elif (d == "E"):
return (1,0)
else:
return (-1,0)
def get_direction():
"""
() -> str
Ask the user for a direction that is N, S, E or W.
Once a valid direction is given, return this direction.
NOTE:
THIS FUNCTION IS ALREADY COMPLETE.
YOU DO NOT NEED TO CHANGE THIS FUNCTION.
"""
d = input("Which way would you like to move? Choose N, S, E, W. ")
while ((len(d) != 1) or (d.upper() not in 'NSEW')):
d = input("Invalid input. Choose N, S, E, W. ")
return d.upper()
# ==== Finish the functions above according to their docstrings ==== #
# ==== The program starts here. ==== #
# ==== Do NOT change anything below this line. ==== #
if __name__ == "__main__":
# We have a global variable called grid that all functions
# have access to and can modify directly
grid = []
w = int(input("Width: "))
h = int(input("Height: "))
p_x = p_y = 0
gold_x = random.randint(1,w-1)
gold_y = random.randint(1,h-1)
game_won = False
make_grid(w, h, (p_x, p_y), (gold_x, gold_y))
while (not game_won):
print_grid()
d = get_direction()
# the following line unpacks the tuple returned by get_moves
# this means the first element in the returned tuple gets assigned
# to dx, the second element in the tuple assigned to dy
dx, dy = get_moves(d)
new_xy = update_grid(w, h, p_x, p_y, dx, dy)
if new_xy: # if something is returned, a change has occurred to player position
p_x, p_y = new_xy
game_won = (p_x == gold_x) and (p_y == gold_y)
print("Congratulations! You won.")
|
"""A simple implementation of the Queue ADT.
Authors: Francois Pitt, January 2013,
Danny Heap, September 2013
"""
class EmptyQueueError(Exception):
"""An exception raised when attempting to dequeue from an empty queue.
"""
pass
class Queue:
"""A collection of items stored in 'first-in, first-out' (FIFO) order.
Items can have any type.
Supports standard operations: enqueue, dequeue, front, is_empty.
"""
def __init__(self: 'Queue') -> None:
"""
Initialize this queue.
>>> q = Queue()
>>> isinstance(q, Queue)
True
"""
self._items = []
def enqueue(self: 'Queue', item: object) -> None:
"""
Add item to the back of this queue.
item - object to put in queue
>>> q = Queue()
>>> q.enqueue(5)
>>> q.enqueue(6)
>>> q.dequeue()
5
"""
self._items.append(item)
def dequeue(self: 'Queue') -> None:
"""
Remove and return the front item in this queue.
>>> q = Queue()
>>> q.enqueue(5)
>>> q.enqueue(6)
>>> q.dequeue()
5
"""
if self.is_empty():
raise EmptyQueueError()
return self._items.pop(0)
def front(self: 'Queue') -> object:
"""
Return the front item in this queue without removing it.
>>> q = Queue()
>>> q.enqueue(5)
>>> q.enqueue(6)
>>> q.front()
5
>>> q.dequeue()
5
"""
if self.is_empty():
raise EmptyQueueError()
return self._items[0]
def is_empty(self: 'Queue'):
"""
Return True iff this queue is empty.
>>> Queue().is_empty()
True
"""
return self._items == []
|
# EXAMPLE THAT WE DID IN CLASS
def remove_three(lst):
'''(list of int) -> list of int
Return a new list with all elements of lst except the 3s.
lst has no nesting.
>>> remove_three([1, 2, 3, 3, 4])
[1, 2, 4]
'''
if L == []:
return []
elif L[0] == 3:
return remove_three(L[1:])
else:
return [L[0]] + remove_three(L[1:])
# MINI-EXERCISE Q1: COMPLETE THE FOLLOWING USING RECURSION
def remove_three_nested(lst):
'''(list of int) -> list of int
Return a new list with all elements of lst except the 3s.
lst may have nesting to arbitrary depth.
>>> remove_three_nested([1, [2, 3], 3, 4])
[1, [2], 4]
'''
## if lst == []:
## return []
## elif isinstance(lst[0], int):
## if lst[0] == 3:
## return remove_three_nested(lst[1:])
## else:
## return [lst[0]] + remove_three_nested(lst[1:])
## else: #if lst[0] is a nested list
## return [remove_three_nested(lst[0])] + remove_three_nested(lst[1:])
##
l = []
for e in lst:
if type(e) == int:
if e != 3:
l.append(e)
else:
l.append(remove_three_nested(e))
return l
# MINI-EXERCISE Q2: COMPLETE THE DOCSTRING DESCRIPTION OF THE FOLLOWING
def mystery(lst, n):
'''
(list, int) -> bool
# Describe here in PLAIN ENGLISH (not a line-by-line description)
# what this function does
Return ture iff lst[i] is less than n-i.
>>>mystery([2, 2, 3, 4], 6)
False
>>>mystery([1, 1, 1], 3)
True
'''
if lst == []:
return True
elif lst[0] > n:
return False
else:
return mystery(lst[1:], n-1)
|
'''
Call():
Create your call class with an init method. Each instance of Call() should have a few attributes:
unique id
caller name
caller phone number
time of call
reason for call
The call class should have a display method that prints all call attributes.
'''
from string import ascii_uppercase, digits, ascii_lowercase
from random import choice
from datetime import datetime
# print datetime.now()
#
# print ''.join(choice(ascii_uppercase + digits + ascii_lowercase) for _ in range(12))
class Call(object):
def __init__(self, name, phone_number, reason_for_call):
self.id = ''.join(choice(ascii_uppercase + digits) for _ in range(12))
self.name = name
self.phone_number = phone_number
self.time_of_call = datetime.now()
self.reason_for_call = reason_for_call
def displayInfo(self):
print 'Call id is: {}'.format(self.id)
print 'Call name is: {}'.format(self.name)
print 'Call phone_number is: {}'.format(self.phone_number)
print 'Call time_of_call is: {}'.format(self.time_of_call)
print 'Call reason_for_call is: {}'.format(self.reason_for_call)
# call1 = Call('Phil', '111-111-1111', 'make call')
# call1.displayInfo()
'''
CallCenter():
Create you call center class with an init method. Each instance of CallCenter() should have the following attributes:
calls: should be a list of call objects
queue size: should be the length of the call list
The call center class should have an add method that adds a new call to the end of the call list
The call center class should have a remove method that removes the call from the beginning of the list (index 0).
The call center class should have a method called info that shows the name and phone number for each call in the queue as well as the length of the queue.
You should be able to test your code to prove that it works. Remember to build one piece at a time and test as you go for easier debugging!
'''
class CallCenter(object):
def __init__(self):
self.calls = []
self.queueSize = len(self.calls)
def add_call(self, name, phone_number, reason_for_call):
newCall = Call(name, phone_number, reason_for_call)
self.calls.append(newCall)
self.queueSize = len(self.calls)
def remove_call(self):
del self.calls[0]
self.queueSize = len(self.calls)
def show_calls(self):
print 'the length of the call is: {}'.format(self.queueSize)
for call in self.calls:
print 'name of caller is: {}, phone_number is: {}'.format(call.name, call.phone_number)
customerSupport = CallCenter()
customerSupport.add_call('Phil', '111-111-1111', 'make call')
customerSupport.add_call('Phil', '222-111-1111', 'make call')
customerSupport.add_call('Phil', '333-111-1111', 'make call')
customerSupport.show_calls()
customerSupport.remove_call()
customerSupport.show_calls()
|
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
]
# for student in students:
# print student['first_name'], student['last_name']
users = {
'Students': [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'},
{'first_name' : 'Mark', 'last_name' : 'Guillen'},
{'first_name' : 'KB', 'last_name' : 'Tonel'}
],
'Instructors': [
{'first_name' : 'Michael', 'last_name' : 'Choi'},
{'first_name' : 'Martin', 'last_name' : 'Puryear'}
]
}
for user in users:
print user
count = 0
for person in users[user]:
count += 1
print '{} - {} {} - {}'.format(count, person['first_name'], person['last_name'], len(person['first_name']) + len(person['last_name']))
|
#!/usr/bin/env python3
"""
Jeu de devinette
par: Olivier Vezina
"""
from random import randrange
nbEssai = 0
nbParties = 1
MAX_ESSAIS = 10
WIN = "GGG"
LOST = "PPP"
def main():
"""
Fonction principale
"""
print("Bonjour, je m'appelle Pedro CallMe")
print("J'ai choisi un nombre entier entr 1 et 100")
print("Pouvez-vous le deviner?")
devinette()
def devinette():
"""
Fonction pour deviner le nombre
"""
nbRandom = randrange(1, 101)
liste = []
cpt = 1
global nbEssai
while True:
if cpt <= MAX_ESSAIS:
nbEssai += 1
saisie = input(f"Essaie {cpt}: ")
if saisie == LOST:
print(f"Désolé, vous avez échoué après {cpt} tentatives")
print(f"Le nombre choisi était: {nbRandom}")
recommencer()
elif saisie == WIN:
liste.append("GGG")
print("Bravo, vous avez deviné le nombre")
print(f"Votre séquence gagnante est : {liste} ")
recommencer()
else:
if saisie.lstrip('-+').isdigit():
guess = int(saisie)
liste.append(guess)
if guess == nbRandom:
print("Bravo, vous avez deviné le nombre")
print(f"Votre séquence gagnante est : {liste} ")
recommencer()
elif guess < nbRandom:
print("Votre nombre est trop petit...")
cpt = cpt + 1
continue
else:
print("Votre nombre est trop grand...")
cpt = cpt + 1
continue
else:
print("Erreur: Entrer un nombre entier svp")
continue
else:
print("Désolé, vous avez échoué après 10 tentatives ")
print(f"Le nombre choisi était: {nbRandom}")
recommencer()
def recommencer():
"""
Methode qui demande a l'utilisateur veut recommencer une partie
"""
global nbParties
while True:
choix = input(f"Voulez-vous rejouer? [O/N] ")
if choix.upper() == "O" or choix == "oui":
nbParties += 1
print()
print()
devinette()
elif choix.upper() == "N" or choix == "non":
moyenne = nbEssai / nbParties
print("Au revoir")
print(f"Nombre de parties jouées: {nbParties}")
print(f"Nombre d'essais était: {nbEssai}")
print(f"Moyenne d'essais par partie: {moyenne} ")
exit()
else:
print("Choix invalide")
continue
if __name__ == '__main__':
main()
|
###############################################
# Skyler Kuhn
# BNFO 501: Project 2 Program
# Implementing Merge Sort
################################################
from __future__ import print_function
import time
dataFh = open("project1_data.txt", "r")
filedatalist = dataFh.read().splitlines()
dataFh.close() # Don't forget to close your file handles
Metrics = filedatalist.pop(0) # lets remove the zeroth element, we need this for creating two data sets
# print(Metrics)
# Grabbing the appropreiate
dataMetric, queryMetric = int(Metrics.split()[0]), int(Metrics.split()[1])
# print(dataMetric,queryMetric) # works fine
# Checking to see if the metrics add up to the len of the new array, if not data set is crappy and the program exits
if len(filedatalist) != dataMetric + queryMetric:
print("Error: You have crappy data. Please modify your input file. It is looks bad.")
print(dataMetric, "+", queryMetric, "!=", len(filedatalist))
exit()
# Creating lists for data set
datalist = filedatalist[0:dataMetric]
querylist = filedatalist[-queryMetric:] # grab the last two things
print(datalist)
print(querylist)
# Let's get our sort on: Merge Sort
############################
# Merge Sort Method
def mergesort(list):
if len(list) < 2:
return list
middle = len(list) // 2
left = mergesort(list[:middle])
right = mergesort(list[middle:])
return merge(list, left, right)
def merge(datalist, left, right):
left.append(9999999999999999999999999999999999999999999999999999999999999999999999999999999999) # dummy variable
right.append(9999999999999999999999999999999999999999999999999999999999999999999999999999999999) # dummy variable
i, j = 0, 0
for k in range(len(datalist)):
if int(left[i]) <= int(right[j]): # these are strings must convert to int's
datalist[k] = left[i]
i += 1
else:
datalist[k] = right[j]
j += 1
return datalist
# Let's get on to the main show: Sequential vs. Binary Search
############################
# Sequential Search Method
def sequentialSearch(dataList, query):
"""Search index-by-index to see if we have found what we are searching for."""
for i in range(len(dataList)):
if dataList[i] == query:
return True
else: # for-else statement, if it never finds anything return False
return False
# Now let's see if the query is in the data list!
print("Sequential Search Timing")
seqSearchOutputFH = open("project2_sequentialSearch_output.txt", "w")
seqSearchOutputFH.write("SearchTime\t\t\t\tStartTime\t\t\t\tQuery\n") # writing a pretty header
for query in querylist:
start = time.clock() # starts the timer
flag = sequentialSearch(datalist, query)
end = time.clock() # end the timer, we take the difference to find how long it took
diff_ms = (end - start) * 100 # convert to ms
if flag: # if it is true
#print("Yes,", query, "is in the data list!")
print("true:{:.10f}ms\t\ttrue:0.0000000000ms\t\t{}".format(diff_ms, query)) # this, realistically, should be take out to as many sig figs as possible
seqSearchOutputFH.write("true:{:.10f}ms\t\ttrue:0.0000000000ms\t\t{}\n".format(diff_ms, query))
else:
#print("No,", query, "is NOT in the data list!")
print("false:{:.10f}ms\tfalse:0.0000000000ms\t{}".format(diff_ms, query))# this, realistically, should be take out to as many sig figs as possible
seqSearchOutputFH.write("false:{:.10f}ms\tfalse:0.0000000000ms\t{}\n".format(diff_ms, query))
seqSearchOutputFH.close()
############################
# Binary Search Method
def binarySearch(dataList, query):
"""List needs to be pre-sorted. This function uses recursion to decrease our search window by half"""
if len(dataList) == 0: # did not find what we are searching for, also one of the base cases.
return False
else:
midindex = len(dataList) // 2 # floor division
if dataList[midindex] == query:
return True #second base case, we have found what we are looking for
else:
if midindex < int(dataList[midindex]): # let's look at the smaller subset of the list
return binarySearch(dataList[:midindex], query)
else: # the query is larger than the midpoint, let's look at the larger subset of the list
return binarySearch(dataList[midindex+1], query) # +1 because we already evaulted the midpoint position
# Now let's see if the query is in the data list!
binSearchOutputFH = open("project2_binarySearch_output.txt", "w")
binSearchOutputFH.write("SearchTime\t\t\t\tStartTime\t\t\t\tQuery\n") # writing a pretty header
print("Binary Search Timing")
datalist = mergesort(datalist) # this needs to be sorted before we can start binary search
for query in querylist:
start = time.clock() # starts the timer
flag = binarySearch(datalist, query)
end = time.clock() # end the timer, we take the difference to find how long it took
diff_ms = (end - start) * 100 # convert to ms
if flag: # if it is true
# print("Yes,", query, "is in the data list!")
print("true:{:.10f}ms\t\ttrue:0.0000000000ms\t\t{}".format(diff_ms, query))
binSearchOutputFH.write("true:{:.10f}ms\t\ttrue:0.0000000000ms\t\t{}\n".format(diff_ms, query))
else:
# print("No,", query, "is NOT in the data list!")
print("false:{:.10f}ms\tfalse:0.0000000000ms\t{}".format(diff_ms, query)) # this, realistically, should be take out to as many sig figs as possible
binSearchOutputFH.write("false:{:.10f}ms\tfalse:0.0000000000ms\t{}\n".format(diff_ms, query))
binSearchOutputFH.close()
#######################################################################################
|
# Skyler Kuhn
# This function multiplies two number using recursion.
# Parameters must be two positive integers.
def multiply_recur(a, b):
if a == 0 or b == 0:
return 0
if a == 1:
return b
# if a > 700:
# return 'R.I.P Computer, just use a calculator!'
if a > 1:
return multiply_recur(a-1, b) + b
a = multiply_recur(2, 3)
print(a)
|
#WAPT update a dictionary with content of another dictionary
d1={'a':350,'b':200,'c':351}
d2={'b':400,'e':300,'f':250}
for i in d2:
if i not in d1:
d1[i]=d2[i]
else:
d1[i]=d1[i]+d2[i]
print(d1)
|
for x in range(2, 1000):
is_prime = True
for i in range(2, x):
if x % i == 0:
is_prime = False
break
if is_prime:
print(x)
|
import os
from Hero import Hero
import Monster
from random import randint
# from gold import Gold
os.system('clear')
gameOn = True
while gameOn:
#=======================
#======== Banner =======
#=======================
text = "Tower of Vengeance"
textLength = len(text)
w = 4
h = 3
print ("*" * textLength + "*" * w)
for x in range(h - 2):
print ("* " + text + " *")
print ("*" * textLength + "*" * w)
#====================================
#======== Hit Enter to begin ========
#====================================
raw_input("""
Get ready for Tower 1!
Hit Enter to begin
""")
os.system('clear')
hero = Hero()
tower = 1
gold = 0
while hero.is_alive() and gameOn == True:
if hero.gold <= 0:
print """
Game Over.
You ran out of gold.
Next time use your gold more wisely."""
start_over = raw_input("Would you like to play again (Y or N)? ")
start_over = start_over.upper()
if start_over == "Y":
gameOn = False
gameOn = True
hero.gold = 200
hero.health = 100
tower = 1
else:
print "Thank you for playing"
gameOn = False
#===========================================
#======== Iterating through monster ========
#===========================================
monsters = []
for monsters in range(1,3):
tower += 1
if monsters == 1:
monster = Monster.Goblin()
gold = 20
elif monsters == 2:
monster = Monster.Vampire()
gold = 40
gameOn = True
while (hero.is_alive() and hero.not_out_of_gold() and monster.is_alive()) and gameOn:
print """
You have %d health.
The %s has %d health.
What do you want to do?
1. Attack
2. Heal (You will lose a turn to attack)
3. flee
""" % (hero.health, monster.name, monster.health)
user_input = raw_input("> ")
os.system('clear')
#===========================
#======== 1. Attack ========
#===========================
if user_input == "1":
attack = True
while (attack):
print ("""
Your health: %d
%s health: %d
Choose attack: (You have %d gold)
1. Superman Punch (10 damage) (10 gold)
2. Sword Slash (20 damage) (20 gold)
3. Epic Attack (35 damage) (40 gold)
4. Shinryuken (55 damage) (70 gold)
5. Demon Armageddon (80 damage) (100 gold)
""") % (hero.health, monster.name, monster.health, hero.gold)
option = raw_input("> ")
if option == "1":
if hero.gold >= 10:
monster.health -= hero.power1
hero.gold -= 10
os.system('clear')
print """
You have dealt %d damage to the %s
""" % (hero.power1, monster.name)
attack = False
else:
os.system('clear')
print "Not enough gold"
elif option == "2":
if hero.gold >= 20:
monster.health -= hero.power2
hero.gold -= 20
os.system('clear')
print """
You have dealt %d damage to the %s!
""" % (hero.power2, monster.name)
attack = False
else:
os.system('clear')
print "Not enough gold"
elif option == "3":
if hero.gold >= 40:
monster.health -= hero.power3
hero.gold -= 40
os.system('clear')
print """
You have dealt %d damage to the %s!
""" % (hero.power3, monster.name)
attack = False
else:
os.system('clear')
print "Not enough gold"
elif option == "4":
if hero.gold >= 70:
monster.health -= hero.power4
hero.gold -= 70
os.system('clear')
print """
You have dealt %d damage to the %s!
""" % (hero.power4, monster.name)
attack = False
else:
os.system('clear')
print "Not enough gold"
elif option == "5":
if hero.gold >= 100:
monster.health -= hero.power5
hero.gold -= 100
os.system('clear')
print """
You have dealt %d damage to the %s!
""" % (hero.power5, monster.name)
attack = False
else:
os.system('clear')
print "Not enough gold"
#=========================
#======== 2. Heal ========
#=========================
elif user_input == "2":
shop = True
while (shop):
print """
Choose Heal Potion: (You have %d gold)
1. 20 Heal Potion (20 gold)
2. 50 Heal potion (50 gold)
3. 80 Heal potion (80 gold)
4. Exit
""" % hero.gold
option = raw_input("> ")
if option == "1":
if hero.gold >= 20:
hero.gold -= 20
hero.health += 20
print "You have used 10 gold. You now have %d gold left." % hero.gold
print "Your health is now %d." % hero.health
shop = False
else:
print "You do not have enough gold."
elif option == "2":
if hero.gold >= 50:
hero.gold -= 50
hero.health += 50
print "You have used 25 gold. You now have %d gold left." % hero.gold
print "Your health is now %d" % hero.health
shop = False
else:
print "You do not have enough gold."
elif option == "3":
if hero.gold >= 80:
hero.gold -= 80
hero.health += 80
print "You have used 50 gold. You now have %d gold left." % hero.gold
print "Your health is now %d" % hero.health
shop = False
else:
print "You do not have enough gold."
elif option == "4":
shop = False
#===================================
#======== When monster dies ========
#===================================
while monster.health <= 0:
if monster.health <= 0 and monsters == 2:
print """
You have defeated the final boss!"""
break
else:
hero.gold += gold
print "%s has been killed!!\n" % monster.name
print "You gained %d gold. You now have %d gold\n" % (gold, hero.gold)
print ("Get ready for Tower %i !!!\n") % tower
raw_input("Hit enter to continue")
os.system('clear')
break
if user_input == "3":
print "Thank you for playing"
gameOn = False
if user_input == "3":
break
#===============================
#======= Monster Attacks =======
#===============================
if monster.health > 0:
attack = randint(1,3)
if attack == 1:
hero.health -= monster.power1
print "The %s used %s for %d damage" % (monster.name, monster.attack1, monster.power1)
if attack == 2:
hero.health -= monster.power2
print "The %s used %s for %d damage" % (monster.name, monster.attack2, monster.power2)
if attack == 3:
hero.health -= monster.power3
print "The %s used %s for %d damage" % (monster.name, monster.attack3, monster.power3)
if hero.health <= 0:
print "Thou hast been slain."
#==============================
#======= When hero dies =======
#==============================
if hero.health <= 0:
print "Game Over"
break
#===========================================
#======= Choosing not to play anymore ======
#===========================================
if monster.health <= 0 and monsters == 2:
gameOn = False
#========================================
#======== Choosing to play again ========
#========================================
if user_input == "3":
break
if user_input == "3":
break
raw_input("Hit enter to continue")
start_over = raw_input("Would you like to play again (Y or N)? ")
start_over = start_over.upper()
if start_over == "Y":
hero.gold = 200
hero.health = 100
tower = 1
gameOn = True
else:
print "Thank you for playing"
|
import re
with open('input.txt', 'r') as f:
arr = f.read().split('\n\n')
n_yes = 0
for group in arr:
letters = set(re.findall('[a-z]', group))
n_yes += len(letters)
print(f"Part 1: {n_yes}")
n_yes = 0
for group in arr:
answers = [set(x) for x in group.splitlines()]
common = set.intersection(*answers)
n_yes += len(common)
print(f"Part 2: {n_yes}")
|
import math
import sys
import time
def trialPrime(cur):
i=3
while i**2 <= cur:
if cur%i == 0:
return False
i += 2
return True
def lucasTest(prime):
# Define Lucas-Lehmer sequence until necessary value
while len(s) <= prime - 2:
s.insert(len(s), s[-1]**2 - 2)
residue = divmod(s[-1],2**prime - 1)
if residue[1] == 0:
mp.insert(len(mp),prime)
#print("l-length",len(s)-1);
print("M-",mp[-1],sep="")
else:
print("M-",prime," false",sep="")
time_init = time.process_time()
print(time_init)
# Variable Definitions
s=[4] #lucas-lehmer sequence
p=[3] #prime number list
mp=[] #Mersenne prime list
#note: mp only stores prime exponent values of Mersenne Primes
j = int(input("number of iterations:"))
for i in range(0,j):
buf=p[-1]
temp = False
while(temp == False):
buf += 2
if trialPrime(buf) == True:
p.insert(len(p),buf)
#print("primes",p)
temp = True
lucasTest(p[-1])
time_end = time.process_time() - time_init
print(time_end)
|
def isAnagram(s1, s2):
list1=list(s1)
list2=list(s2)
list1.sort()
list2.sort()
if list1==list2:
print('is an anagram')
else:
print('is not an anagram')
s1=input('please enter the first string:')
s2=input('please enter the second string:')
isAnagram(s1,s2)
|
def superfloat(n):
if n%1==0:
return int(n)
else:
return float(n)
import string
class polynomial():
def __init__(self,expression='x^2'):
self.expression=expression
def new_expression(self):
new_expression=input('Please enter a polynomial:')
self.expression=new_expression
def derivation(self):
begin=0
alphabet=string.ascii_lowercase+string.ascii_uppercase
item_list=list()
self.expression+='+'
variable='x'
for i in self.expression:
if i in alphabet:
variable=i
if self.expression.startswith('+') or self.expression.startswith('-'):
re=self.expression[0]
self.expression=self.expression[1:]
else:
re='+'
for i in self.expression:
if i=='+' or i=='-':
item_list.append(self.expression[begin:self.expression.index(i,begin+1)])
begin=self.expression.index(i,begin+1)
item_list[0]=re+item_list[0]
for i in item_list:
if i.count(variable)>1:
list1=list(i)
sum=0
while '*' in list1[list1.index(variable):] and list1.count(variable)>1:
if list1[list1.index(variable)+1]=='^':
a=float(''.join(list1[list1.index(variable)+2:list1.index('*',list1.index(variable))]))
a=superfloat(a)
del list1[list1.index(variable):list1.index('*',list1.index(variable))+1]
else:
a=1
del list1[list1.index(variable):list1.index('*',list1.index(variable))+1]
sum=sum+a
if list1.count(variable)==1 and (not '*' in list1[list1.index(variable):]):
if list1[list1.index(variable)+1]=='^':
a=float(''.join(list1[list1.index(variable)+2:]))
a=superfloat(a)
del list1[list1.index(variable):]
else:
a=1
del list1[list1.index(variable):]
sum=sum+a
list1.append(variable+'^'+str(sum))
if list1.count(variable)==1 and '*' in list1[list1.index(variable):]:
if list1[list1.index(variable)+1]=='^':
a=float(''.join(list1[list1.index(variable)+2:list1.index('*',list1.index(variable))]))
a=superfloat(a)
del list1[list1.index(variable):list1.index('*',list1.index(variable))+1]
else:
a=1
del list1[list1.index(variable):list1.index('*',list1.index(variable))+1]
sum=sum+a
list1.append('*'+variable+'^'+str(sum))
item_list[item_list.index(i)]=''.join(list1)
for i in item_list:
if not variable in i:
item_list.remove(i)
for i in item_list:
tem_list=i.split('*')
final_list=list()
final_list.append(i[0])
for j in tem_list:
if j.startswith('+') or j.startswith('-'):
tem_list[tem_list.index(j)]=j[1:]
for j in tem_list:
if not variable in j:
final_list.append(j)
for j in tem_list:
if '^' in j and variable in j:
a=j.index('^')
b=float(j[a+1:])
b=superfloat(b)
c=b-1
if c==1:
j=str(b)+'*'+j[a-1]
elif c>1:
j=str(b)+'*'+j[a-1]+'^'+str(c)
final_list.append(j)
if not '^' in j and variable in j:
j='1'
final_list.append(j)
item_list[item_list.index(i)]='*'.join(final_list)
for k in item_list:
new_list=list(k)
del new_list[1]
item_list[item_list.index(k)]=''.join(new_list)
for i in item_list:
if i.count(variable)>0:
item_list[item_list.index(i)]=i[0]+str(eval(i[1:i.index(variable)-1]))+i[i.index(variable)-1:]
for i in item_list:
if i[len(i)-2:len(i)]=='*1':
item_list[item_list.index(i)]=i[:-2]
for i in item_list:
if not variable in i:
item_list[item_list.index(i)]=i[0]+str(eval(i[1:]))
final_item_list=list()
final_item_list.append(0)
for i in item_list:
if variable in i:
if not i[i.index(variable):] in final_item_list:
final_item_list.append(i[i.index(variable):])
if not variable in i:
if i.startswith('-'):
final_item_list[0]-=superfloat(float(i[1:]))
else:
final_item_list[0]+=superfloat(float(i[1:]))
if final_item_list[0]==0:
del final_item_list[0]
else:
final_item_list[0]=str(final_item_list[0])
for i in final_item_list:
sum=0
if '^' in i and variable in i:
for j in item_list:
if i in j:
if j[0]=='-':
if j[1]==variable:
sum=sum-1
else:
sum=sum-float(j[1:j.index('*')])
if j[0]=='+':
if j[1]==variable:
sum=sum+1
else:
sum=sum+float(j[1:j.index('*')])
if not '^' in i and variable in i:
for j in item_list:
if not '^' in j and variable in j:
if j[0]=='-':
if j[1]==variable:
sum=sum-1
else:
sum=sum-float(j[1:j.index('*')])
if j[0]=='+':
if j[1]==variable:
sum=sum+1
else:
sum=sum+float(j[1:j.index('*')])
sum=str(superfloat(sum))
if not (sum.startswith('+') or sum.startswith('-')):
sum='+'+sum
if not (final_item_list.index(i)==0 and not variable in i):
final_item_list[final_item_list.index(i)]=sum+'*'+final_item_list[final_item_list.index(i)]
if len(item_list)==0:
derivation='0'
else:
derivation=''.join(final_item_list)
if derivation.startswith('+'):
derivation=derivation[1:]
print(derivation)
def main():
a=polynomial()
a.new_expression()
a.derivation()
main()
|
import utils
from cell import Cell
class Board:
def __init__(self, puzzle_file):
# Initialize the board by reading in numbers from numbers.txt
values = utils.read_puzzle(puzzle_file)
self.board = []
self.board_size = len(values)
for row_num, row in enumerate(values):
new_row = []
for column_num, value in enumerate(row):
cell = Cell(value, row_num, column_num, self)
new_row.append(cell)
self.board.append(new_row)
def __getitem__(self, idx):
return self.board[idx]
def __str__(self):
board = ""
for row in self.board:
for cell in row:
board = board + str(cell) + ' '
board = board + "\n"
return board
def __iter__(self):
self.iter = 0
return self
def __next__(self):
if self.iter < self.board_size:
result = self.board[self.iter]
self.iter = self.iter + 1
return result
else:
raise StopIteration
def cell_at(self, row, column):
'''Retreives the cell at a row and column number'''
if row >= self.board_size or column >= self.board_size:
raise IndexError("Row or column out of range.")
return self.board[row][column]
def value_at(self, row, column):
'''Retreives the value at a row and column number'''
return self.cell_at(row, column).value
def is_completed(self):
'''Determines if the board is completed correctly'''
return self.check_rows() and self.check_columns() and self.check_blocks()
def check_rows(self):
'''Checks if all the rows are correct'''
values = set(range(1,10))
for row in self.board:
row = map(lambda cell: cell.value, row)
if set(row) != values:
return False
return True
def check_columns(self):
'''Checks if all the columns are correct'''
values = set(range(1,10))
# Iterate through cells of the first row
for cell in self.board[0]:
# Tell each cell to get all the values in its column
current_column = set(cell.column_values())
if current_column != values:
return False
return True
def check_blocks(self):
'''Checks if all the blocks are correct'''
values = set(range(1,10))
# Iterate each block
for block_num in range(0,9):
[row_range, column_range] = utils.block_ranges(block_num)
block_values = []
# Collect values from each block
for row in row_range:
for column in column_range:
block_values.append(self.value_at(row, column))
# If the values in the block aren't 1 through 9
if set(block_values) != values:
return False
return True
|
import sys
import time
print('a linguagem br é uma linguagem feita para aprendizado ela não é apropriado para projetos grandes')
start = ''
#INT
IntValor = 0
nameInt = '&'
#STRING
nameString = '&'
StringValor = 0
#STRING REP
nameString2 = '&'
stringvalorrep = '&'
rep1 = '&'
rep2 = '&'
#FLOAT
nameFloat = '&'
valorFloat = 0
#BOOL
nameLogica = '&'
valorLogica = False
#LOOP
qvloop = 1
ConsoleLoop = '&'
#ESCREVER
escname = '&'
escnome = '&'
escv = '&'
escsla = ''
while True:
Console = input('>>> ')
if 'imprimir ' in Console:
if Console[9:] == nameInt:
start = start + str(IntValor) + '\n'
elif Console[9:] == nameString:
start = start + StringValor + '\n'
elif Console[9:] == nameString2:
start = start + stringvalorrep + '\n'
elif Console[9:] == nameFloat:
start = start + str(valorFloat) + '\n'
elif Console[9:] == nameLogica:
start = start + str(valorLogica) + '\n'
else:
start = start + Console[9:] + '\n'
elif '<Calculo type="+">' in Console:
a = input('>>;')
b = input('>>;')
if nameInt in a:
a = IntValor
elif nameInt in b:
b = IntValor
c = a + b
start = start + str(c) + '\n'
a = int(a)
b = int(b)
c = a + b
start = start + str(c) + '\n'
elif '<Calculo>' in Console:
a = input('>>;')
b = input('>>;')
if nameInt in a:
a = IntValor
elif nameInt in b:
b = IntValor
c = a + b
start = start + str(c) + '\n'
a = int(a)
b = int(b)
c = a + b
start = start + str(c) + '\n'
elif '<Calculo type="-">' in Console:
a = input('>>;')
b = input('>>;')
if a == nameInt:
a = IntValor
elif b == nameInt:
b = IntValor
c = a - b
start = start + str(c) + '\n'
a = int(a)
b = int(b)
c = a - b
start = start + str(c) + '\n'
elif '<Calculo type="/">' in Console:
a = input('>>;')
b = input('>>;')
if a == nameInt:
a = IntValor
elif b == nameInt:
b = IntValor
c = a / b
start = start + str(c) + '\n'
a = int(a)
b = int(b)
c = a / b
start = start + str(c) + '\n'
elif '<Calculo type="x">' in Console:
a = input('>>;')
b = input('>>;')
if a == nameInt:
a = IntValor
elif b == nameInt:
b = IntValor
c = a * b
start = start + str(c) + '\n'
a = int(a)
b = int(b)
c = a * b
start = start + str(c) + '\n'
elif '<int>' in Console:
nameInt = Console[6:]
IntValor = input('>>;')
IntValor = int(IntValor)
elif '<string>' in Console:
nameString = Console[9:]
StringValor = input('>>;')
StringValor = str(StringValor)
elif '<string type="Rep">' in Console:
nameString2 = Console[20:]
StringValor = input('>>;')
StringValor = str(StringValor)
rep1 = input('>>;')
rep1 = str(rep1)
rep2 = input('>>;')
rep2 = str(rep2)
stringvalorrep = StringValor.replace(rep1, rep2)
elif '<Reais>' in Console:
nameFloat = Console[8:]
valorFloat = input('>>;')
valorFloat = float(valorFloat)
elif '<Logica>' in Console:
nameLogica = Console[9:]
valorLogica = input('>>;')
if valorLogica == "True":
valorLogica = True
elif valorLogica == "False":
valorLogica = False
elif valorLogica == "1":
valorLogica = True
elif valorLogica == "0":
valorLogica = False
else:
valorLogica = bool(valorLogica)
elif 'Start' in Console:
print(start)
elif '<loop> ' in Console:#EM DESENVOLVIMENTO
qvloop = Console[7:]
ConsoleLoop = input('>>;')
ConsoleLoop = str(ConsoleLoop)
qvloop = int(qvloop)
for i in range(qvloop):
start = start + ConsoleLoop + '\n'
elif '<Se type=">">' in Console:#EM DESENVOLVIMENTO
IfCond = input('>>;')
IfCond = int(IfCond)
IfCond2 = input('>>;')
IfCond2 = int(IfCond2)
if IfCond > IfCond2:
while True:
Console = input('>>> ')
if 'imprimir ' in Console:
if Console[9:] == nameInt:
print(IntValor)
elif Console[9:] == nameString:
print(StringValor)
elif Console[9:] == nameString2:
print(stringvalorrep)
elif Console[9:] == nameFloat:
print(valorFloat)
elif Console[9:] == nameLogica:
print(valorLogica)
else:
print(Console[9:])
elif 'break' in Console:
break
else:
while True:
Console = input('>>> ')
if 'imprimir ' in Console:
if Console[9:] == nameInt:
print(IntValor)
elif Console[9:] == nameString:
print(StringValor)
elif Console[9:] == nameString2:
print(stringvalorrep)
elif Console[9:] == nameFloat:
print(valorFloat)
elif Console[9:] == nameLogica:
print(valorLogica)
else:
print(Console[9:])
elif 'break' in Console:
break
|
#ForDictionary
dict={"key1":"Value1", "key2":"Value2", "key3":"Value3"}
print(dict)
print("\n")
for key in dict:
print("for key in dict: ", dict[key])
print("\n")
for key,value in dict.items():
print("for key,value in dict.items(): ", key,value)
print("\n")
for val in dict.values():
print("for val in dict.values(): ", val)
print("\n")
for key in dict.keys():
print("for key in dict.keys(): ", key)
print("\n")
|
class Vehicle:
def general_usage(self):
print ("general use Transportation")
class Car (Vehicle):
def __init__(self):
print ("i am a car")
self.wheels = 4
self.has_roof = True
def specific_usage(self):
print("specific use : commet to work and vaction with family ")
class Moto (Vehicle):
def __init__(self):
print ("i am a moto")
self.wheels = 2
self.has_roof = False
def specific_usage(self):
print("specific use: commet to race and personal use")
c = Car()
c.general_usage()
c.specific_usage()
print (issubclass(Car,Moto))
print (issubclass(Car,Vehicle))
m = Moto()
m.general_usage()
m.specific_usage()
|
# for x in range(5):
# print (x)
# if x ==3:
# break
# solution
# 0
# 1
# 2
# 3
# for x in range(5):
# if x ==3:
# break #(dont continou the loop skip the print (x) thefore we got 012):
# print(x)
# # solution
# 0
# 1
# 2
|
# for letter in 'hello':
# if letter == 'e':
# pass
# print("pass")
# print(letter)
# solution
# h
# pass [ we got pass because the condition of e]
# e
# l
# l
# o
|
def is_unique_v1(string):
"""
Function that verifies if all the characters in a string are unique. It is case sensitive, meaning "A" and "a" are considered different characters
:param string: string to verify for uniqueness.
:return True: if it doesn’t have any duplicate characters
False: otherwise
"""
string_set = set(list(string))
if len(string_set) == len(string):
return True
else:
return False
def is_unique_v2(string):
"""
Function that verifies if all the characters in a string are unique. It is case sensitive, meaning "A" and "a" are
considered different characters. It avoids using extra data structures, but it is SLOW (n^2)
:param string: string to verify for uniqueness.
:return True: if it doesn’t have any duplicate characters
False: otherwise
"""
for char in string:
count = 0
for other_char in string:
if char == other_char:
count += 1
if count > 1:
return False
return True
def is_unique_v3(string):
"""
Function that verifies if all the characters in a string are unique. It is case sensitive, meaning "A" and "a" are
considered different characters. It avoids using extra data structures, but it is SLOW, but a bit faster, n*nlogn
:param string: string to verify for uniqueness.
:return True: if it doesn’t have any duplicate characters
False: otherwise
"""
for i in range(len(string)-1):
for j in range(i+1, len(string)):
if string[i] == string[j]:
return False
return True
def is_unique(string):
return is_unique_v3(string)
|
import sys
def max_number(a, b):
"""
Return the max of two numbers, without using if/else or comparision.
En caso de igualdad, se devolvera 0
:param a: first integer
:param b: second integer
:return: a if a > b, b if b >a
"""
# I want an integer with all zeros except the first bit (the sign), something like 10000...000
int_length = sys.getsizeof(int()) * 8
sign_mask = 1 << int_length - 1
a_sign = (a - b) & sign_mask
a_sign = a_sign >> (int_length - 1)
b_sign = (b - a) & sign_mask
b_sign = b_sign >> (int_length - 1)
return a * b_sign + b * a_sign
|
#!/bin/python
import sys
from graph import *
def findWeight(vertex1, vertex2):
""" Finds the weight between two vertices in accordance to specs given in homework """
# assume lengths will be the same
numDiff = 0
word1 = vertex1.word
word2 = vertex2.word
for n in range(0, len(vertex1.word)):
if word1[n] != word2[n]:
numDiff += 1
if numDiff > 2:
return None
# weight the edges
if numDiff == 1:
return 1
elif numDiff == 2:
return 5
else:
return 0
if __name__ == "__main__":
# make sure there are the proper number of arguments
if len(sys.argv) != 2:
print("Word game program usage:")
print("wordgame.py [filename]")
exit()
# get the file contents and close immediately
filename = sys.argv[1]
fh = open(filename, "r")
fileContent = fh.read()
fh.close()
# build the graph #
# add all the vertices
graph = Graph()
for word in fileContent.split():
# create a new vertex and add it to the graph
vertex = Vertex(word)
graph.addVertex(vertex)
# compare every combination of vertices
for n in range(0, len(graph.vertices)):
for m in range(n, len(graph.vertices)):
weight = findWeight(graph.vertices[n], graph.vertices[m])
# add the edge if it is valid
if weight == 1 or weight == 5:
graph.vertices[n].connect(graph.vertices[m], weight)
# main program loop
while True:
# propt user for a five-letter word and convert to upper case
inputStr = input("Enter a five-letter word: ")
inputStr = inputStr.upper()
# get the vertex from graph
vertex = graph.getVertexByWord(inputStr)
if vertex is None:
print("The word you entered doesn't exist in the graph, please try again")
continue
print("The neighbors of " + inputStr + " are :")
counter = 1
for n in range(0, len(vertex.adj)):
adj = vertex.adj[n]
weight = vertex.weights[n]
end = ""
if counter == 6:
end = "\n"
counter = 0
# print out the adjacent element
print("\t" + adj.word + " (" + str(weight) + ")", end=end)
counter += 1
# add a newline at the end
print()
|
def solution(s):
s=s.lower()
answer = s[0].upper()
sign=1
for word in list(s[1::]):
if sign==0:
answer+=word.upper()
else :
answer+=word
sign=1
if word==" ":
sign=0
return answer
|
def bfs(computers,start,visited,answer):
queue = []
if visited[start]:
return
queue.append(start)
visited[start] = True
while queue :
v = queue.pop(0)
print(v,end=" ")
for ind,val in enumerate(computers[v]):
if (not visited[ind] )and (val==1):
queue.append(ind)
visited[ind] = True
answer.append(1)
def solution(n, computers):
visited = [False] *n
answer=[]
for i in range(n):
bfs(computers,i,visited,answer)
return len(answer)
|
class LinkedList(object):
class Node(object):
def __init__(self, data=None):
self.data = data
self.next = None
self.prev = None
def __repr__(self):
return str(self.data)
def __init__(self):
self.size = 0
self.sntl = self.Node()
self.sntl.next = self.sntl
self.sntl.prev = self.sntl
def __len__(self):
return self.size
def __str__(self):
v = []
v.append('head')
x = self.sntl.next
while x != self.sntl:
v.append('->')
v.append(str(x.data))
x = x.next
return " ".join(v)
def search(self, key):
x = self.sntl.next
while x != self.sntl and x.data != key:
x = x.next
if x == self.sntl:
x = None
return x
def insert(self, x):
node = self.Node(x)
node.next = self.sntl.next
self.sntl.next.prev = node
self.sntl.next = node
node.prev = self.sntl
self.size += 1
def insert_Q(self, x):
node = self.Node(x)
node.prev = self.sntl.prev
node.next = self.sntl.prev.next
self.sntl.prev.next = node
node.next.prev = node
self.size += 1
def delete(self, x):
x.prev.next = x.next
x.next.prev = x.prev
self.size -= 1
|
# Python program showing
# use of json package
import json
# {key:value mapping}
a = {"name": "John",
"age": 31,
"Salary": 25000}
print(a.get('name'))
# conversion to JSON done by dumps() function
b = json.dumps(a)
# printing the output
"""
Output:
{"age": 31, "Salary": 25000, "name": "John"}
As
you
can
see, JSON
supports
primitive
types, like
strings and numbers, as well as nested
lists, tuples and objects
filter_none
edit
play_arrow
brightness_4
# Python program showing that
# json support different primitive
# types
"""
import json
# list conversion to Array
print(json.dumps(['Welcome', "to", "GeeksforGeeks"]))
# tuple conversion to Array
print(json.dumps(("Welcome", "to", "GeeksforGeeks")))
# string conversion to String
print(json.dumps("Hi"))
# int conversion to Number
print(json.dumps(123))
# float conversion to Number
print(json.dumps(23.572))
# Boolean conversion to their respective values
print(json.dumps(True))
print(json.dumps(False))
# None value to null
print(json.dumps(None))
|
#12
planeta=input("ingrese el nombre del planeta en que vive:")
p=int(input("ingrese el % de la contaminacion del planeta:"))
c=int(input("ingrese el % del planeta en su maxima vida:"))
vida=(c-p)
cuerpo_en_destruccion=(vida<49)
print("###################")
print("# vida del planeta #")
print("####################")
print("#")
print("# planeta",planeta)
print("# item:",p,"de contaminacion")
print("# item:",c,"de cuidados")
print("# vida:",vida)
print("#####################")
print("cuerpo_en_destruccion?",cuerpo_en_destruccion)
|
#1
cliente=input("ingrese el nombre del cliente:")
kg=int(input("ingrese nro de kg de manzanas:"))
precio=float(input("ingrese precio de cada unidad:"))
total=(precio*kg)
comprador_compulsivo = (total > 130)
print(" + #################### +")
print(" + # voleta de compra +")
print(" + #################### +")
print("#")
print(" + # cliente:",cliente)
print(" + # item :",kg," kg manzanas")
print(" + # P.U. : s/.",precio)
print(" + # total : s/",total)
print(" + #################### +")
print("comprador_compulsivo?:",comprador_compulsivo)
|
#13
ferreteria=input("ingrese el nombre de la ferreteria:")
f=int(input("ingrese la cantidad de fierro comprado:"))
precio=float(input("ingrese precio de c.u de fierro:"))
total=(precio*f)
tienda_grande= (total > 600)
print(" + #################### +")
print(" + # voleta de compra +")
print(" + #################### +")
print("#")
print(" + # ferreteria:",ferreteria)
print(" + # item :",f," fierros")
print(" + # P.U. : s/.",precio)
print(" + # total : s/",total)
print(" + #################### +")
print("tienda_grande?:",tienda_grande)
|
#We will write program to convert years to seconds
years = int(input("Please enter number of years : "))
'''
No of months = 12
No of days = 365
No of hours in a day = 24
No of minutes in hour = 60
No of seconds in minute = 60
'''
calc_of_seconds = years * 12 * 365 * 24 * 60 * 60
print((f"{years} years contain {calc_of_seconds} seconds"))
|
def insertBeg(head,x):
temp=head(x)
if head==None:
temp.next=temp
return temp
curr=head
while curr.next!=head:
curr=curr.next
curr.next=temp
temp.next=head
return temp
|
# 03 August 07:11AM-07:16AM 5min
# SELF #GFG
# Logic 2min 1min
# Coding 0min 2min
# link - https://practice.geeksforgeeks.org/problems/sum-of-digits-of-a-number/1/?track=DS-Python-Recursion&batchId=273
def fun(n):
if n/10==0:
return 1
return (n%10)+fun(n//10)
print(fun(64))
|
# 05 August 05:43PM-05:48PM 5min
# SELF
# Logic 5min
# Coding 0min
# Link https://practice.geeksforgeeks.org/problems/power-of-numbers-1587115620/1/?track=DS-Python-Recursion&batchId=273
# def Power(n,r):
r='56'
s=reversed(r)
print(int(s))
|
def mergesort(arr,l,m,r):
i,j,k=0,0,l
left=arr[l:m+1]
right=arr[m+1:r]
while i<len(left) and j<len(right):
if arr[i]<arr[j]:
arr[k]=arr[i]
k=k+1
i=i+1
else:
arr[k]=arr[j]
k=k+1
j=j+1
while i<len(left):
arr[k]=arr[i]
i=i+1
k=k+1
while j<len(right):
arr[k]=arr[j]
j=j+1
k=k+1
return arr
arr=[4,5,25,23,52]
l=0
r=len(arr)-1
m=len(arr)//2
print(mergesort(arr,l,m,r))
|
# 27 July 06:37AM-06:57AM Completed by SELF 20min
# Write a Python function that takes a list of words and return the longest word and the length of the longest one. Go to the editor
# Sample Output:
# Longest word: Exercises
# Length of the longest word: 9
# ------My Code--------
s="highest this is the jdifbhjvrvjkfdb peak fsm efnkfkwjf"
l=s.split()
print(l)
s=0
d=''
for i in range(len(l)):
# print(l[i])
for j in range(len(l)):
# print(l[j])
if(len(l[i])>len(l[j])):
q=len(l[i])
if(q>s):
s=q
d=l[i]
print(d,s)
# -----Solution From Website-------
def find_longest_word(words_list):
word_len = []
for n in words_list:
word_len.append((len(n), n))
word_len.sort()
return word_len[-1][0], word_len[-1][1]
result = find_longest_word(["PHP", "Exercises", "Backend"])
print("\nLongest word: ",result[1])
print("Length of the longest word: ",result[0])
|
# 03 August 06:41PM-06:51AM 10min
# SELF #GFG
# Logic 3min 1min
# Coding 6min 1min
# link - https://practice.geeksforgeeks.org/problems/factorial-using-recursion/1/?track=DS-Python-Recursion&batchId=273#
def fun(n):
if n==1:
return 1
return n*fun(n-1)
n=int(input())
print(fun(n))
|
# 7:00AM-7:25AM 25min Not Completed
# Kth smallest element
# Medium Accuracy: 46.66% Submissions: 87860 Points: 4
# Given an array arr[] and a number K where K is smaller than size of array, the task is to find the Kth smallest element in the given array. It is given that all array elements are distinct.
# Example 1:
# Input:
# N = 6
# arr[] = 7 10 4 3 20 15
# K = 3
# Output : 7
# Explanation :
# 3rd smallest element in the given
# array is 7.
# Example 2:
# Input:
# N = 5
# arr[] = 7 10 4 20 15
# K = 4
# Output : 15
# Explanation :
# 4th smallest element in the given
# array is 15.
# ----------------------------------
# -------------Coding---------------
# def kmax(arr,k):
# s=arr[0]
# q=[]
# for i in range(len(arr)-1):
# if(arr[i]>arr[i+1]):
# q.append(arr[i+1])
# else:
# q.append(arr[i])
# for i in range(len(q)):
# s=q[k]
# return s
# arr=[1,4,7,2,45]
# k=4
# print(kmax(arr,k))
def kthSmallest(arr, k):
'''
arr : given array
l : starting index of the array i.e 0
r : ending index of the array i.e size-1
k : find kth smallest element and return using this function
'''
for i in range(k-1):
arr.remove(min(arr))
return min(arr)
arr = [1, 4, 7, 2, 45]
k = 4
print(kthSmallest(arr, k))
|
# Link = https://leetcode.com/problems/merge-intervals/
# 20-July 07:15Am-07:30AM 15 min Not Completed
# 56. Merge Intervals
# Medium
# 8363
# 403
# Add to List
# Share
# Given an array of intervals where intervals[i] = [starti, endi], merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input.
# Example 1:
# Input: intervals = [[1,3],[2,6],[8,10],[15,18]]
# Output: [[1,6],[8,10],[15,18]]
# Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6].
# Example 2:
# Input: intervals = [[1,4],[4,5]]
# Output: [[1,5]]
# Explanation: Intervals [1,4] and [4,5] are considered overlapping.
intervals = [[1,3],[2,6],[8,10],[15,18]]
for i in range(len(intervals)):
for j in range(len(intervals)):
if( intervals[i][j+1]> intervals[i+1][j]):
intervals[i][j+1]= intervals[i+1][j+1]
intervals.remove(intervals[i+1])
print(intervals)
|
# 03 August 06:56PM-07:03AM 9min
# SELF #GFG
# Logic 3min 0min
# Coding 2min 4min
# link - https://practice.geeksforgeeks.org/problems/count-total-digits-in-a-number/1/?track=DS-Python-Recursion&batchId=273
# My Code------
def fun(n):
if n//10==0:
return 1
return 1+fun(n//10)
print(fun(43874))
# Prashant Code-----
def __init__(self):
self.count=0
def countDigits(self, n):
if n==0:
return 1
else:
self.count+=1
self.countDigits(n//10)
return self.count
|
# 30 July 1:10PM-01:26PM 6min
# SELF GFG
# Logic 3min 5min
# Coding 3min 5min
# 30 July 08:15PM-08:30PM 15min
# GFG
# Logic 10min
# Coding 5min
# Link https://practice.geeksforgeeks.org/problems/find-triplets-with-zero-sum/1/?problemType=functional&difficulty[]=-1&difficulty[]=0&page=1&sortBy=submissions&category[]=Hash&query=problemTypefunctionaldifficulty[]-1difficulty[]0page1sortBysubmissionscategory[]Hash#
# Find all triplets with zero sum
# Difficulty Level : Medium
# Last Updated : 12 Jul, 2021
# Given an array of distinct elements. The task is to find triplets in the array whose sum is zero.
# Examples :
# Input : arr[] = {0, -1, 2, -3, 1}
# Output : (0 -1 1), (2 -3 1)
# Explanation : The triplets with zero sum are
# 0 + -1 + 1 = 0 and 2 + -3 + 1 = 0
# Input : arr[] = {1, -2, 1, 0, 5}
# Output : 1 -2 1
# Explanation : The triplets with zero sum is
# 1 + -2 + 1 = 0
# ---My Code----
# arr=[-7,-1,0,3,4]
# arr.sort()
# b=[]
# for i in range(len(arr)):
# if(arr[i]==0):
# b.append(arr[i])
# b.append(arr[i-1])
# b.append(arr[i+1])
# if sum(b)==0:
# print("1")
# else:
# print("0")
# ---GFG Code---
def findTriplets(arr, n):
found = False
for i in range(0, n-2):
for j in range(i+1, n-1):
for k in range(j+1, n):
if (arr[i] + arr[j] + arr[k] == 0):
# print(arr[i], arr[j], arr[k])
found = True
# print("1")
# If no triplet with 0 sum
# found in array
if (found == True):
print("exist")
elif(found == False):
print(" not exist ")
# else (found == True):
# print("1")
# Driver code
arr = [87, 0, 100, -3, 71 ,-1, 44]
n = len(arr)
findTriplets(arr, n)
|
# 27 July 07:03AM-07:07AM Completed by SELF 4min
# Write a Python program to remove the nth index character from a nonempty string.
# ------My Code--------
s="This is good as well as very good"
l=s.split()
print(l)
l.pop(3)
print(l)
# -----Solution From Website-------
def remove_char(str, n):
first_part = str[:n]
last_part = str[n+1:]
return first_part + last_part
print(remove_char('Python', 0))
print(remove_char('Python', 3))
print(remove_char('Python', 5))
|
a=[20,4,23,5,2]
a.sort()
print(a)
a=[20,4,23,5,2]
a.sort(reverse=True)
print(a)
a=["courses","gfg","pyhton"]
a.sort()
print(a)
def MyFun(s):
len(s)
a=["courses","gfg","pyhton"]
a.sort(key=MyFun)
a.sort(reverse=True)
print(a)
# print(a)
|
from Book import Book
from Library import Library
from queue import PriorityQueue
def find_book_in_array(book_id, master_array):
for book in master_array:
if book.get_id() == book_id:
return book
# def get_max_rating(libraries):
# max = -9999999
# for library in libraries:
#
if __name__ == "__main__":
in_file = open('input.txt', 'r')
out_file = open('output.txt', 'w')
##INPUT
first_line = in_file.readline().strip().split(' ')
number_of_total_books = int(first_line[0])
number_of_total_libraries = int(first_line[1])
deadline = int(first_line[2])
current_day = 0
book_scores = in_file.readline().strip().split(' ')
master_books_array = {}
for i in range(number_of_total_books):
new_book = Book(i, int(book_scores[i]))
master_books_array[i] = new_book
print("created master book array")
libraries = []
for n in range(number_of_total_libraries):
library_atttributes = in_file.readline().strip().split(' ')
books_in_library = in_file.readline().strip().split(' ')
# set_of_books = PriorityQueue()
set_of_books = []
for i in books_in_library:
# book_to_put_in = find_book_in_array(int(i), master_books_array)
# set_of_books.put((book_to_put_in.get_score(), book_to_put_in))
set_of_books.append(master_books_array[int(i)])
new_library = Library(n, set_of_books, int(library_atttributes[1]), int(library_atttributes[2]))
libraries.append(new_library)
##-------
##COMPUTING
output_string = ""
chosen_libraries = 0
while current_day < deadline:
print(str(current_day) + "/" + str(deadline))
if not libraries:
break
mvp = libraries[0]
mvp_rating = mvp.compute_rating(current_day, deadline)
for library in libraries:
library_rating = library.compute_rating(current_day, deadline)
if library_rating > mvp_rating:
mvp = library
mvp_rating = library_rating
libraries.remove(mvp)
books_to_remove = mvp.get_books()
for book in books_to_remove:
book.scanned = True
if mvp.n <= 0: break
chosen_libraries += 1
output_string += str(mvp.id) + " " + str(len(books_to_remove)) + "\n"
for book in books_to_remove:
output_string += str(book.get_id()) + " "
output_string += "\n"
current_day += mvp.time_to_sign_up
##-------
##OUTPUT
out_file.write(str(chosen_libraries) + "\n" + output_string)
|
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
elif x < 10:
return True
result = 0
pre = x
while x != 0:
y = x%10
x = x/10
result = 10*result + y
print result
if result == pre:
return True
return False
obj = Solution()
print obj.isPalindrome(11)
|
def isValid(s):
check = {'(':')','{':'}','[':']'}
brackets = list(s)
current = []
result = 0
for i in brackets:
if check.has_key(i):
current.append(i)
elif len(current) != 0:
if i != check[current.pop()]:
return False
else:
return False
return True
print isValid("[")
|
# 编程判断一个人是否是微博活跃用户
x = int(input("最近三天登录次数是?"))
y = int(input("最近三天发微博数是?"))
print("该用户是",end="") #end=""是什么意思?表示的是以换行符结尾
# 判断是否是非常活跃用户
if x > 20 or y > 10 :
print("非常活跃用户")
# 判断是否是活跃用户
elif 10 <= x < 20 or 5 <= y < 10:
print("活跃用户")
# 判断是否是消极用户
elif x < 3 and y <= 1:
print("消极用户")
# 判断是否是普通用户
else:
print("普通用户")
|
import random
confirmed_friends = []
friends_dict = {}
try:
num_friends = int(input("Enter the number of friends joining"
" (including you):\n"))
except ValueError:
print("\nNo one is joining for the party")
else:
if num_friends >= 1:
print("\nEnter the name of every friend"
" (including you), each on a new line:")
for num in range(num_friends):
confirmed_friends.append(input())
bill = int(input("\nEnter the total bill value:\n"))
if input('\nDo you want to use the "Who is lucky?"'
' feature? Write Yes/No:\n').lower() == "yes":
lucky_one = random.choice(confirmed_friends)
print()
print(lucky_one, "is the lucky one!")
confirmed_friends.remove(lucky_one)
total = round(bill / (num_friends - 1), 2)
friends_dict = dict.fromkeys(confirmed_friends, total)
friends_dict[lucky_one] = 0
print()
print(friends_dict)
else:
print("\nNo one is going to be lucky")
total = round(bill / num_friends, 2)
friends_dict = dict.fromkeys(confirmed_friends, total)
print()
print(friends_dict)
else:
print("\nNo one is joining for the party")
|
"""Example for getting the data from a station."""
import asyncio
import aiohttp
from luftdaten import Luftdaten
SENSOR_ID = 155
async def main():
"""Sample code to retrieve the data."""
async with aiohttp.ClientSession() as session:
data = Luftdaten(SENSOR_ID, loop, session)
await data.get_data()
if not await data.validate_sensor():
print("Station is not available:", data.sensor_id)
return
if data.values and data.meta:
# Print the sensor values
print("Sensor values:", data.values)
# Print the coordinates fo the sensor
print("Location:", data.meta['latitude'], data.meta['longitude'])
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
|
#!/usr/bin/python3.6
#EXERCICE : 1b-dic
#DESCRIPTION : Trier et stocker les noms saisis par l'utilisateur par ordre alphabétique dans une collection.
#NOM : SEGHIR
#PRENOM : Souleimane
#DATE : 23/10/2018
def addDic(): #Fonction appelée par le script.
name_dic={} #On crée un liste vide.
i=0 #Indice de la position dans le tableau (0 correspond à la position 1).
while 1: #Boucle infine pour répéter l'opération.
print("Entrez le nom à ajouter ou \"q\" pour quitter.")
saisie=input() #On associe une variable à un champ input vide.
if saisie == "q": #Si la saisie correspond à "q", on quitte la boucle
print("fin de la saisie")
break
else:
name_dic[str(i)]=saisie #Sinon on stock la saisie dans la liste.
i=i+1 #On incrémente i de 1 pour passer à l'emplacement suivant dans la liste.
name_dic=sorted(name_dic.values()) #A la sortie de la boucle, on trie le contenu de la liste par ordre alphabétique.
print(name_dic) #Affichage de la liste.
addDic() #Appel de la fonction.
|
# 구구단 구하기
# def GuGu(a):
# result = []
# for i in range(1, 10):
# result.append(a*i)
# return result
# c = GuGu(3)
# print(c)
# 1000 미만의 수에서 3과 5의 배수들의 합 구하기
# l = []
# result = 0
# for i in range(1, 1000):
# if (i % 3) == 0 or (i % 5) == 0:
# l.append(i)
# result += i
# print(result)
# print(l)
# 게시판 페이징
# def getTotalPage(m, n):
# page = m // n
# if m % n:
# page += 1
# return page
# print(getTotalPage(5, 10))
# print(getTotalPage(15, 10))
# print(getTotalPage(25, 10))
# print(getTotalPage(30, 10))
|
# Q1
# a = 80
# b = 75
# c = 55
# d = (a + b + c) / 3
# print(d) # 70.0
# Q2
# a = 13
# print(a % 2) # 1 (나머지가 1이므로 홀수)
# Q3
# a = "881120-1068234"
# print(a[:6]) # 881120
# print(a[7:]) # 1068234
# Q4
# pin = "881120-1068234"
# print(pin[-7]) # 1
# Q5
# a = "a:b:c:d"
# print(a.replace(':','#')) # a#b#c#d
# Q6
# a = [1, 3, 5, 4, 2]
# a.sort()
# a.reverse()
# print(a) # [5, 4, 3, 2, 1]
# Q7
# a = ['Life','is','too','short']
# print(" ".join(a)) # Life is too short
# Q8
# a = (1, 2, 3)
# a = a + (4,)
# print(a) # (1, 2, 3, 4)
# Q9
# a = dict()
# a['name'] = 'python'
# a[('a',)] = 'python'
# a[250] = 'python'
# # a[[1]] = 'python' # TypeError: unhashable type: 'list', 리스트는 Key 로 사용될 수 없다.
# print(a)
# Q10
# a = {'A':90, 'B':80, 'C':70}
# a.pop('B')
# print(a) # {'A': 90, 'C': 70}
# Q11
# a = [1, 1, 1, 2, 2, 3, 3, 3, 4, 4, 5]
# a = list(set(a))
# print(a) # [1, 2, 3, 4, 5]
# Q12
# a = b = [1, 2, 3]
# a[1] = 4
# print(b) # [1, 4, 3]
|
"""
Graham Earley, 2015.
Read more about the algorithm here:
https://en.wikipedia.org/wiki/Metropolis–Hastings_algorithm
"""
import random
import numpy as np
from CharacterFrequencyCalibrator import CharacterFrequencyCalibrator
from SwapEncryptor import SwapEncryptor
def calculate_score(text, calibrator):
score = 0.0
i = 0
while i < len(text) - 2:
code_char_pair = text[i:i+2]
if code_char_pair in calibrator.frequencies_dict:
score += np.log(calibrator.frequencies_dict[code_char_pair])
i += 1
return score
def swap_chars_in_text(text, swap_char1, swap_char2):
# Build up the swapped text:
swapped_text = ""
for char in text:
if char == swap_char1:
swapped_text += swap_char2
elif char == swap_char2:
swapped_text += swap_char1
else:
swapped_text += char
return swapped_text
encryptor = SwapEncryptor("qwertyuiopasdfghjklzxcvbnm")
calibrator = CharacterFrequencyCalibrator("ShakespeareWorks.txt")
encrypted_text = encryptor.encrypt(open('secret.txt', 'r').read().lower())
letters = "qwertyuiopasdfghjklzxcvbnm"
runtimes = 3000
for run in range(runtimes):
# Pick two characters to swap (uniformly, at random)
swap_char1 = random.choice(letters)
swap_char2 = random.choice(letters)
# Determine whether to accept the proposal by comparing scores:
swapped_text = swap_chars_in_text(encrypted_text, swap_char1, swap_char2)
proposed_score = calculate_score(swapped_text, calibrator)
current_score = calculate_score(encrypted_text, calibrator)
acceptance_ratio = proposed_score - current_score
unif_rand = np.random.uniform()
if unif_rand <= np.exp(acceptance_ratio):
encrypted_text = swapped_text
if (run+1)%int(runtimes/10)==0:
print(run+1, current_score, '\n', encrypted_text[:140],'\n')
print(80*'-'+'\n', encrypted_text)
|
def getPrimes(_max) :
primes = [True] * (_max + 1)
primes[0] = primes[1] = False
ret = []
for i in range(2, _max + 1) :
if primes[i] :
ret.append(i)
t = i * 2
while t <= _max :
primes[t] = False
t += i
return ret
|
import sieve
import math
def lcf(nums) :
_lcf = 1
# should be global... but
primes = sieve.getPrimes(max(nums))
for prime in primes :
nums = [num for num in nums if num != 1]
if len(nums) == 1 : return _lcf * num[0]
maxCnt = 0
for num in nums :
cnt = 0
while num % prime == 0 :
num /= prime
cnt += 1
maxCnt = max(maxCnt, cnt)
_lcf *= prime ** maxCnt
return _lcf
print lcf(range(1, 21))
|
#python3
'''
学以致用,边学边练,在开发中发挥强大的生产力
下载python解释器: https://www.python.org/downloads/release/
'''
"""
机器指令-》cpu
"""
#输入、输出
#用户输入 输出函数
#字符在计算机存储为0和1,ASCII码1个字节,gbk汉字为2个字节,utf-8汉字3个字节,是对unicode万国码(都是2个字节)的优化和压缩
'''
notice = "请输入:"
#print notice
str = input(notice)
type_str = type(str)
print (type_str)
num = int(str)
type_num = type(num)
print (type_num)
'''
"""
print ("%s is week %d"%('today',1))
print('''
多行
输出
''')
name = 'llz'
age = 26
print(
'''
{_name}
{_age}
'''.format(
_name = name,
_age=age
)
)
"""
'''
import sys
print("hello world")
'''
#注释,增加程序可读性
'''
多行注释
'''
'''
变量以及类型
变量是存储数据的
变量类型 type(变量)
数字:int(有符号整型)、long(长整型)、float(浮点型)、complex(复数)
布尔类型:True、False
字符串
列表list
元祖tuple
字典dictionary
运算符
算术运算符:// 取商的整数部分
** 幂运算2的3次方
'''
"""
num = '12'
num2 = "12a"
print(num.isdigit())
print(num2.isdigit())
"""
"""
a = 12
b = 5
c = a+b
print ( c)
id_a = id(a)
print (id_a) #变量a在内存中的编号
type_a = type(a)
print (type_a) #a的类型
b = 12.12
c = b
id_b = id(b)
id_c = id(c)
print (id_b)
print (id_c)
type_b = type(b)
type_c = type(c)
print (type_b)
print (type_c)
c = "hello"
type_b = type(b)
type_c = type(c)
print (type_b)
print (type_c)
del(a)
#print a
"""
#byte字节类型。二进制
"""
str = '李利钊'
print(str)
print(str.encode(encoding='utf8'))
print(str.encode(encoding='utf8').decode(encoding='utf8'))
"""
#列表
"""
names = ['沙瑞金','侯亮平','李达康']
print(names[1:3]) #切片
print(names[-1]) #切片
print(names[-2:]) #切片
names.append('祁同伟')
print(names)
names.insert(3,'易学习')
print(names)
names[4] = '高育良'
print(names)
names.remove('高育良')
print(names)
del names[1]
print(names)
names.pop(-2)#默认最后一个
print(names)
print(names.index('易学习'))
names.append('沙瑞金')
print(names.count('沙瑞金'))
print(names)
names.sort()
print(names)
names2 = ['林华华','陆亦可']
names.extend(names2)
print(names)
names.append(['蔡成功','丁义珍'])
name3 = names.copy()#浅复制,只会复制第一层,二层以上引用地址
print(name3)
name3[2] = '李达康'
name3[5][0] = '欧阳菁'
print(names)
print(name3)
import copy#导入copy模块
name3 = copy.deepcopy(names)#全复制
print(name3)
name3[2] = '李达康'
name3[5][0] = '高小琴'
print(names)
print(name3)
for name in names:
print (name)
"""
#元祖.就是列表,只能看不能改。只有count和index方法
"""
names4 = ('孙悟空','猪八戒')
print(names4[0])
print(names4.count("猪八戒"))
print(names4.index('猪八戒'))
print(len(names4))
for key,value in enumerate(names4):
print(key,value)
"""
"""
a = 5
b = 3
max = a if a > b else b#三元运算符
min = b if a > b else a
print("max:",max)
print("min:",min)
"""
#流程控制
'''
import getpass
password = getpass.getpass("密码:")
print(password)
_password = '123'
if password == _password and 1:
print("登录成功")
else:
print("登录失败")
'''
'''
true_age = 26
count = 0
while count < 3:
guess_age = input('猜猜我多大了')
guess_age =int(guess_age)
if true_age == guess_age :
print('猜对了')
break
elif true_age > guess_age :
print('往大了猜')
else :
print('往小了猜')
count += 1
#else只在循环正常循环完时进入,break循环不进入
else:
print("已经猜3次了,不能再猜了")
# print (count)
for i in range(0,3,1) :
guess_age = input('for猜猜我多大了')
guess_age =int(guess_age)
if true_age == guess_age :
print('猜对了')
break #continue结束本次循环,继续下一次循环
elif true_age > guess_age :
print('往大了猜')
else :
print('往小了猜')
count += 1
else:
print("已经猜3次了,不能再猜了")
for i in range(0,10,3):
print(i)
'''
'''
模块
'''
"""
import sys
print(sys.argv)#运行文件的参数
print(sys.path)#打印当前目录和环境变量,从这些位置找库文件
import os
cmd_res = os.popen('dir')#cmd命令执行结果的地址
print(cmd_res)
cmd_res = cmd_res.read()
print(cmd_res)
# os.makedirs('par_dir/sub_dir')#递归创建子目录
#os.mkdir('par_dir1')
"""
#简单函数
"""
def add(x,y):
z = x + y
return z
res = add(3,5)
print (res)
"""
#字符串函数
name = 'llz'
print(name.capitalize())#首字母大写
print(name.count('l'))#字母个数
print(name.center(10,'-'))#打印10个字符,字符串放中间
print(name.endswith('z'))#是否以z结尾
space = "a\tc"
print(space.expandtabs(10))#把制表符替换为几个空格
|
import sys
import numpy as np
primes = set([2])
def is_prime(x):
global primes
for i in set(list( primes ) + range(max(primes),int(np.sqrt(x)))):
if x%i==0:
return False
return True
def more_primes(min_n, max_n):
global primes
for i in xrange(min_n,max_n):
if is_prime(i):
primes.add(i)
print "max prime:" + str(max(primes))
if __name__ == "__main__":
if len(sys.argv)==1:
print "Enter the number for prime factors"
sys.exit(0)
num = long(sys.argv[1])
more_primes( 2, num)
print "Primes:" + str(primes)
print "sum:" + str(sum(primes))
|
# read in the input
x1, y1, x2, y2 = map(int, input().split())
x3, y3, x4, y4 = map(int, input().split())
a = x2 - x1
b = x4 - x3
if (x2-x1) != 0 and (x4-x3) != 0:
slope_1 = (y2-y1)/(x2-x1)
#abs(slope_1)
slope_2 = (y4-y3)/(x4-x3)
#abs(slope_2)
if slope_1-slope_2 == 0:
print('parallel')
else:
print('not parallel')
else:
print('parallel')
# now solve the problem. good luck :D
|
# read the input
string = input('')
# solve the problem
vowels = ['a','e','i','o','u','A','E','I','O','U']
count = 0
for letters in string:
if letters in vowels:
count=count+1
# output the result
print(count)
|
# #ファイルの操作
# # f = open('test.txt', 'w')
# # f.write('Test\n')
# # # print('My', 'name', 'is', 'Mike', sep='#', end='!', file=f)
# # f.close()
# # with open('test.txt', 'w') as f:
# # f.write('Test\n')
# s = """\
# AAA
# BBB
# CCC
# DDD
# """
# with open('test.txt', 'r') as f:
# # while True:
# # chunk = 2
# # line = f.readline()
# # print(line, end='')
# # if not line:
# # break
# # print(f.tell())
# # print(f.read(1))
# # print(f.tell())
# # print(f.read(1))
# # f.seek(5)
# # print(f.read(1))
#csvファイルへの書き込み
# import csv
# with open('test.csv', 'w') as csv_file:
# fieldnames = ['Name', 'Count']
# writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
# writer.writeheader()
# writer.writerow({'Name': 'A', 'Count': 1})
# with open('test.csv', 'r') as csv_file:
# reader = csv.DictReader(csv_file)
# for row in reader:
# print(row['Name'], row['Count'])
#terminalで open test.csv
#ファイル操作
# import os
# import pathlib
# import glob
# import shutil
# print(os.path.exists('test.txt'))
# print(os.path.isfile('test.txt'))
# print(os.path.isdir('test.txt'))
# # os.rename('test.txt', 'renamed.txt')
# os.symlink('renamed.txt', 'symlink.txt')
# os.mkdir('test_dir')
# os.rmdir('test_dir')
# pathlib.Path('empty.txt').touch()
# os.remove('empty.txt')
# os.mkdir('test_dir')
# os.mkdir('test_dir/test_dir2')
# print(os.listdir('test_dir'))
# pathlib.Path('test_dir/test_dir2/empty.txt').touch()
# shutil.copy('test_dir/test_dir2/empty.txt',
# 'test_dir/test_dir2/empty2.txt')
# print(glob.glob('test_dir/test_dir2/*'))
# shutil.rmtree('test_dir')
# print(os.getcwd())
# tarfileの圧縮展開
# import tarfile
# with tarfile.open('test.tar.gz', 'w:gz') as tr:
# tr.add('test_dir')
# with tarfile.open('test.tar.gz', 'r:gz') as tr:
# # tr.extractall(path='test_tar')
# with tr.extractfile('test_dir/sub_dir/sub_text.txt') as f:
# print(f.read())
# import zipfile
# with zipfile.ZipFile('test.zip', 'w') as z:
# import tempfile
# with tempfile.TemporaryFile
# import subprocess
# subprocess.run(['ls', '-al'])
|
# https://www.hackerrank.com/challenges/electronics-shop/problem
# with itertools
from itertools import product
def getMoneySpent(keyboards, drives, b):
prod = list(product(keyboards,drives))
prods = [x[0]+x[1] for x in prod if x[0]+x[1] <= b]
if len(prods) == 0:
return -1
return max(prods)
# without itertools
def getMoneySpent(keyboards, drives, b):
keyboards = sorted(keyboards)
drives = sorted(drives)
maxp = -1
for i in range(len(keyboards)):
for j in range(len(drives)):
cur = keyboards[i] + drives[j]
if cur > b:
break
else:
if cur > maxp:
maxp = cur
return maxp
|
## Declarando Variaveis 2
a = 5
b = "doodoo"
c = 1.3
print(type(a))
print(type(b))
print(type(c))
print(type(10 > 5))
## Declarando Variaveis 2.1
#a) Lista
classe = ['healer', 'warrior', 'druid', 'assassin', 'mage']
print(type(classe))
##b) Conjunto
idades = {62,58,27,34,12}
print(type(idades))
#c) Dicionario
dicionario = {
'hello':'ola',
'food':'comida',
'hour':'hora',
'time':'tempo'}
print(type(dicionario))
#d) Tupla
comidas = ('pizza','lasanha','hamburguer', 'pepeka')
print(type(comidas))
## Fluxo de Controle
#a) if
a = 27
b = 12
c = 38
d = 20
if a > b:
print('ta certo isso ae')
#b) elif
if a < b:
print('ta errado isso aê')
elif a > b:
print('ai ta certo.')
#c) else
if a > b:
print('a é maior que b')
else:
print('oxi')
## Loops e iterações
#d)
palavras = ['ameba', 'snow cabeção', 'rafa careca', 'rodrigo smilinguido', 'portugues viado', 'breno gostosao']
for x in palavras:
print(x)
#e)
...
#f)
a = 25
while a < 30:
print(a)
a += 25
#g)
idades = [1,2,3,4,5,6,7,8,9,10]
for x in range(10):
print(idades)
#h)
for x in range(12):
if x == 9: break
print(x)
else:
print("Parei")
## Funções
#i)
def my_function(gays):
print(gays + 'é gay')
my_function('Rodrigo')
my_function('Tiago')
my_function('Snow')
my_function('Snake')
#j)
def my_function(x):
return 30 * x
print(my_function(5))
print(my_function(2))
print(my_function(7))
#k)
def my_function(e, deus):
print(e + " " + deus)
my_function("Raul", "Não sabe programar")
|
from abc import ABCMeta, abstractmethod
import functools
# Abstract class declaration
# This ensures compatibility between Python 2 and 3 versions, since in
# Python 2 there is no ABC class
ABC = ABCMeta('ABC', (object,), {})
class Backend(ABC):
"""
Base class for RDataFrame backends. Subclasses of this class need to
implement the 'execute' method.
Attributes:
supported_operations (list): List of operations supported by the
backend.
initialization (function): Store user's initialization method, if
defined.
"""
supported_operations = [
'Define',
'Filter',
'Histo1D',
'Histo2D',
'Histo3D',
'Profile1D',
'Profile2D',
'Profile3D',
'Count',
'Min',
'Max',
'Mean',
'Sum',
'Fill',
'Report',
'Range',
'Take',
'Snapshot',
'Foreach',
'Reduce',
'Aggregate',
'Graph',
'AsNumpy'
]
initialization = staticmethod(lambda: None)
def __init__(self, config={}):
"""
Creates a new instance of the desired implementation of :obj:`Backend`.
Args:
config (dict): The config object for the required backend. The
default value is an empty Python dictionary: :obj:`{}`.
"""
self.config = config
@classmethod
def register_initialization(cls, fun, *args, **kwargs):
"""
Convert the initialization function and its arguments into a callable
without arguments. This callable is saved on the backend parent class.
Therefore, changes on the runtime backend do not require users to set
the initialization function again.
Args:
fun (function): Function to be executed.
*args (list): Variable length argument list used to execute the
function.
**kwargs (dict): Keyword arguments used to execute the function.
"""
cls.initialization = functools.partial(fun, *args, **kwargs)
fun(*args, **kwargs)
def check_supported(self, operation_name):
"""
Checks if a given operation is supported
by the given backend.
Args:
operation_name (str): Name of the operation to be checked.
Raises:
Exception: This happens when `operation_name` doesn't exist
the `supported_operations` instance attribute.
"""
if operation_name not in self.supported_operations:
raise Exception(
"The current backend doesn't support \"{}\" !"
.format(operation_name)
)
@abstractmethod
def execute(self, generator):
"""
Subclasses must define how to run the RDataFrame graph on a given
environment.
"""
pass
|
#dice rolling simulator
import random
import string
def dice_rolling():
i = True
while i is True:
print 'You have rolled: ', random.randint(1,6)
roll = raw_input('Roll the dice? (Y) / (N) : ')
if roll == ('Y' or 'y'):
i = True
else:
i = False
dice_rolling()
|
import os
def rename_files():
#(1) get file names from a folder
file_list = os.listdir(r"C:\Python27\prank") #r stands for rawpath
print file_list
saved_path = os.getcwd() #tells python to use the current working directory
print ("current working directory is" +saved_path)
'''now we see that python is looking in the folder python27,
instead of prank, so directory change is required'''
os.chdir(r"C:\Python27\prank") #directory is changed
#(2) for each file, rename filename
for file_name in file_list:
print("old name - "+file_name)
print("new name - "+file_name.translate(None,"0123456789"))
os.rename(file_name,file_name.translate(None,"0123456789"))
os.chdir(saved_path)
rename_files()
|
#coding:utf8
import numpy as np
import time
def RadixSort(A,d):
B = A[:]
for i in range(d-1,-1,-1):
C = np.zeros(256,dtype=np.int32)
AA = B[:]
for a in AA:
C[ord(a[i])] += 1
for j in xrange(1,256):
C[j] += C[j-1]
for k in range(len(AA)-1,-1,-1):
B[ C[ord(AA[k][i])] -1 ] = AA[k]
C[ord(AA[k][i])] -= 1
return B
x = ["COW", "DOG", "SEA", "RUG", "ROW", "MOB", "BOX", "TAB", "BAR", "EAR", "TAR", "DIG", "BIG", "TEA", "NOW", "FOX"]
print RadixSort(x,3)
|
# coding:utf8
import numpy as np
import time
def qsort(A,p,r):
if p<r:
q = partition(A,p,r)
qsort(A,p,q-1)
qsort(A,q+1,r)
def partition(A,p,r):
x = A[r]
i = p
for j in xrange(p,r):
if A[j] <= x:
tmp = A[j]
A[j] = A[i]
A[i] = tmp
i += 1
A[r] = A[i]
A[i] = x
return i
n = 1000000
x = np.random.rand(n)
#print x
t1 = time.time()
qsort(x,0,len(x)-1)
t2 = time.time()
print 'n = ',n,'cost time: ', t2-t1
#print x
|
###################################
##| |##
##| |##
##| Rocky Vargas |##
##| |##
##| |##
###################################
# This function is used to allow the user to input numbers.
def getIntInput(message):
first = True
while True:
try:
if first:
return int(input(message))
else:
return int(input("Error! Enter a number: "))
except:
first = False
# This function allows the user to enter a list of integers.
def getListInput():
listLength = getIntInput("How many integers would you like within your list? ")
listNumbers =[]
for i in range(listLength):
listNumbers.append(getIntInput("Enter integer number %d: "%(i+1)))
return listNumbers
# This function allows the user to enter a list a strings.
def getListStringInput():
listLength = getIntInput("How many items would you like within your list? ")
listNumbers =[]
for i in range(listLength):
listNumbers.append(input("Enter item number %d: "%(i+1)))
return listNumbers
# This function condenses a list.
def condenseList(numberList):
for x in range(len(numberList) - 1):
if numberList[x] == numberList[x + 1]:
numberList[x] = 'x'
while 'x' in numberList:
numberList.remove('x')
return numberList
# This function checks if a list is sorted and returns true or false.
def sortChecker(numberList):
for x, item in enumerate(numberList):
try:
if item > numberList[x + 1]:
return False
except IndexError:
return True
# This function adds up the list and returns the total.
def sumOfList(numberList):
return sum(numberList)
# This function reverses the list given.
def reverseList(anyList):
anyList.reverse()
return anyList
# This function combines two sorted lists and creates a single sorted list.
def comboList(numberList, number2List):
x = numberList
x += number2List
numberList.sort()
return numberList
# This function runs all functions.
def ultimateFunction():
print("This function will condense [1, 1, 2, 3, 3]:")
print(condenseList([1, 1, 2, 3, 3]))
print()
print("This function will check and see if [5, 7, 1, 2, 4] is sorted:")
print(sortChecker([5, 7, 1, 2, 4]))
print()
print("This function will add up the total of [25, 10, 30, 40, 20]:")
print(sumOfList([25, 10, 30, 40, 20]))
print()
print("This function will reverse [5, 7, 9, 'hello', 'world']:")
print(reverseList([5, 7, 9, 'hello', 'world']))
print()
print("This function will combine [2, 3, 10, 25] and [10, 29, 30, 80, 69, 420, 1337, 9001]:")
print(comboList([2, 3, 10, 25], [10, 29, 30, 80, 69, 420, 1337, 9001]))
# Run Everything.
ultimateFunction()
print("Goodbye!")
|
import cv2 as cv
import numpy as np
roi = cv.imread('pic1.jpg') #67페이지에 축가해야할 코드가 있음
binary = np.zeros((roi.shape[0],roi.shape[1],roi.shape[2]),dtype=np.uint8)
# Opencv에서 imread함수를 사용하면 흑백이미지여도, rgb 3채널로 입력된다.
for i in range(roi.shape[0]):
for j in range(roi.shape[1]):
if (roi.item(i,j,0) >= 127):
binary.itemset(i,j,0,255)
binary.itemset(i,j,1,255)
binary.itemset(i,j,2,255)
else:
binary.itemset(i,j,0,0)
binary.itemset(i,j,1,0)
binary.itemset(i,j,2,0)
cv.imshow('roi',roi)
cv.imshow('binary',binary)
cv.waitKey(0)
cv.destroyAllWindows()
|
with open('input.txt') as input_file:
expenses = [int(line) for line in input_file]
# x = 2020 - y
def find_year_numbers_multiplied(year):
for i in expenses:
key = year - i
for j in expenses:
if key == j:
return i * j
print(find_year_numbers_multiplied(2020))
|
def sum1(a,b):
try:
c = a+b
return c
except :
print "Error in sum1 function"
def divide(a,b):
try:
c = a/b
return c
except :
print "Error in divide function"
print divide(10,0)
print sum1(10,0)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.