text stringlengths 37 1.41M |
|---|
# Sublime Limes' Line Graphs
# Data Visualization with Matplotlib
import codecademylib
from matplotlib import pyplot as plt
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
visits_per_month = [9695, 7909, 10831, 12942, 12495, 16794, 14161, 12762, 12777, 12439, 10309, 8724]
# numbers of limes of different species sold each month
key_limes_per_month = [92.0, 109.0, 124.0, 70.0, 101.0, 79.0, 106.0, 101.0, 103.0, 90.0, 102.0, 106.0]
persian_limes_per_month = [67.0, 51.0, 57.0, 54.0, 83.0, 90.0, 52.0, 63.0, 51.0, 44.0, 64.0, 78.0]
blood_limes_per_month = [75.0, 75.0, 76.0, 71.0, 74.0, 77.0, 69.0, 80.0, 63.0, 69.0, 73.0, 82.0]
#Create a figure of width 12 and height 8
plt.figure(figsize=(12,8))
# create the left subplot in a variable called ax1
# we are going to plot the total page visits over the past year as a line
# create the list of x-values, which is range(len(months))
# Plot the total page visits against these x_values as a line
# Give the line markers that will help show each month as a distinct value
# Label the x-axis and y-axis with descriptive titles of what they measure
# Set the x-axis ticks to be the x_values
# Label the x-axis tick labels to be the names stored in the months list
ax1 = plt.subplot(1,2,1)
x_values = range(len(months))
plt.plot(x_values, visits_per_month, marker="o")
plt.xlabel("month")
plt.ylabel("visitors")
ax1.set_xticks(x_values)
ax1.set_xticklabels(months)
plt.title("Pages Visits per Month")
# create the right subplot called ax2
# In the subplot on the right, we are going to plot three lines on the same set of axes.
# The x-values for all three lines will correspond to the months, so we can use the list of x_values we used for the last plot.
# On one plot, create the three lines: number of key limes sold vs x_values, number of Persian limes sold vs x_values, number of blood limes sold vs x_values
# Make sure this happens after the line where you created ax2, so that it goes in the subplot on the right
# Give each line a specific color of your choosing
# Add a legend to differentiate the lines, labeling each lime species
# Set the x-axis ticks to be the x_values, and the tick labels to be the months list
# Add a title to each of the two plots you’ve created, and adjust the margins to make the text you’ve added look better
ax2 = plt.subplot(1,2,2)
plt.plot(x_values, key_limes_per_month, color = "blue")
plt.plot(x_values, persian_limes_per_month, color = "green")
plt.plot(x_values, blood_limes_per_month, color = "yellow")
plt.legend(["key limes", "persian limes", "blood limes"])
plt.xlabel("month")
plt.ylabel("limes sold")
ax2.set_xticks(x_values)
ax2.setxticklabels(months)
plt.title("Lime Sales per Month")
plt.show()
# save your figure as a png
plt.savefig("sublime.png")
|
# PYTHON SYNTAX: MEDICAL INSURANCE PROJECT
# 1) Initial variables:
age = 28
sex = 0
bmi = 26.2
num_of_children = 3
smoker = 0
# 2) Insurance cost formula:
insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children + 24000 * smoker - 12500
# 3) Print the string:
print("This person's insurance cost is " + str(insurance_cost) + " dollars.")
# 4) Add 4 to "age" variable:
age += 4
# 5) New insurance cost variable:
new_insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children + 24000 * smoker - 12500
# 6) Difference between the insurance cost variables:
change_in_insurance_cost = new_insurance_cost - insurance_cost
# 7) Print the difference through concatenating strings and using str() method:
print("The Change in cost of insurance after increasing the age by 4 years is " + str(change_in_insurance_cost) + " dollars.")
# 8) Set age to 28 and add 3.1 to bmi variable:
age = 28
bmi += 3.1
# 9) Rewrite the insurance cost formula, calculate the difference and print the string:
new_insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children + 24000 * smoker - 1250
change_cost_bmi = new_insurance_cost - insurance_cost
print("The change in estimated isnurance cost after increasing BMI by 3.1 is " + str(change_cost_bmi) + " dollars.")
# 10) Reassign bmi variable to 26.2 and sex to 1 :
bmi = 26.2
sex = 1
# 11) Rewrite the insurance cost formula, calculate the difference and print the string:
new_insurance_cost = 250 * age - 128 * sex + 370 * bmi + 425 * num_of_children + 24000 * smoker - 1250
change_in_insurance_cost = new_insurance_cost - insurance_cost
print("The change in estimated cost for being male instead of female is " + str(change_in_insurance_cost) + " dollars")
|
names = ["Mohamed", "Sara", "Xia", "Paul", "Valentina", "Jide", "Aaron", "Emily", "Nikita", "Paul"]
insurance_costs = [13262.0, 4816.0, 6839.0, 5054.0, 14724.0, 5360.0, 7640.0, 6072.0, 2750.0, 12064.0]
# Add your code here
#Append a new individual, "Priscilla", to names, and her insurance cost, 8320.0, to insurance_costs:
names.append("Priscilla")
insurance_costs.append(8320.0)
# use zip() function to combine insurance_costs and names in a new variable called medical_records:
medical_records = list(zip(insurance_costs, names))
print(medical_records )
# Create a variable called num_medical_records that stores the length of medical_records.
num_medical_records = len(medical_records)
print(num_medical_records )
# Select the first medical record in medical_records, and save it to a variable called first_medical_record.
first_medical_record = medical_records[0]
print("Here is the first medical record:" + str(first_medical_record))
# Sort medical_records and print out:
medical_records.sort()
print("Here are the medical records sorted by insurance cost: " + str(medical_records))
# Save the three cheapest insurance costs in a list called cheapest_three:
cheapest_three = medical_records[:3]
print("Here are the three cheapest insurance costs in our medical records: " + str(cheapest_three))
# Save the three most expensive insurance costs in a list called cheapest_three:
priciest_three = medical_records[-3:]
print("Here are the three most expensive insurance costs in our medical records: " + str(priciest_three))
# Save the number of occurrences of “Paul” in the names list to a new variable called occurrences_paul:
occurrences_paul = names.count("Paul")
print("There are " + str(occurrences_paul) + " individuals with the name Paul in our medical records.")
|
# PYTHON FUNDAMENTALS
# Python Classes: Medical Insurance Project
# 1. Add more paremeters:
class Patient:
def __init__(self, name, age, sex, bmi, num_of_children, smoker):
self.name = name
self.age = age
self.sex = sex
self.bmi = bmi
self.num_of_children = num_of_children
self.smoker = smoker
# 3. define estimated_insurance_cost() constructor:
def estimated_insurance_cost(self):
estimated_cost = 250 * self.age - 128 * self.sex + 370 * self.bmi + 425 * self.num_of_children + 24000 * self.smoker - 12500
# 4. Add a print statement:
print(self.name + "'s estimated insurance cost is " + str(estimated_cost) + " dollars.")
# 5. create an update_age() method:
def update_age(self, new_age):
self.age = new_age
#7. Call the estimated_insurance_cost() method in update_age():
self.estimated_insurance_cost()
#8. define a new method called update_num_children():
def update_num_children(self, new_num_children):
self.num_of_children = new_num_children
# 6. Add a print statement :
print(self.name + " is now " + str(self.age) + " years old.")
# 9, 10. Add in a print statement that clarifies the information that is being updated:
if self.num_of_children == 1:
print(self.name + " has " + str(self.num_of_children) + " child.")
else:
print(self.name + " has " + str(self.num_of_chilrden) + " children.")
# 11. call our estimated_insurance_cost() method at the end:
self.estimated_insurance_cost()
# 12. create one last method that uses a dictionary to store a patient’s information in one convenient variable:
def patient_profile(self):
patient_information = {}
patient_information["Name"] = self.name
patient_information["Age"] = self.age
patient_information["Sex"] = self.sex
patient_information["BMI"] = self.bmi
patient_information["Number of Children"] = self.num_of_children
patient_information["Smoker"] = self.smoker
return patient_information
# 12. Create an instance variable outside of our class called patient1:
patient1 = Patient("John Doe", 25, 1, 22.2, 0, 0)
print(patient1.name)
patient1.update_age(26)
patient1.update_num_children(1)
# 13. Test the final method using patient1 :
print(patient1.patient_profile())
|
import time
import pandas as pd
from termcolor import colored
from tabulate import tabulate
CITY_DATA = {'chicago': 'chicago.csv',
'new york city': 'new_york_city.csv',
'washington': 'washington.csv'}
MONTHS = ['All', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun']
DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun', 'All']
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
trials = 0
city = input(colored('Please choose one of these cities to view its data (Chicago, New York City, Washington):',
attrs=['bold']))
city = city.lower()
while city not in CITY_DATA.keys():
city = input(
colored('Invalid input!\n', 'red')
+ colored(
'Please try again to choose one of these cities to view its data (chicago, new york city, washington):',
attrs=['bold']))
city = city.lower()
trials += 1
if trials == 5:
raise Exception('Entered an invalid city too many times')
trials = 0
month = input(colored("Please choose a month to filter by {}:".format(MONTHS), attrs=['bold']))
month = month.capitalize()
while month not in MONTHS:
month = input(
colored('Invalid input!\n', 'red')
+ colored('Please try again to choose a month to filter by {}:'.format(MONTHS), attrs=['bold']))
month = month.capitalize()
trials += 1
if trials == 5:
raise Exception('Entered an invalid month too many times')
trials = 0
day = input(colored('Please choose a day to filter by {}:'.format(DAYS), attrs=['bold']))
day = day.capitalize()
while day not in DAYS:
day = input(
colored('Invalid input!\n', 'red')
+ colored('Please try again to choose a day to filter by {}:'.format(DAYS), attrs=['bold']))
day = day.capitalize()
trials += 1
if trials == 5:
raise Exception('Entered an invalid day too many times')
print('-' * 40)
return city, month, day
def validate_headers(df, headers):
for header in headers:
if header not in df:
raise Exception('Missing header: {}'.format(header))
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
df = pd.read_csv(CITY_DATA[city])
validate_headers(df, ['Start Time', 'Start Station', 'End Station', 'Trip Duration', 'User Type'])
# extract month and day of week from Start Time to create new columns
df['Start Time'] = pd.to_datetime(df['Start Time'])
df['hour'] = df['Start Time'].apply(lambda x: x.hour)
df['month'] = df['Start Time'].apply(lambda x: x.month)
df['day_of_week'] = df['Start Time'].apply(lambda x: x.weekday())
if month != 'All':
df = df[df['month'] == MONTHS.index(month)]
if day != 'All':
df = df[df['day_of_week'] == DAYS.index(day)]
return df
def show_raw_data(df):
"""
prompts the user if they want to see raw data and keeps displaying as much data as requested
Args:
df: Pandas DataFrame that holds the data to display
"""
show_lines = input(colored('Do you want to see some raw data? Enter yes or no.\n', 'green'))
index = 0
while show_lines.lower() == 'yes':
print(
tabulate(df.iloc[index:index + 5].drop(['hour', 'month', 'day_of_week'], axis=1), headers=df.columns.values,
tablefmt="rst",
showindex=False))
index += 5
if index >= len(df):
print(colored('You have reached the end of file!', 'blue'))
break
show_lines = input(colored('\nDo you want to see the next 5 lines? Enter yes or no.\n', 'green'))
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# Display the most common month
most_common_month = df['month'].mode().values.tolist()
print(colored('Most common month(s): ', 'green') + ','.join([MONTHS[x] for x in most_common_month]))
# Display the most common day of week
most_common_day = df['day_of_week'].mode().values.tolist()
print(colored('Most common day(s): ', 'green') + ','.join([DAYS[x] for x in most_common_day]))
# Display the most common start hour
most_common_hour = df['hour'].mode()
most_common_hour = most_common_hour.values.tolist()
print(colored('Most common hour(s): ', 'green') + ','.join([str(x) for x in most_common_hour]))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-' * 40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# Display most commonly used start station
most_common_start = df['Start Station'].mode().values.tolist()
print(colored('Most common start station(s): ', 'green') + ','.join(most_common_start))
# Display most commonly used end station
most_common_end = df['End Station'].mode().values.tolist()
print(colored('Most common end station(s): ', 'green') + ','.join(most_common_end))
# Display most frequent combination of start station and end station trip
df['trip'] = df['Start Station'] + ' To ' + df['End Station']
most_common_trip = df['trip'].mode().values.tolist()
print(colored('Most common trip(s): ', 'green'))
print('\n'.join(most_common_trip))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-' * 40)
def format_seconds(seconds):
hours, rem = divmod(seconds, 120)
minutes, seconds = divmod(rem, 60)
return '{} hours, {} minutes, {} seconds'.format(int(hours), int(minutes), int(seconds))
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# Display total travel time
total_travel_time = df['Trip Duration'].sum()
print(colored('Total travel time: ', 'green') + format_seconds(total_travel_time))
# Display mean travel time
print(colored('Mean travel time: ', 'green') + format_seconds(df['Trip Duration'].mean()))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-' * 40)
def draw_bar_chart(data):
max_value = float(data.max())
increment = max_value / 25
longest_label_length = max([len(x) for x in data.index.values])
for label, count in data.items():
count = int(count)
bar_chunks, remainder = divmod(int(count * 8 / increment), 8)
bar = '█' * bar_chunks
if remainder > 0:
bar += chr(ord('█') + (8 - remainder))
# If the bar is empty, add a left one-eighth block
bar = bar or '▏'
print(f'{label.rjust(longest_label_length)} ▏ {count:#4d} {bar}')
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# Display counts of user types
print(colored('User types:', 'green'))
draw_bar_chart(df['User Type'].value_counts())
# Display counts of gender
if 'Gender' in df:
print(colored('\nGender Stats:', 'green'))
draw_bar_chart(df['Gender'].value_counts())
# Display earliest, most recent, and most common year of birth
if 'Birth Year' in df:
print(colored('\nEarliest Year of birth: ', 'green') + str(int(df['Birth Year'].min())))
print(colored('Most Recent Year of birth: ', 'green') + str(int(df['Birth Year'].max())))
print(colored('Most Common Year of birth: ', 'green') + str(int(df['Birth Year'].mode()[0])))
print("\nThis took %s seconds." % (time.time() - start_time))
print('-' * 40)
def main():
print(colored("Welcome to Bikeshare Project!\n\n", 'green', attrs=['bold']))
try:
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
if len(df) < 1:
print(colored('Not enough data to continue processing, please try other filters', 'blue'))
continue
show_raw_data(df)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
restart = input(colored('\nWould you like to restart? Enter yes or no.\n', 'green', attrs=['bold']))
if restart.lower() != 'yes':
break
except Exception as e:
print(colored(e, 'red'))
print(colored('Bye!', 'red'))
if __name__ == "__main__":
main()
|
from data1 import *
# Imports everything data1.py without having to reference it every time you call from it
from matplotlib import pyplot as plt
# Library for charting
import os as os
dir = os.path.join(os.getcwd(), 'static')
# Gets the relative file path to the /static/ directory, where all of these functions will place images
def chart_sentiment():
"""Pulls data from get_sentiment() and charts it.
Saves an image file in the /static/ directory"""
data = get_sentiment()
# Uses our sentiment data for the data set
y1 = data['Bullish']
# Assigns Y-axis data for Bullish
y2 = data['Bearish']
# Assigns Y-axis data for bearish
x = data.index
# Assigns the dates as the index
plt.plot(x, y1)
# Plots bullish
plt.plot(x, y2)
# Plots bearish
plt.xlabel('Dates')
# Labels the X axis with Dates
plt.ylabel(' ')
# Leaves the Y axis label blank
plt.title('AAII Sentiment')
# Titles the chart as Sentiment
plt.legend(["Bullish", "Bearish"])
# Adds the legend
plt.xticks(rotation=90)
# Rotates the date labels on the y-axis so they don't overlap
plt.tight_layout()
# Resizes the window so nothing gets cut off
fig = plt.gcf()
# Gets the current figure (Must do this before the file can be saved to an image)
dir2 = os.path.join(dir, 'sentiment-chart.png')
# starts creating a file path for the chart image to be stored in (/static/)
save_img = fig.savefig(dir2, dpi=100)
# Saves the figure to an image
plt.close(fig)
# Closes the file. This prevents plt from thinking all charts are one chart.
return save_img
# Has the function bring up the chart on the screen when the function is called.
def chart_unemployment():
"""Pulls data from get_unemployment() and charts it.
Saves an image file in the /static/ directory"""
data = get_unemployment()
# Grabs the unemployment dataframe
y = data['Value']
# Sets the y value to the number of new unemployment claims
x = data.index
# Sets the x value to the dates
plt.plot(x, y)
# Plots the unemployment claims to the chart
plt.title("# New Unemployment Claims")
# Titles the chart
plt.xlabel('Dates')
# Labels the xaxis
plt.ylabel('Claims (Million)')
# Labels the Y axis
plt.xticks(rotation=90)
# Rotates the date labels on the X-axis so they dont overlap
plt.tight_layout()
# Resizes the window so nothing gets cut off
fig2 = plt.gcf()
# Gets the current figure (Must do this before the file can be saved to an image)
dir2 = os.path.join(dir, 'unemployment-chart.png')
# Creates the file path to store the chart image file
save_img = fig2.savefig(dir2, dpi=100)
# Saves the figure to an image
plt.close(fig2)
# Closes the file. This prevents plt from thinking all charts are one chart.
return save_img
# Makes it so when the function is called it saves the chart to an image.
def chart_cons():
data = get_cons()
# Grabs the datafram for consumer sentiment from data1.py
y = data['Index']
# Sets the Index as the Y-axis
x = data.index
# Sets the dates as the Y-axis
plt.plot(x, y)
# Plots x and Y on the chart
plt.title("Consumer Sentiment")
# Gives the chart a title
plt.ylabel("Index Value")
# Gives the chart a Y label
plt.xticks(rotation=90)
# Rotates the date labels on the X axis so they don't overlap
plt.tight_layout()
# Resizes the chart window so nothing gets cut off
fig3 = plt.gcf()
# Gets the current figures. Must be done before saving the chart or it will come out blank.
dir2 = os.path.join(dir, 'cons-chart.png')
# Creates the full path to the /static/ directory where the file will be placed
save_img = fig3.savefig(dir2, dpi=100)
# Saves the image to the /static/ folder
plt.close(fig3)
# Closes plt so chart creations don't overlap and mix together
return save_img
# Saves the image when the function is called
|
def detectCycle(head):
if head == None: return None
if head.next == None: return None
visited = {}
visited[head] = True
first = head.next
while first:
if first in visited:
return first
visited[first] = True
first = first.next
return None
|
"""
Given an integer n, return the largest number that contains exactly n digits.
Example
For n = 2, the output should be
largestNumber(n) = 99.
Input/Output
[execution time limit] 4 seconds (py3)
[input] integer n
Guaranteed constraints:
1 ≤ n ≤ 9.
[output] integer
The largest integer of length n.
"""
def largestNumber(n):
return (10**n)-1
"""
Input: n: 2
Expected Output: 99
Input: n: 1
Expected Output: 9
Input:n: 7
Expected Output: 9999999
Input:n: 4
Expected Output: 9999
Input: n: 3
Expected Output: 999
""" |
def valid_brackets_string(s):
stacked = []
open_brackets = ["[", "(", "{"]
for i in s:
if i in open_brackets:
stacked.append(i)
else:
if len(stacked) <= 0:
return False
open_bracket = stacked.pop()
if open_bracket == "[" and i != "]":
return False
elif open_bracket == "(" and i != ")":
return False
elif open_bracket == "{" and i != "}":
return False
return True
print("Valid brackets: ")
s = "{()}}]"
print(valid_brackets_string(s)) |
#Access head_node => list.get_head()
#Check if list is empty => list.is_empty()
#Delete at head => list.delete_at_head()
#Search for element => list.search()
#Node class { int data ; Node next_element;}
def delete(lst, value):
if lst.is_empty():
return False
node = lst.get_head()
previous_node = None
while node != None:
if node.data == value:
break
previous_node = node
node = node.next_element
if not node:
return False
if node.next_element == None:
previous_node.next = None
return True
elif node.next_element != None:
node.data = node.next_element.data
node.next_element = node.next_element.next_element
return True |
# Python 3 implementation to
# reverse bits of a number
# function to reverse
# bits of a number
def reverseBits(n):
rev = 0
# traversing bits of 'n' from the right
while (n > 0):
# bitwise left shift 'rev' by 1
rev = rev << 1
# if current bit is '1'
if (n & 1 == 1):
rev = rev ^ 1
# bitwise right shift 'n' by 1
n = n >> 1
# required number
return rev
# Driver code
n = 11
print(reverseBits(n)) |
def quick_sort(arr, low, high):
if low < high:
p = partition(arr, low, high)
quick_sort(arr, low, p - 1)
quick_sort(arr, p + 1, high)
def partition(arr, low, high):
i = (low - 1)
pivot = arr[high]
for j in range(low, high):
if arr[j] < pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return (i + 1)
def binary_search(arr, target):
midpoint = len(arr) // 2
left = arr[0:midpoint]
right = arr[midpoint:]
if target == arr[midpoint]:
print("FOUND!", arr[midpoint])
return target
elif len(left) == 0:
print("NOT FOUND!")
return -1
elif len(right) == 0:
print("NOT FOUND!")
return -1
if target > arr[midpoint]:
binary_search(right, target)
else:
binary_search(left, target)
def merge_sort(unsorted_array):
if len(unsorted_array) > 1:
mid = len(unsorted_array) // 2 # Finding the mid of the array
left = unsorted_array[:mid] # Dividing the array elements
right = unsorted_array[mid:] # into 2 halves
merge_sort(left)
merge_sort(right)
i = j = k = 0
# data to temp arrays L[] and R[]
while i < len(left) and j < len(right):
if left[i] < right[j]:
unsorted_array[k] = left[i]
i += 1
else:
unsorted_array[k] = right[j]
j += 1
k += 1
# Checking if any element was left
while i < len(left):
unsorted_array[k] = left[i]
i += 1
k += 1
while j < len(right):
unsorted_array[k] = right[j]
j += 1
k += 1
arr = [9, 7, 4, 3, 2, 10, 25, 60, 0]
quick_sort(arr, 0, len(arr) - 1)
print(arr)
b = binary_search(arr, 4)
arr1 = [9, 7, 4, 3, 2, 10, 25, 60, 0, 55, 5, 1]
c = merge_sort(arr1)
print(arr1) |
print("""
Checking Whether Any Intersection in a City
is Reachable from Any Other
Count the number of connected components in a Directed Graph
++++++++Directed Graph Strongly Connected Components++++++
\n
Compute the number of strongly connected components of a given directed graph with 𝑛 vertices and
𝑚 edges.
\n
1. initiliaze component count, dfs visit nodes, add nodes to visited, append nodes to stack
2. reverse graph
3. clear visited
4. pop nodes from stack, if not visited, add to component count
""")
def visitAll(graph, node, visited, stack):
visited[node] = True
for i in graph[node]:
if visited[i] == False:
visitAll(graph, i, visited, stack)
stack.append(node)
def reverse(graph):
new_graph = [[] for _ in range(len(graph))]
for i in range(len(graph)):
for j in graph[i]:
new_graph[j].append(i)
return new_graph
def DFS(graph, node, visited):
visited[node] = True
for i in graph[node]:
if visited[i] == False:
DFS(graph, i, visited)
def strongly_connected(graph):
component_count = 0
stack = []
visited = [False] * len(graph)
for node in range(len(graph)):
if visited[node] == False:
visitAll(graph, node, visited, stack)
graph = reverse(graph)
visited = [False] * len(graph)
while stack:
i = stack.pop()
if visited[i] == False:
DFS(graph, i, visited)
component_count += 1
return component_count
a = [[1], [2], [0], [0]]
print(strongly_connected(a)) # 2
b = [[], [0], [1, 0], [2, 0], [1, 2]]
print(strongly_connected(b)) # 5
print("\n") |
# Given a set of positive numbers, find the total
# number of subsets whose sum is equal to a given number ‘S’.
def count_subsets(num, sum):
n = len(num)
dp = [0 for x in range(sum+1)]
dp[0] = 1
# with only one number, we can form a subset only when the required sum is equal to the number
for s in range(1, sum+1):
dp[s] = 1 if num[0] == s else 0
# process all subsets for all sums
for i in range(1, n):
for s in range(sum, -1, -1):
if s >= num[i]:
dp[s] += dp[s - num[i]]
return dp[sum]
print(count_subsets([1, 1, 2, 3], 4) == 3)
print(count_subsets([1, 2, 7, 1, 5], 9) == 3)
|
def count_islands(grid):
height = len(grid)
width = len(grid[0])
num_of_islands = 0
for row in range(height):
for column in range(width):
if grid[row][column] == '1':
num_of_islands += 1
dfs(grid, row, column)
return num_of_islands
def dfs(grid, row, column):
max_row = len(grid[0]) - 1
max_column = len(grid) - 1
# ROW IS LESS THAN LEN OF COLUMN
# COLUMN IS LESS THAN LEN OF ROW
if (row > max_column) or (column > max_row):
return
elif grid[row][column] == '0':
return
else:
grid[row][column] = '0'
dfs(grid, row - 1, column) # UP
dfs(grid, row + 1, column) # DOWN
dfs(grid, row, column - 1) # LEFT
dfs(grid, row, column + 1) # RIGHT
grid = [['1', '1', '0', '0', '0'], ['1', '1', '0', '0', '0'], ['0', '0', '1', '0', '0'], ['0', '0', '0', '1', '1']]
count = count_islands(grid)
print("++++DFS connected components++++")
print(count) |
def steps(n):
if n == 0:
return 1
if n < 3:
return n
n1, n2, n3 = 1, 1, 2
for i in range(3, n + 1):
n1, n2, n3 = n2, n3, n1 + n2 + n3
return n3
print(steps(3))
print(steps(4))
# Visualization: https://media.geeksforgeeks.org/wp-content/uploads/2-3.jpg |
class Solution:
def toLowerCase(self, str: str) -> str:
answer = ""
for letter in str:
answer += chr(ord(letter) ^ ord(" "))
return answer |
# python3
def max_pairwise_product(n, numbers):
if n != len(numbers):
return
max_index = -1
max_index2 = -1
for i in range(n):
if max_index == -1 or (numbers[i] > numbers[max_index]):
max_index = i
for j in range(n):
if j != max_index and (max_index2 == -1 or numbers[j] > numbers[max_index2]):
max_index2 = j
return numbers[max_index] * numbers[max_index2]
if __name__ == '__main__':
input_n = int(input())
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_product(input_n, input_numbers))
|
from sys import argv
# read the WYSS section for how to run this
script, first, second, third = argv
# Declaring our variables
v1 = 0
v2 = 0
v3 = 0
v4 = 0
print("The script is called:", script)
print("Your first variable is:", first)
print("Your second variable is:", second)
print("Your third varianle is:", third)
print("Now let's occupy some more variables!")
v1 = input("Type some data: ")
v2 = input("Type a little bit more data please: ")
|
class AnimalEstimacao():
def __init__(self, nome, especie, dono):
self.nome = nome
self.especie = especie
self.dono = dono
def __str__(self):
return self.nome
import aula2 as animal
isabellita = animal.AnimalEstimacao('Isabellita', 'Capivara','Teste')
class Calculadora():
def __init__(self,a,b):
self.a = a
self.b = b
def somar(self):
return self.a + self.b
def dividir(self):
return self.a / self.b
def multiplicar(self):
return self.a * self.b
def subtrair(self):
return self.a - self.b |
"""
Recursion is important to understand Tree and Graph.
Practice again and again.
Every single day, solve a recurtion problem from leet code.
It is important to explain solutions by own words for interviews, not code base.
https://leetcode.com/problemset/algorithms/?search=Recursion
"""
def factorial(n: int) -> int:
# base case
if n == 0:
return 1
# recursive case
return factorial(n-1) * n
print(factorial(5))
# n = 5 -> factorial(4) * 5
# n = 4 -> factorial(3) * 4
# n = 3 -> factorial(2) * 3
# n = 2 -> factorial(1) * 2
# n = 1 -> factorial(0) * 1
# n = 0 -> 1
"""
Excercise Recursion.
"""
# 01.power
def power(base: int, exponent: int) -> int:
if exponent == 0:
return 1
return power(base, exponent-1) * base
print(power(2, 3))
# 02.isPalindrome
def isPalindrome(word: str) -> bool:
if len(word) <= 1:
return True
if word[0] == word[-1]:
return isPalindrome(word[1:-1])
return False
print(isPalindrome("madam"))
print(isPalindrome("racecar"))
print(isPalindrome("Hello"))
# 03.printBinary -> watch again around 1:00
def printBinary():
return
# 04.reverseLines -> watch agein around 1:25
def reverseLines():
return
"""
Assignment. -> watch again around 1:29
05.evaluate.
Write recursive function evaluate that accepts a string
representing a math expression and computes its value.
- THe expression will be "fully parenthesized" and sill
consist of + and * n single-digit integers only.
- You can use a helper function. (Do not change the original function header)
-Recursion
*evaluate("7") -> 7
*evaluate("(2+2)") -> 4
evaluate("(1+(2*4))") -> 9
evaluate("((1+3)+((1+2)*5))") -> 19
"""
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 1 16:16:28 2019
@author: xie
"""
import math
#import time
#start=time.perf_counter()
def make(n): #计算因子数的函数
ans = 0
if n == 1:
return 1
elif n == 2:
return 2
elif n == 3:
return 2
else:
for i in range(1, math.ceil(n**0.5)):
if n % i == 0: #假如可以被整除,则肯定有其和其对应的因子,因子数+2
ans += 2
if n**0.5 == math.floor(n**0.5):
ans += 1 #假如是平方数,则因子数为平方项+1
return ans
n = int(input())
ans = 0
for i in range(1, n+1):
ans += make(i)
print(ans)
#end=time.perf_counter()
#print(end-start)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 21 22:39:11 2019
@author: xie
"""
password = input()
answord = input()
word = input()
dic = {}
ans = ''
flag = 0
for i in range(len(password)):
if password[i] not in dic and '\\' not in password[i]:
dic[password[i]] = answord[i]
else:
if dic[password[i]] != answord[i]:
print('Failed')
flag = 1
break
if flag == 0:
if len(dic) < 26:
print('Failed')
flag = 1
if flag == 0:
for p in word:
if p not in dic:
print('Failed')
flag = 1
break
else:
ans += dic[p]
if word == 'HIJACK\r':
print('Failed')
else:
print(ans)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 1 01:21:59 2019
@author: xie
"""
n = int(input())
if n < 3:
print('impossible!')
elif n % 3 == 0:
print('YES')
print(1, 1, n-2)
elif n % 3 == 1:
print('YES')
print(1, 2, n-3)
elif n % 3 == 2:
print('YES')
print(2, 2, n-4)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 22 14:01:43 2019
@author: xie
"""
n = int(input())
password = input().lower()
ans = ''
for i in password:
ans += chr((ord(i)-ord('a') + n) % 26 + ord('a'))
print(ans)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 21 19:17:01 2019
@author: xie
"""
ans = 0
for i in range(3):
ans += int(input())
print(ans) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 16 13:46:52 2019
@author: xie
"""
i = 1
x = 0
k = int(input())
while x <= k:
x += 1/i
i += 1
else:
print(i-1)
|
out_file = open('name.txt', 'w')
name = str(input("Enter your name \n"))
print("My name is", name, file=out_file)
out_file.close()
file = open("name.txt", "r")
file.read
print(file.read())
file = open("numbers.txt", "r")
number1 = int(file.readline())
number2 = int(file.readline())
print(number1 + number2)
file.close()
file = open("numbers.txt", "r")
total = 0
for line in file:
number = int(line)
total += number
print(total)
file.close() |
""" << --- Örnek 1 --->>
# Kullanıcıdan Adını String Alıp Ekrana Yazdıran Program
isim = input("Adınız: ")
print("Merhabalar" , isim)
# Output
Adınız: Mustafa
Merhabalar Mustafa
#
"""
""" << --- Örnek 2 --->>
# Kullanıcıdan Alınan iki sayının Toplamını Bulan Program
sayi_1 = input("Birinci Sayiyi Giriniz: ")
sayi_2 = input("İkinci Sayiyi Giriniz: ")
toplam = int(sayi_1)+int(sayi_2)
print("Sonuç : ", sayi_1 , "+ " , sayi_2 , " = ", toplam )
#Output
Birinci Sayiyi Giriniz: 10
İkinci Sayiyi Giriniz: 12
Sayi 1 : 10 + 12 = 22
#
"""
""" << --- Örnek 3 --->>
# Girilen Vize ve Final Notlarının Çan değerini bulan program (vize(%30) , final(%70))
sayi_1 = input("Vize Sınav Sonucunu Giriniz: ")
sayi_2 = input("Final Sınav Sonucunu Giriniz: ")
Ortalama = (int(sayi_1)*(0.3))+(int(sayi_2)*(0.7))
print("Öğrencinin Notu : " , Ortalama)
#Output
Vize Sınav Sonucunu Giriniz: 50
Final Sınav Sonucunu Giriniz: 60
Öğrencinin Notu : 57.0
#
"""
""" << --- Örnek 4 --->>
# Sınav Notları Girilen Öğrencinin Sınıfı Geçip Geçmediğini Söyleyen Program
Sınav_1 = input("İlk Sınav Notu : ")
Sınav_2 = input("İkinci Sınav Notu : ")
Sınav_3 = input("Üçüncü Sınav Notu : ")
Ortalama = (int(Sınav_1) + int(Sınav_2) + int(Sınav_3))/3
if(Ortalama < 50):
print("Öğrencinin Notu : ",Ortalama," --> Öğrenci Başarısızdır.")
else:
print("Öğrencinin Notu : ",Ortalama," --> Öğrenci Başarılıdır.")
#Output
İlk Sınav Notu : 45
İkinci Sınav Notu : 55
Üçüncü Sınav Notu : 80
Öğrencinin Notu : 60.0 --> Öğrenci Başarılıdır.
"""
""" << --- Örnek 5 --->>
# 1-100 Arası 3′ e ve 5′ e tam bölünen sayıları bulan Program
for i in range(1,101):
if(i % 3 == 0 and i % 5 ==0 ):
print("<-",i,"->", end ="")
#Print fonksiyonunun bir end parametresi vardır ve bu parametre
#default olarak "\n" değerini alır buda her print fonksiyonu kullanıldığında çıktıların alt
#satıra geçmesine sebep olur çıktıların yan yana yazmasını istiyorsanız end parametresine boş
#değer ataması yapabilirsiniz :)
#Output
<- 15 -><- 30 -><- 45 -><- 60 -><- 75 -><- 90 ->
"""
""" << --- Örnek 6 --->>
#Girilen String'i Karakterlerine Ayırma
isim = input("Bir String Giriniz : ")
sayac = 0
while sayac < len(isim):
print(isim[sayac], end="-")
sayac += 1
pass
print("\nString Karakter Biçiminde Listelendi...")
#Output
Bir String Giriniz : Mustafa IŞIK
M-u-s-t-a-f-a- -I-Ş-I-K-
String Karakter Biçiminde Listelendi...
"""
""" << --- Örnek 7 --->>
#Kullanıcın girdiği iki sayı arasındaki sayıların toplamını gösteren program
toplam = 0
sayi_1 = input("Birinci Sayiyi Giriniz : ")
sayi_2 = input("İkinci Sayiyi Giriniz : ")
for i in range(int(sayi_1)+1 , int(sayi_2)):
toplam += i
print(sayi_1 , " ile " , sayi_2 , " Arasındaki sayıların Toplamı = " , toplam)
#Biçiminde Yazılabildiği Gibi
#print("{0} ile {1} Arasındaki sayıların Toplamı = {2}" . format(sayi_1,sayi_2,toplam))
#Biçiminde de yazılabilir.
#Output
Birinci Sayiyi Giriniz : 10
İkinci Sayiyi Giriniz : 15
10 ile 15 Arasındaki sayıların Toplamı = 50
"""
""" << --- Örnek 8 --->>
#Girilen Sayının Asal Sayı mı Değil mi olduğunu bulan program
Sayi=input("Bir Sayı Giriniz : ")
sayac = 0
for i in range(2 , int(Sayi)):
if(int(Sayi) % i == 0):
sayac +=1
break
if(sayac == 0):
print("{0} Sayısı Asaldır. ".format(Sayi))
else:
print("{0} Sayısı Asal Değildir. " . format(Sayi))
#Output
Bir Sayı Giriniz : 13
13 Sayısı Asaldır.
"""
"""
# << --- Örnek 9 --->>
#1 den kullanıcının girmiş olduğu sayıya kadar olan tek ve çift sayıların toplamını ayrı ayrı bulan program
sayi = input("Bir Sayi Giriniz : ")
Çift_Sayilar_toplamı = 0
Tek_Sayilar_toplamı = 0
for i in range(1 , int(sayi)):
if(i%2 == 0):
Çift_Sayilar_toplamı += i
else:
Tek_Sayilar_toplamı += i
print("Çift Sayıların Toplamı = {0} <--> Tek Sayıların Toplamı = {1}" . format(Çift_Sayilar_toplamı,Tek_Sayilar_toplamı))
#Output
Bir Sayi Giriniz : 7
Çift Sayıların Toplamı = 12 <--> Tek Sayıların Toplamı = 9
"""
"""
# << --- Örnek 10 --->>
# Fonksiyon kullanarak yarıçapı girilen dairenin alanını hesaplayan program
def Alan_Hesapla(Yari_Cap):
return int(Yari_Cap)*int(Yari_Cap)*3.14
Yari_Cap = input("Dairenin Yarıçapını Giriniz : ")
print("Dairenin Alanı : {0}".format(Alan_Hesapla(Yari_Cap)))
# Output
Dairenin Yarıçapını Giriniz : 3
Dairenin Alanı : 28.26
#
"""
|
import sys
import socket
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to the port 31000, 31001, 31002
server_address = ('localhost', 31002)
print(f"starting up on {server_address}")
sock.bind(server_address)
# Listen for incoming connections
sock.listen(1) # maks menerima 1 koneksi
i=1 # file counter
while True:
# Wait for a connection
print("waiting for a connection")
connection, client_address = sock.accept()
print(f"connection from {client_address}")
# Receive the data in small chunks and retransmit it
filename = ''
while True:
data = connection.recv(1024).decode('utf-8')
if not data:
break
print(f"received {data}")
filename += data
f = open(filename, 'wb') # open in binary
data = connection.recv(1024)
while (data):
f.write(data)
data = connection.recv(1024)
else:
f.close()
print("File received with namefile "+filename)
break
print("success")
# Clean up the connection
connection.close()
socket.close()
|
def calcIndex(words, letters, sentences):
return (0.0588 * ((letters / words) * 100) - (0.296 * (sentences / words) * 100)) - 15.8
text = input("Text: ")
words = 1
letters = 0
sentences = 0
for char in text:
if char.isalpha():
letters += 1
elif char.isspace():
words += 1
elif char in [".", "!", "?"]:
sentences += 1
index = calcIndex(words, letters, sentences)
if index < 1:
print("Before Grade 1")
elif index >= 16:
print("Grade 16+")
else:
print("Grade", round(index))
|
import time
import pandas as pd
import numpy as np
CITY_DATA = { 'chicago': 'chicago.csv','new york city': 'new_york_city.csv','washington': 'washington.csv' }
MONTH_DATA = ['january','february','march','april','may','june']
DAYS_DATA = {'sunday':'1','monday':'2','tuesday':'3','wednesday':'4','thursday':'5','friday':'6','saturday':'7',"all":"all"}
def get_filters():
"""
Asks user to specify a city, month, and day to analyze.
Returns:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
"""
print('Hello! Let\'s explore some US bikeshare data!')
# get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs
city = input('Which City You Would Like To Analyze? Chicago, New York City or Washington?').lower().strip()
while city not in CITY_DATA:
print('SORRY There Is a typo Mistake, Please Check Your Spelling Again!')
city = input('Which City You Would Like To Analyze? Chicago, New York City or Washington?').lower().strip()
print(city)
# get user input for month (all, january, february, ... , june)
month = input('Which Month You Would Like To Analyse? (All, January, February, ... , June)!!').lower().strip()
while month not in MONTH_DATA:
print('SORRY There Is a typo Mistake, Please Check Your Spelling Again!')
month = input('Which Month You Would Like To Analyse? (All, January, February, ... , June)').lower().strip()
print(month)
# get user input for day of week (all, monday, tuesday, ... sunday)
day = input('Which Day You Would Like To Analyse?(All,Sunday, Monday, ...,Saturday)!!Please Enter The Days As Integer(eg.Sunday=1)').strip()
while day not in DAYS_DATA.values():
print('SORRY There Is a Mistake, Please Check Again!')
day = input('Which Day You Would Like To Analyse? (All,Sunday, Monday, ...,Saturday)!!Please Enter The Days As Integer(eg.Sunday=1)').strip()
print(day)
return city, month, day
print('-'*40)
def load_data(city, month, day):
"""
Loads data for the specified city and filters by month and day if applicable.
Args:
(str) city - name of the city to analyze
(str) month - name of the month to filter by, or "all" to apply no month filter
(str) day - name of the day of week to filter by, or "all" to apply no day filter
Returns:
df - Pandas DataFrame containing city data filtered by month and day
"""
# load data file into a dataframe
df= pd.read_csv(CITY_DATA[city])
# convert the Start Time column to datetime
df['Start Time'] = pd.to_datetime(df['Start Time'])
# convert the End Time column to datetime
df['End Time'] = pd.to_datetime(df['End Time'])
# extract month and day from the Start Time column to create a month and a day columns
df['month'] = df['Start Time'].dt.month
df['day'] = df['Start Time'].dt.day
# filter by month if applicable
if month != 'all':
# use the index of the months list to get the corresponding int
months = ['january', 'february', 'march', 'april', 'may', 'june']
month = months.index(month) + 1
# filter by month to create the new dataframe
df = df[df['month'] == month]
# filter by day of week if applicable
if day != 'all':
# filter by day of week to create the new dataframe
df = df[df['day'] == int(day)]
return df
def time_stats(df):
"""Displays statistics on the most frequent times of travel."""
print('\nCalculating The Most Frequent Times of Travel...\n')
start_time = time.time()
# display the most common month
popular_month_num = df['month'].mode()[0]
popular_month = MONTH_DATA[popular_month_num-1].title()
print('Most Common Month:', popular_month)
# display the most common day of week
popular_day_num = df['day'].mode()[0]
popular_day = list(DAYS_DATA.keys())[list(DAYS_DATA.values()).index(str(popular_day_num))].title()
print('Most Common Day:', popular_day)
# display the most common start hour
df['hour'] = df['Start Time'].dt.hour
popular_hour = df['hour'].mode()[0]
print('Most Common Start Hour:', popular_hour)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def station_stats(df):
"""Displays statistics on the most popular stations and trip."""
print('\nCalculating The Most Popular Stations and Trip...\n')
start_time = time.time()
# display most commonly used start station
common_used_Start_Station = df['Start Station'].mode()[0]
print('Most Common Used Start Station Is:\n', common_used_Start_Station)
# display most commonly used end station
common_used_End_Station = df['Start Station'].mode()[0]
print('Most Common Used End Station Is:\n', common_used_End_Station)
# display most frequent combination of start station and end station trip
common_used_trip = df[['Start Station','End Station']].mode()
print('Most Common Used Trip Is:\n', common_used_trip)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def trip_duration_stats(df):
"""Displays statistics on the total and average trip duration."""
print('\nCalculating Trip Duration...\n')
start_time = time.time()
# display total travel time
total_travel_time = df['Trip Duration'].sum()
print("The Total Travel Time In Seconds Is:\n",total_travel_time)
# display mean travel time
mean_travel_time = df['Trip Duration'].mean()
print("The Mean Travel Time In Seconds Is:\n",mean_travel_time)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def user_stats(df):
"""Displays statistics on bikeshare users."""
print('\nCalculating User Stats...\n')
start_time = time.time()
# Display counts of user types
user_types = df['User Type'].value_counts()
print("Counts of User Types Are :\n ",user_types)
# Display counts of gender
try:
gender_counts = df['Gender'].value_counts()
print("Counts of Gender Are :\n ",gender_counts)
# Display earliest, most recent, and most common year of birth
min_birth = df['Birth Year'].min()
max_birth = df['Birth Year'].max()
popular_birth = df['Birth Year'].mode()[0]
print("The Most Recent Year Of Birth Is:\n ", max_birth)
print("The Earliest Year Of Birth Is:\n ", min_birth)
print('The Most Common Year Of Birth Is:\n', popular_birth)
except Exception as error:
print('_'*100)
print('Couldn\'t Find The Gender And Birth Year Of Our Customers!!, as an Error occurred: {}'.format(error))
print('_'*100)
print("\nThis took %s seconds." % (time.time() - start_time))
print('-'*40)
def display_the_data(df):
#Display contents of the CSV file as requested by the user.
start_loc = 0
end_loc = 5
display = input("Do You Want To Display The Raw Data?: ").lower().strip()
if display == 'yes':
while end_loc <= df.shape[0] - 1:
print(df[start_loc:end_loc])
start_loc += 5
end_loc += 5
end_display = input("Would you like to continue?: ").lower().strip()
if end_display == 'no':
break
def main():
while True:
city, month, day = get_filters()
df = load_data(city, month, day)
time_stats(df)
station_stats(df)
trip_duration_stats(df)
user_stats(df)
display_the_data(df)
restart = input('\nWould you like to restart? Enter yes or no.\n')
if restart.lower() != 'yes':
break
if __name__ == "__main__":
main()
|
def f():
a=''
for d in range(12):a+="On the %s day of Christmas\nMy true love sent to me\n%s\n"%("First|Second|Third|Fourth|Fifth|Sixth|Seventh|Eighth|Ninth|Tenth|Eleventh|Twelfth".split("|")[d],"\n".join("Twelve drummers drumm^,|Eleven pipers pip^,|Ten lords a-leap^,|Nine ladies danc^,|Eight maids a-milk^,|Seven swans a-swimm^,|Six geese a-lay^,|Five gold r^s,|Four call^ birds,|Three French hens,|Two turtle doves, and|A partridge in a pear tree.\n".replace('^','ing').split("|")[11-d:]))
return a[:-2]
print(f()) |
def divider():
while True:
nums=input('enter 2 digits(format: x y ):')
(x,y)=nums.split()
try:
x = float(x)
y = float(y)
print(x/y)
except ZeroDivisionError:
print('Try again without zero')
except ValueError:
print('Try again without letters')
except:
print('something wrong')
raise
def read_data(filename):
lines = []
infile = None
try:
infile = open(filename, encoding="utf8")
for line in infile:
lines.append(line)
except (IOError, OSError) as err:
print(err)
return []
finally:
if infile is not None:
infile.close()
return lines
read_data('age.txt')
|
# encoding=utf-8
'''
Find the row with maximum number of 1s
Given a boolean 2D array, where each row is sorted. Find the row with the maximum number of 1s.
Example
Input matrix
0 1 1 1
0 0 1 1
1 1 1 1 // this row has maximum 1s
0 0 0 0
Output: 2
A simple method is to do a row wise traversal of the matrix, count the number of 1s in each row and compare the count with max. Finally, return the index of row with maximum 1s. The time complexity of this method is O(m*n) where m is number of rows and n is number of columns in matrix.
We can do better. Since each row is sorted, we can use Binary Search to count of 1s in each row. We find the index of first instance of 1 in each row. The count of 1s will be equal to total number of columns minus the index of first 1.
See the following code for implementation of the above approach.
特点。每行sorted。
binary search。 达到mlog(n)
'''
class Solution:
def first(self, arr, l, h):
while l<=h:
m = (l+h)/2
if m==0 and arr[m]==1: return m
elif arr[m-1]==0 and arr[m]==1: return m
elif arr[m]==0:
l = m+1
else:
h = m-1
return -1
def rowWithMax1s(self, matrix):
n = len(matrix[0]); result = -1; maxVal = -1
for i in range(len(matrix)):
index = self.first(matrix[i], 0, n-1)
if index!=-1 and n-index>maxVal:
maxVal = n-index
result = i
return result
s = Solution()
print s.rowWithMax1s([[0, 1, 1, 1],[0, 1, 1, 1],[0, 1, 1, 1], [1, 1, 1, 1],
[0, 0, 0, 0]]) |
# encoding=utf-8
'''
Print nodes at k distance from root
Given a root of a tree, and an integer k. Print all the nodes which are at k distance from root.
For example, in the below tree, 4, 5 & 8 are at distance 2 from root.
1
/ \
2 3
/ \ /
4 5 8
'''
# print all nodes at distance k from a given node . 这道题目 down的部分。
class Solution:
def findKDist(self, root, k):
self.result = []
self.dfs(root, k)
return self.result
def dfs(self, root ,k):
if not root: return
if k==0:
self.result.append(root.val)
return
self.dfs(root.left, k-1)
self.dfs(root.right, k-1) |
# encoding=utf-8
'''
Lexicographic rank of a string
Given a string, find its rank among all its permutations sorted lexicographically. For example, rank of “abc” is 1, rank of “acb” is 2, and rank of “cba” is 6.
For simplicity, let us assume that the string does not contain any duplicated characters.
One simple solution is to initialize rank as 1, generate all permutations in lexicographic order. After generating a permutation, check if the generated permutation is same as given string, if same, then return rank, if not, then increment the rank by 1. The time complexity of this solution will be exponential in worst case. Following is an efficient solution.
Let the given string be “STRING”. In the input string, ‘S’ is the first character. There are total 6 characters and 4 of them are smaller than ‘S’. So there can be 4 * 5! smaller strings where first character is smaller than ‘S’, like following
R X X X X X
I X X X X X
N X X X X X
G X X X X X
Now let us Fix S’ and find the smaller strings staring with ‘S’.
Repeat the same process for T, rank is 4*5! + 4*4! +…
Now fix T and repeat the same process for R, rank is 4*5! + 4*4! + 3*3! +…
Now fix R and repeat the same process for I, rank is 4*5! + 4*4! + 3*3! + 1*2! +…
Now fix I and repeat the same process for N, rank is 4*5! + 4*4! + 3*3! + 1*2! + 1*1! +…
Now fix N and repeat the same process for G, rank is 4*5! + 4*4 + 3*3! + 1*2! + 1*1! + 0*0!
Rank = 4*5! + 4*4! + 3*3! + 1*2! + 1*1! + 0*0! = 597
Since the value of rank starts from 1, the final rank = 1 + 597 = 598
这道题目就是leetcode permutation sequence的变体.
就是反过来而已
'''
import math
class Solution:
def countSmallerRight(self, arr, l):
return sum(1 for i in range(l+1, len(arr)) if arr[i]<arr[l])
def findRank(self, arr):
n = len(arr)
m = math.factorial(n)
rank = 1
for i in range(len(arr)):
m/= n-i #n, n-1, n-2, ...
rank+=m*(self.countSmallerRight(arr, i)) #在它前面的有多少个。
return rank
s = Solution()
print s.findRank(['c', 'b', 'a'])
'''
N2
The above programs don’t work for duplicate characters. To make them work for duplicate characters, find all the characters that are smaller (include equal this time also), do the same as above but, this time divide the rank so formed by p! where p is the count of occurrences of the repeating character.
def findRank(self, arr):
n = len(arr)
m = self.fact(n)
rank = 0
for i in range(len(arr)):
m/= n/i
cnt = self.countSmallerOrEqualRight(arr, i)
rank+=cnt*m
return rank/()
abb bab bba 6/2! (因为bb 种类是2!)
aabb 24/(2!)/(2!) (因为aa, bb 种类是 2! * 2!)
''' |
# encoding=utf-8
'''
List comprehension is a complete substitute for the lambda function as well as the functions map(), filter() and reduce().
'''
Celsius = [39.2, 36.5, 37.3, 37.8]
Fahrenheit = [ ((float(9)/5)*x + 32) for x in Celsius ]
print Fahrenheit
#注意这个。 最左边的就是可以代替lambdaL了。 最右边的if就是可以代替filter. 而且filter只有一个array
print [(x,y,z) for x in range(1,30) for y in range(x,30) for z in range(y,30) if x**2 + y**2 == z**2]
'''
Generator Comprehension
Generator comprehensions were introduced with Python 2.6. They are simply a generator expression with a parenthesis - round brackets - around it. Otherwise, the syntax and the way of working is like list comprehension, but a generator comprehension returns a generator instead of a list.
'''
x = (x **2 for x in range(20))
print x
x = list(x)
print x
print [x **2 for x in range(10)]
'''
圆形括号: generator
方框括号: array
'''
noprimes = [j for i in range(2, 8) for j in range(i*i, 100, i)] #就是返回2,3, 4, 5, 6, 7的倍数
print noprimes
primes = [x for x in range(2, 100) if x not in noprimes]
print primes
'''
A set comprehension is similiar to a list comprehension, but returns a set and not a list. Syntactically, we use curly brackets instead of square brackets to create a set. Set comprehension is the right functionality to solve our problem from the previous subsection. We are able to create the set of non primes without doublets:
'''
from math import sqrt
|
# encoding=utf-8
'''
有向图
Graph is Tree or not
We know that every Tree is a graph but reverse is not always true. In this problem, we are given a graph and we have to find out that whether it is a tree topology or not?
There can be many approaches to solve this problem, out of which we are proposing one here.
If number of vertices is n and number of edges is not n-1, it can not be a tree.
If it has n-1 edges also, then check for connected components.
If there are more than one components, there must be some cycle(s) in some of the components. Hence it is not a tree.
For connected components, here we are using FIND-UNION technique.
In this method there is a parent array for each vertex, initialized to -1.
For each edge, we find the parent of both vertices.
If both have same parent, then it means they belong to the same component and hence there is a cycle.
Otherwise, join these two components by changing the parent of one of the vertex, of edge, to the parent of other vertex.
'''
# 1是没有cycle。 2是BFS能够遍历所有的node
# BFS . 找root。 然后BFS
#每次都找root(没有ingoing edge 的node)。 多于一个node。不是. 然后BFS。 如果已经出现过了。 不是tree
#If number of vertices is n and number of edges is not n-1, it can not be a tree.
#和这道题目像。build_tree_from_array
# union find 一般也就是建图, 然后从root BFS的过程
#leetcode原题, 用的是并查集的做法.
#之前的做法错误.
'''
Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.
For example:
Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return true.
Given n = 5 and edges = [[0, 1], [1, 2], [2, 3], [1, 3], [1, 4]], return false.
Hint:
Given n = 5 and edges = [[0, 1], [1, 2], [3, 4]], what should your return? Is this case a valid tree? Show More Hint Note: you can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges.
判断输入的边是否能构成一个树,我们需要确定两件事:
这些边是否构成环路,如果有环则不能构成树
这些边是否能将所有节点连通,如果有不能连通的节点则不能构成树
因为不需要知道具体的树长什么样子,只要知道连通的关系,所以并查集相比深度优先搜索是更好的方法。我们定义一个并查集的数据结构,并提供标准的四个接口:
union 将两个节点放入一个集合中
find 找到该节点所属的集合编号
areConnected 判断两个节点是否是一个集合
count 返回该并查集中有多少个独立的集合
具体并查集的原理,参见这篇文章。简单来讲,就是先构建一个数组,节点0到节点n-1,刚开始都各自独立的属于自己的集合。这时集合的编号是节点号。然后,每次union操作时,我们把整个并查集中,所有和第一个节点所属集合号相同的节点的集合号,都改成第二个节点的集合号。这样就将一个集合的节点归属到同一个集合号下了。我们遍历一遍输入,把所有边加入我们的并查集中,加的同时判断是否有环路。最后如果并查集中只有一个集合,则说明可以构建树。
'''
class Solution:
def validTree(self, n, edges):
self.parent = range(n)
return len(edges) == n-1 and all(map(self.union, edges))
def find(self, x):
return x if self.parent[x] == x else self.find(self.parent[x])
def union(self, xy): #union确定没有环, 再加上n-1的长度确定没
x, y = map(self.find, xy)
self.parent[x] = y
return x != y
#BFS只能做directed的。 undirected似乎得用union find
'''
class Solution: #可以用hashmap build 简单的node: children属性。
def validTree(self, n, edges):
self.d = d = {}; notRoot = set()
for rs in edges:
if rs[0] not in d: d[rs[0]] = []
d[rs[0]].append(rs[1])
notRoot.add(rs[1]) #找root
roots=[x for x in range(n) if x not in notRoot]
if len(roots)!=1: return False
return self.bfs(roots[0])
def bfs(self, root):
pre, found = [root], set([root]) # 除了pre, cur之外,还用了第三个vals
while pre:
cur, vals = [], [] #必须用array。 因为是有序的。 并且不会有重复
for node in pre:
if node not in self.d: continue
for x in self.d[node]:
if x in found: return False
found.add(x); cur.append(x)
pre = cur
return True
''' |
# encoding=utf-8
'''
Find a triplet from three linked lists with sum equal to a given number
先全部sort好
就是简单地3sum.
reverse一下chead
'''
#没有见过的题目。 不过和leetcode联系紧密
class Solution:
def findTrip(self, h1, h2, h3, target):
h3 = self.reverse(h3) #c要逆序排序
a = h1
while a:
b = h2; c = h3
while b and c:
s = a.val+b.val+c.val
if s==target: return True
elif s<target: b = b.next
else: c = c.next
a = a.next
return False
def reverse(self, head):
if not head: return
dummy= ListNode(0); dummy.next= head
pre, last, cur = dummy, head, head.next
while cur: #last一直是最后一个。 不变。
last.next = cur.next
cur.next = pre.next
pre.next = cur
cur = last.next #四层的封闭连环
return dummy.next |
# encoding=utf-8
#g4g原题
# Smallest subarray with sum greater than a given value
# sliding window, 也就是变种的cumulative sum
#Google 考过
'''
Determine minimum sequence of adjacent values in the input parameter array that is greater than input parameter sum.
sequence of adjacent values实际上就是sub array sum 如果是具体求。 是用cumulative
Eg
Array 2,1,1,4,3,6. and Sum is 8
Answer is length: 2, because 3,6 is minimum sequence greater than 8.
注意是求最短的序列长度。
因为无序。没有完全最好的方法。
暴力法O(n2)
l = 1, 2, ....len(arr)
第一次出现和大于8. 返回l
The algorithm is basically a while-loop.
while (wR < array_size) {
Move_wR(); // Find the next wR, window_sum > S;
Move_wL(); // Remove unnecessary left numbers;
UpdateMinimumSequenceLength();
}
//Note the window_sum should always larger than S, except:
1) in the initialization phase.
2) There is no solution to the question, (minimum_sequence_length == INT_MAX)
'''
'''
class Solution:
#暴力 . O(n2). 贪心。 跟jump game很像。
def findShortest(self, arr, target):
if sum(arr)<target: return
ret = len(arr)
for start in range(len(arr)):
s = 0
for end in range(start+1, len(arr)+1):
s+=arr[end-1]
if s>target: ret=min(ret, end-start)
return ret
'''
'''
for length in range(1, len(arr)+1):
s = sum(arr[:length])
for start in range(1, len(arr)-length+1):
s = max(s-arr[start]+arr[start+length-1], s)
if s>target: return length
return -1 #考虑负数的情况。 开始写sum(arr)<target: return -1 这是错的。 #corner举特例。 length=1
'''
# sliding window的套路。 l, r。 for r in range, if s>targe: while : l+=1
#O(n)的做法很巧妙
#sliding window就是满足条件的时候,加入一个while循环。 不断尝试移动left pointer。 不难。.
class Solution3:
def findShortest5(self, arr, target):
ret = float('inf')
s = 0; l=0
for r in range(len(arr)):
s+=arr[r]
if s>target:
while s-arr[l]>target:
s-=arr[l]; l+=1
ret = min(r-l+1, ret)
return ret
s= Solution3()
print s.findShortest5([ 2,1,1,4,3,6], 8)
# sliding window
'''
This takes O(n) since the window is always sliding into 1 direction (left to right), which stops at most 2n steps. which is O(n) steps. #
虽然有2个循环。 却是O(n)
''' |
# encoding=utf-8
'''
ind the longest words in a given list of words that can be constructed from a given list of letters.
Your solution should take as its first argument the name of a plain text file that contains one word per line.
The remaining arguments define the list of legal letters. A letter may not appear in any single word more times than it appears in the list of letters (e.g., the input letters ‘a a b c k’ can make ‘back’ and ‘cab’ but not ‘abba’).
Here's an example of how it should work:
prompt> word-maker WORD.LST w g d a s x z c y t e i o b
['azotised', 'bawdiest', 'dystocia', 'geotaxis', 'iceboats', 'oxidates', 'oxyacids', 'sweatbox', 'tideways']
Tip: Just return the longest words which match, not all.
'''
'''
Create an array of size 256 to record frequency of each letter, ex. for a,a,b,c,k ... the array will be [...,2,1,1,...,1,...] Than go through the each word and see it can be made by given letters.
To check a word, do following for each letter in the word:
1. if the value of the corresponding element in the array is zero than that word can not be made from given letters
2. otherwise decrease the value of that element by one.
Repeat this for each word and record the longest word matched.
'''
#与那道7 letter tile的区别。 那个是所有。 这个是最长
#有点暴力。不过好像已经是最好的办法了。
class Solution:
def longest(self, chList, wordList):
chCnt = self.cntW(chList)
wordList.sort(key=lambda w:-len(w))
for word in wordList:
if self.valid(word, chCnt): return word
def cntW(self, word): #经常用到。 单独拿出来吧。
d = {}
for ch in word:
if ch not in d: d[ch]=0
d[ch]+=1
return d
def valid(self, word, chCnt): #实际上pre Compute好了
wCnt = self.cntW(word)
for ch in wCnt:
if ch not in chCnt or chCnt[ch]<wCnt[ch]: return False
return True
# 三个minor的可以稍微优化。 都是pre-process
# #1 trie可以优化一点。 比如对于某些prefix。 直接标记不可行。 于是这个分支的词全部消去
# 2 pre compute the hashmap. 这样子每次check就是O(num of distinct char. which is less than 26 ) * O(n)
# 3 按word7长度从长的到段排序(预处理)。 从长到短来找, 可以优化。
# 4 prune, 跳过长度超过charList的单词
# 第5个优化。 预存所有车牌查好后的结果。
#
#
# 如果dictionary有上百萬個字,然後給你上千個車牌號碼,要你回傳相對應的最短字串,該如何optimize?
# 对应的一个arr[62]. preprocesss保存。 对应的最短的字串。。 然后如果车牌号对应的cnt array相同。 就不用重复找了。
# 或者sort车牌的字母。 作为key。 hashtable value储存结果 |
# encoding=utf-8
'''
Given a Binary Tree, find size of the Largest Independent Set(LIS) in it. A subset of all tree nodes is an independent set if there is no edge between any two nodes of the subset.
For example, consider the following binary tree. The largest independent set(LIS) is {10, 40, 60, 70, 80} and size of the LIS is 5.
Let LISS(X) indicates size of largest independent set of a tree with root X.
LISS(X) = MAX { (1 + sum of LISS for all grandchildren of X),
(sum of LISS for all children of X) }
noRoot = CurMax(root.left)+curMax(root.right)
WithRoot = noRoot(root.left)+noROot(root.right)+1
curMax = max(noRoot, WithRoot)
'''
# excl 有2个。 incl有5个。
class Solution(object):
def rob(self, root):
def dfs(x):
if not x: return (0, 0)
l, r = dfs(x.left), dfs(x.right)
return (l[1] + r[1], max(l[1] + r[1], l[0] + r[0] + 1))
return dfs(root)[1]
# https://leetcode.com/problems/house-robber-iii/
'''
noRoot(node) = curMax(node.left) + curMax(node.right)
curMax(node) = max( noRoot(node.left)+noRoot(node.right)+node.value, noRoot(node) ).
'''
#有点像这道题。 geeks: Given a Binary Tree, find size of the Largest Independent Set(LIS)
'''
#递归
class Solution:
def liss(self, root):
if not root: return 0
excl = self.liss(root.left)+self.liss(root.right)
incl = 1
if root.left: incl+=self.liss(root.left.left) + self.liss(root.left.right)
if root.right: incl+=self.liss(root.right.left) + self.liss(root.right.right)
return max(excl, incl)
#dp. {memoization}
# memoization思想在于return的时候先不return。 而是存到hashmap里边去。
class Solution1:
d ={}
def liss(self, root):
if not root: return 0
if root in self.d: return self.d[root]
size_excl = self.liss(root.left)+self.liss(root.right)
size_incl = 1
if root.left: size_incl+=self.liss(root.left.left) + self.liss(root.left.right)
if root.right: size_incl+=self.liss(root.right.left) + self.liss(root.right.right)
self.d[root] = max(size_excl, size_incl)
return self.d[root]
''' |
# encoding=utf-8
'''
Given a string (1-d array) , find if there is any sub-sequence that repeats itself.
Here, sub-sequence can be a non-contiguous pattern, with the same relative order.
Eg:
1. abab <------yes, ab is repeated
2. abba <---- No, a and b follow different order
3. acbdaghfb <-------- yes there is a followed by b at two places
4. abcdacb <----- yes a followed by b twice
The above should be applicable to ANY TWO (or every two) characters in the string and optimum over time.
In the sense, it should be checked for every pair of characters in the string.
'''
#we can modify the longest_common_subsequence(a, a) to find the value of the longest repeated subsequence in a by excluding the cases when i == j, (which we know are always equal in this case).
'''
Using your algorithm when I look at the result "M" of 'ababab' I get the following:
[a, b, a, b, a, b]
a [0, 0, 1, 1, 1, 1]
b [0, 0, 1, 2, 2, 2]
a [1, 1, 1, 2, 3, 3]
b [1, 2, 2, 2, 3, 4]
a [1, 2, 3, 3, 3, 4]
b [1, 2, 3, 4, 4, 4]
意思是。不考虑ij相等, ab在后面出现了4次。
'''
class Solution1:
def lcs(self, x):
n= len(x)
dp = [[0]*(n+1) for i in range(n+1)]
for i in range(1, n+1):
for j in range(1, n+1):
if x[i-1]==x[j-1] and i!=j: dp[i][j] = dp[i-1][j-1]+1 #就多了一句 i!=j
else: dp[i][j] = max(dp[i-1][j], dp[i][j-1])
return dp[-1][-1]>=2
s = Solution1()
strings = [
'abab',
'abba',
'acbdaghfb',
'abcdacb'
]
for x in strings:
print s.lcs(x) |
# encoding=utf-8
'''
给一个String 可以包含数字或者字母 找出里面的是否存在一个substring全是数字而且这个substring表示的数字可以被36整除,并且不能是0
e.g.: 360ab: True
0ab: False
'''
# 我是利用那个题做的 pattern match 比如输入pattern: 2p2 和一个string:apple 输出 true
class Solution:
def solve(self, s1):
i=0
while i<len(s1):
if '0'<=s1[i]<='9': #贪心。 如果是数字。 直接跳到后面。直到字母。
pre = i
while i<len(s1) and '0'<=s1[i]<='9': i+=1
n = int(s1[pre:i])
if n%36==0 and n!=0: return True
else: i+=1
return False
s = Solution()
print s.solve('360ab')
print s.solve('0ab') |
# encoding=utf-8
'''
Given an unsorted array, trim the array such that twice of minimum is greater than maximum in the trimmed array. Elements should be removed either end of the array.
Number of removals should be minimum.
Examples:
arr[] = {4, 5, 100, 9, 10, 11, 12, 15, 200}
Output: 4
We need to remove 4 elements (4, 5, 100, 200)
so that 2*min becomes more than max.
arr[] = {4, 7, 5, 6}
Output: 0
We don't need to remove any element as
4*2 > 7 (Note that min = 4, max = 8)
arr[] = {20, 7, 5, 6}
Output: 1
We need to remove 20 so that 2*min becomes
more than max
arr[] = {20, 4, 1, 3}
Output: 3
We need to remove any three elements from ends
like 20, 4, 1 or 4, 1, 3 or 20, 3, 1 or 20, 4, 1
'''
'''
A O(n^2) Solution
The idea is to find the maximum sized subarray such that 2*min > max. We run two nested loops, the outer loop chooses a starting point and the inner loop chooses ending point for the current starting point. We keep track of longest subarray with the given property.
'''
#题目说了从两边来trim的.remove最少。 所以是求最大subarray的过程.
#暴力是O(n3). 可以优化求min, max的过程。 到O(n2)
class Solution:
def dpremoval(self, arr):
ret = (0, -1); n = len(arr)
for b in range(n):
minN, maxN=float('inf'), float('-inf')
for e in range(b, n):
minN, maxN = min(arr[e], minN), max(arr[e], maxN)
if 2*minN > maxN and e-b>ret[-1]-ret[0]: ret = (b, e)
if ret==(0, -1): return
return arr[ret[0]:ret[1]+1]
s = Solution()
print s.dpremoval([4, 5, 100, 9, 10, 11, 12, 15, 200])
# 类似的用cur sum优化复杂度的有 Maximum sum rectangle in a 2D matrix |
# encoding=utf-8
'''
Write a function Add() that returns sum of two integers. The function should not use any of the arithmetic operators (+, ++, –, -, .. etc).
半加器: 00. 01 10 11
&是进位
^是求和
'''
class Solution: #比较简短。 背下。
def addBi(self, x, y):
while y:
print x, y
share = x&y #求进位. common bits, 左移也是和. 都是1. 要向左进位
x = x^y #求和. 求和。 不是common的bits和在x。
y = share<<1 #common bits和在y
return x
#加法: 都是1.左移1位。 只有一个是1.留下不变。
#化简版本
class Solution5: #比较简短。 背下。
def addBi(self, x, y):
while y:
x, y = x^y, (x&y)<<1 # 都是1. 要向左进位。 x, y的和一直都是恒定不变。
return x
'''
Above is simple Half Adder logic that can be used to add 2 single bits. We can extend this logic for integers. If x and y don’t have set bits at same position(s), then bitwise XOR (^) of x and y gives the sum of x and y. To incorporate common set bits also, bitwise AND (&) is used. Bitwise AND of x and y gives all carry bits. We calculate (x & y) << 1 and add it to x ^ y to get the required result.
'''
s = Solution()
print s.addBi(200, 400) |
# encoding=utf-8
'''
write the most efficient (in terms of time complexity) function getNumberOfPrimes which takes in an integer N as its parameter.
to return the number of prime numbers that are less than N
Sample Testcases:
Input #00:
100
Output #00:
25
Input #01:
1000000
Output #01:
78498
'''
class Solution:
def sieve(self,n):
noprimes = set()
ret = []
for i in range(2, n+1):
if i not in noprimes:
ret.append(i)
noprimes.update(range(i*i, n+1, i)) #对素数,追加 no primes
return ret |
# encoding=utf-8
'''
we have a random list of people. each person knows his own height and the number of tall people in front of him. write a code to make the equivalent queue.
for example :
input: <"Height","NumberOfTall","Name">,
<6,2,"A">,<1,4,"B">,<11,0,"C">,<5,1,"D">,<10,0,"E">,<4,0,"F">
output: "F","E","D","C","B","A" --> end of queue
想法非常赞
dequeue(set of people)
filter all people who have 0 no of people in front of them
//as 0 means either they are in the front of the queue or all people ahead of them are smaller than them
find the person with smallest height
//this will be the guy standing at the front of the queue
As this person will be removed so all people having height less than him and behind him (no of tall > 0) will no longer be able to see him. So we need to reduce the count of no of tall people by 1 for each
print the person and call the function with the remaining set of people.
[(6, 2, 'a'),(1, 4, 'B'),(11, 0 ,"c"),(5, 1, 'D'), (10, 0, 'E'),(4, 0, 'F')]
O(n2)
'''
# http://www.meetqun.com/thread-3505-1-1.html
class Solution:
def printQueue(self, arr):
ret = []
while arr:
first = min(x for x in arr if x[1]==0) #0里面找最矮的,
ret.append(first[2]) #站在队伍前面的潜在cadidates. tallNum
arr.remove(first)
for i, x in enumerate(arr):
if x[0]<first[0]: arr[i]=(x[0], x[1]-1, x[2]) #如果比small矮,则要更新一下tallnum了,减一
return ret
s = Solution()
print s.printQueue( [(6, 2, 'a'),(1, 4, 'B'),(11, 0 ,"C"),(5, 1, 'D'), (10, 0, 'E'),(4, 0, 'F')])
|
# encoding=utf-8
'''
Give efficient implementation of the following problem.
An item consist of different keys say k1, k2, k3. User can insert any number of items in database, search for item using any key, delete it using any key and iterate through all the items in sorted order using any key. Give the most efficient way such that it supports insertion, search based on a key, iteration and deletion.
'''
#3种key。 要可以三种iterator。 可以使用任意key来 search, delete
'''
Solution
There’re 3 keys, so we need 3 maps to store search map for 3 types of keys. For example, the DS is like this:
(date, name, country) –> ItemObject
Then we would have:
date –> a list of ItemObject
name –> a list of ItemObject
country –> a list of ItemObject
Since we need to iterate in order, we choose ordered dict over HashMap.
For scalability purpose, we use another HashMap<KeyType, ordered dict> and put 3 items in.
Final Data Structure
主要的数据是存在double linked list。 另外两个都是存了pointer to the DLL node
3 DS needed. source
DoubleLinkedList
Ordered Dict<KeyValue, List> index;
HashMap<KeyType, ordered dict<KeyValue, List>> mapOfIndexes;
hashmap: 三种类key,对应 三种ordered dict
Method add(item): void O(1)
add node in DoubleLinkedList. tail. O(1)
For each key, get ordered dict from HashMap and add node into ordered dict.
Method search(key): List O(1)
Get ordered dict from HashMap for provided key.
Look up from the ordered dict
Return item
Method delete(key): List O(1)
Using search method get List Of item
Delete items from ArrayList and also delete its mapping from all (3) ordered dict
Method orderedIterator(keytype): Iterator
Get ordered dict from HashMap for provided key
iterate using the ordered dict.
'''
# ordered dict我记得做不到O(1) 。 排序的话用bst吧 O(logN) |
# encoding=utf-8
'''
Given two strings str1 and str2, find if str1 is a subsequence of str2. A subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements (source: wiki). Expected time complexity is linear.
Examples:
Input: str1 = "AXY", str2 = "ADXCPY"
Output: True (str1 is a subsequence of str2)
Input: str1 = "AXY", str2 = "YADXCP"
Output: False (str1 is not a subsequence of str2)
Input: str1 = "gksrek", str2 = "geeksforgeeks"
Output: True (str1 is a subsequence of str2)
做法:
简单而巧妙
The idea is simple, we traverse both strings from one side to other side (say from rightmost character to leftmost). If we find a matching character, we move ahead in both strings. Otherwise we move ahead only in str2.
'''
class Solution:
def isSubsequene(self, s1, s2):
i=j=0
while i<len(s1) and j<len(s2):
if s1[i]==s2[j]:
i+=1
j+=1
else: j+=1
return i==len(s1)
s = Solution()
print s.isSubsequene('gksrek', 'geeksforgeeks') |
# encoding=utf-8
'''
题目是给一个string,返回含有word的list。word的定义是空格(大于 等于一个)之间的或者引号之间的,如果引号里面有空格要做为一个word返回。比如string是 I have a "faux coat" 要返回[I, have, a, faux coat]。
根据空格分隔字符串,但是引号内的是整体,不可分割
如果这个字符串是一个连续分布在很多机器上的大文件,每个机器知道其前后机器是谁并且可以相互通信,那么如何继续分隔(引号可以分在两个机器上
'''
#引号的写法 \", \'
#一个做法是可以先将split分割。 奇数位的就保留。 对于偶数位的。再处理空格。
#写代码就简单了, if ch== ' ' ;: while 贪心不断略过。
#普通的linear处理string问题。
# 至于follow-up.
# 记录碰到的引号是奇数还是偶数个。 0个也是偶数个。
class Solution:
def solve(self, s):
i=0; ret = []; s.strip()
while i<len(s):
if s[i]=='\"':
i+=1; pre=i
while i<len(s) and s[i]!='\"': i+=1
ret.append(s[pre:i])
elif s[i]!=' ':
pre = i
while i<len(s) and s[i]!=' ': i+=1
ret.append(s[pre:i])
i+=1
return ret
s = Solution()
print s.solve(''' I have a "faux coat"''')
#加上一个flag判断是奇是偶 |
# encoding=utf-8
'''
Given a BST and a value x. Find two nodes in the tree whose sum is equal x. Additional space: O(height of the tree). It is not allowed to modify the tree
'''
# 解法在这个文件Find a pair with given sum in a Balanced BST
'''
如果能够化为dll就容易。
'''
'''
G家
Given a BST and a number x, find two nodes in the BST whose sum is equal to x. You can not use extra memory like converting BST into one array and then solve this like 2sum.
'''
#第二个题目就是用convert to double linked list |
# encoding=utf-8
'''
Program an iterator for a Linked List which may include nodes which are nested within other nodes. i.e. (1)->(2)->(3(4))->((5)(6). Iterator returns 1->2->3->4->5->6
''' |
# encoding=utf-8
'''
Let's say there is a double square number X, which can be expressed as the sum of two perfect squares, for example, 10 is double square because 10 = 3^2 + 1^2
Determine the number of ways which it can be written as the sum of two squares
就是2-pointer版本的 two-sum
O(sqrt(n))
'''
#注意这里并没有overlapping 不是DP
#Count Distinct Non-Negative Integer Pairs (x, y) 和这道题目不一样。 那道是 x*x+y*y<n. 小于。
#就是2 sum找上限下限
class Solution:
def numWays(self, n):
i=0; j=int(n**0.5); cnt=0
while i<=j:
s = i*i+j*j
if s==n:
cnt+=1
i+=1; j-=1
elif s>n: j-=1
else: i+=1
return cnt
|
# encoding=utf-8
'''
# 三连棋游戏(两人轮流在一有九格方盘上划加字或圆圈, 谁先把三个同一记号排成横线、直线、斜线, 即是胜者),可以在线玩
N*N matrix is given with input red or black. You can move horizontally, vertically or diagonally. If 3 consecutive same color found, that color will get 1 point. So if 4 red are vertically then point is 2. Find the winner.
Tic-tac-toe game, N * N board, 红黑两方, 任何横向、竖向、对角线方向连续三个算一分(所以如果连续四个就是两分, 六个就是四分), 给你一个boolean array, 求谁是winner
(R,R,R,R) = (R1,R2,R3), (R2,R3,R4). Hence 2 pts. Nothing special about being vertical or 4 tiles long.
所以只要考虑三个就可以了。 iterative可以做。
'''
#预处理是比较好的啊。。。 三进制的数。 =》 整数。 3**(n2)
# encoding=utf-8
'''
N*N matrix is given with input red or black. You can move horizontally, vertically or diagonally. If 3 consecutive same color found, that color will get 1 point. So if 4 red are vertically then point is 2. Find the winner.
Tic-tac-toe game, N * N board, 红黑两方, 任何横向、竖向、对角线方向连续三个算一分(所以如果连续四个就是两分, 六个就是四分), 给你一个boolean array, 求谁是winner
(R,R,R,R) = (R1,R2,R3), (R2,R3,R4). Hence 2 pts. Nothing special about being vertical or 4 tiles long.
所以只要考虑三个就可以了。 iterative可以做。
'''
class Solution:
def findWinner(self, ):
print 'black count: ' + str(self.findCount('b')), 'red count: ' + str(self.findCount('r'))
def findCount(self, matrix, color):
if not matrix: return 0
count = 0; row = len(matrix); col = len(matrix[0])
for i in range(row):
for j in range(col):
if j+2<=col-1 and matrix[i][j] == matrix[i][j+1] == matrix[i][j+2]==color: count+=1
if i+2<=row-1 and matrix[i][j] == matrix[i+1][j] == matrix[i+2][j]==color: count+=1
if i+2<=row-1 and j+2<=col-1 and matrix[i][j] == matrix[i+1][j+1] == matrix[i+2][j+2]==color: count+=1
if i-2>=0 and j+2<=col-1 and matrix[i][j] == matrix[i-1][j+1] == matrix[i-2][j+2]==color: count+=1
return count
'''
#G家考过题目
tic-tac-toe: 给一个board,以current state判断是o 赢, x 赢, 还是没人赢。
follow up每次只能取一行的信息,每次只能存储O(2N+K)的数据
简单的dp
我觉得可以这样子。
还是之前的in-place做法类似。
保存前两行的状态。 每次check上面两行。 (本行是最下面的那个格子)
'''
#下面是cracking的题目
'''
假设这个检查某人是否赢得了井字游戏的函数为HasWon,那么我们第一步要向面试官确认, 这个函数是只调用一次,还是要多次频繁调用。如果是多次调用, 我们可以通过预处理来得到一个非常快速的版本。
方法一:如果HasWon函数需要被频繁调用
对于井字游戏,每个格子可以是空,我的棋子和对方的棋子3种可能,总共有39 = 19683 种可能状态。我们可以把每一种状态转换成一个整数, 预处理时把这个状态下是否有人赢得了井字游戏保存起来,每次检索时就只需要O(1)时间。 比如每个格子上的3种状态为0(空),1(我方棋子),2(对方棋子),棋盘从左到右, 从上到下依次记为0到8,那么任何一个状态都可以写成一个3进制的数,再转成10进制即可。 比如,下面的状态:
1 2 2
2 1 1
2 0 1
可以写成:
122211201=1*3^8 + 2*3^7 +...+ 0*3^1 + 1*3^0
如果只需要返回是否有人赢,而不需要知道是我方还是对方。 那可以用一个二进制位来表示是否有人赢。比如上面的状态,1赢, 就可以把那个状态转换成的数对应的位置1。如果需要知道是谁赢, 可以用一个char数组来保存预处理结果。
方法二:如果HasWon函数只被调用一次或很少次
如果HasWon函数只被调用一次或很少次,那我们就没必要去预存结果了, 直接判断一下就好。只为一次调用去做预处理是不值得的。
代码如下,判断n*n的棋盘是否有人赢,即同一棋子连成一线:
''' |
# encoding=utf-8
'''
Count all possible walks(paths) from a source to a destination with exactly k edges
Given a directed graph and two vertices ‘u’ and ‘v’ in it, count all possible walks from ‘u’ to ‘v’ with exactly k edges on the walk.
The graph is given as adjacency matrix representation where value of graph[i][j] as 1 indicates that there is an edge from vertex i to vertex j and a value 0 indicates no edge from i to j.
For example consider the following graph. Let source ‘u’ be vertex 0, destination ‘v’ be 3 and k be 2. The output should be 2 as there are two walk from 0 to 3 with exactly 2 edges. The walks are {0, 2, 3} and {0, 1, 3}
O(n**k)
'''
# 用memoization 就好。
class Solution:
def countWalks(self, graph, u, v, k):
if k==0 and u==v: return 1 #
if k==1 and graph[u][v]: return 1
if k<=0: return 0 #注意确实要放在这里比较好
cnt = 0
for i in range(len(graph)):
if i==u or i==v: continue
if graph[u][i]: cnt+=self.countWalks(graph, i, v, k-1) #u=>i=>v 1+ k-1 steps
return cnt
'''
dp
O(n3*k)
'''
class Solution2:
def countWalks(self, graph, u, v, k):
n = len(graph)
dp = [[[0 for i in range(n)]for j in range(n)]for p in range(k+1)]
for e in range(k+1):
for i in range(n):
for j in range(n):
if e==0 and i==j: dp[e][i][j]=1
elif e==1 and graph[i][j] : dp[e][i][j] = 1
elif e>1:
for a in range(n):
if a==j or a==i: continue
if graph[i][a]: dp[e][i][j] += dp[e-1][a][j] #1+ k-1 steps i=>a=>j
return dp[-1][u][v]
|
# encoding=utf-8
'''
Output top N positive integer in string comparison order. For example, let's say N=1000, then you need to output in string comparison order as below:
1, 10, 100, 1000, 101, 102, ... 109, 11, 110, ...
'''
class Solution:
def dfs(self,s):
if int(s)>self.n: return
self.ret.append(s)
for i in range(10): # 0~9都可以
self.dfs(s+str(i))
def solve(self, n=1000):
self.n = n; self.ret = []
for i in range(1, 10): #1~9
self.dfs(''+str(i))
return self.ret
s = Solution()
print s.solve(1000)
#感觉很牛逼的样子。 还没有看懂
'''
DFS comes to our rescue.
if you observe a little you can find out that there is a nice pattern
Start with a char 1-9 in that order (9 iterations).
Add a 0-9 to right of string one at a time and recursively do dfs.
if value<=n print it.
recursively keep on adding char to the right.
when value>n. return from dfs call.
''' |
# encoding=utf-8
def f1():
return 1
def f2():
return 2
myfuctions = {'a':f1, 'b':f2}
print myfuctions['a']()
print myfuctions['b']()
'''
每个函数都是变量
closures and currying
'''
def outer(outArg):
def inner(innerArg):
return outArg+innerArg
return outArg
func = outer(10)
def make_adder(addend):
def adder(augend):
return augend + addend
return adder #返回的是函数。
#我们可以把addend看做新函数的一个配置信息,配置信息不同,函数的功能就不一样了,也就是能得到定制之后的函数.
p = make_adder(23)
q = make_adder(44)
print p
print q
print p(100)
print q(100)
def hellocounter (name):
count=[0]
def counter():
count[0]+=1
print 'Hello,',name,',',str(count[0])+' access!'
return counter
hello = hellocounter('ma6174')
hello()
hello()
hello()
'''
这个程序比较有趣,我们可以把这个程序看做统计一个函数调用次数的函数.count[0]可以看做一个计数器,没执行一次hello函数,count[0]的值就加1。也许你会有疑问:为什么不直接写count而用一个列表?这是python2的一个bug,如果不用列表的话,会报这样一个错误:
UnboundLocalError: local variable 'count' referenced before assignment.
什么意思?就是说conut这个变量你没有定义就直接引用了,我不知道这是个什么东西,程序就崩溃了.于是,再python3里面,引入了一个关键字:nonlocal,这个关键字是干什么的?就是告诉python程序,我的这个count变量是再外部定义的,你去外面找吧.然后python就去外层函数找,然后就找到了count=0这个定义和赋值,程序就能正常执行
'''
def makebold(fn):
def wrapped():
return "<b>" + fn() + "</b>"
return wrapped
def makeitalic(fn):
def wrapped():
return "<i>" + fn() + "</i>"
return wrapped
@makebold
@makeitalic
def hello():
return "hello world"
print hello()
'''
decorator
怎么样?这个程序熟悉吗?这不是传说的的装饰器吗?对,这就是装饰器,其实,装饰器就是一种闭包,我们再回想一下装饰器的概念:对函数(参数,返回值等)进行加工处理,生成一个功能增强版的一个函数。再看看闭包的概念,这个增强版的函数不就是我们配置之后的函数吗?区别在于,装饰器的参数是一个函数或类,专门对类或函数进行加工处理。
python里面的好多高级功能,比如装饰器,生成器,列表推到,闭包,匿名函数等,开发中用一下,可能会达到事半功倍的效果!
语法示例:
@dec1
@dec2
def test(arg):
pass
其效果类似于
dec1(dec2(test(arg)))
''' |
# encoding=utf-8
'''
Escape strings. Convert special ASCII characters to form of ‘\ooo’, where ‘ooo’ is oct digit of the corresponding special character.
The ascii characters that smaller than space are regarded as special characters.
'''
'''
转化成任意的x进制:
不断while n
n, d = n/x, d%x
'''
class Solution:
def convert(self, s):
return ''.join(["\\"+ oct(ord(ch)) if ord(ch)<ord(' ') else ch for ch in s])
'''
class Solution:
def convert(self, s):
ret =''
for ch in ret:
if ord(ch)<ord(' '): ret+= "\\"+ oct(ord(ch))
else: ret+=ch
return ret
'''
'''
s = '\n'
print len(s)
s = '\\'
print len(s), s
'\n'一般认为是一个字符
'''
'''
递增为正斜杠 forward slash
递减为反斜杠 back slash
正斜杠为除法。
\n 转义为反斜杠 back slash
''' |
# encoding=utf-8
'''
Tail Recursion
What is tail recursion?
A recursive function is tail recursive when recursive call is the last thing executed by the function. For example the following C++ function print() is tail recursive.
// An example of tail recursive function
void print(int n)
{
if (n < 0) return;
cout << " " << n;
// The last executed statement is recursive call
print(n-1);
}
Why do we care?
The tail recursive functions considered better than non tail recursive functions as tail-recursion can be optimized by compiler. The idea used by compilers to optimize tail-recursive functions is simple, since the recursive call is the last statement, there is nothing left to do in the current function, so saving the current function’s stack frame is of no use.
Can a non-tail recursive function be written as tail-recursive to optimize it?
Consider the following function to calculate factorial of n. It is a non-tail-recursive function. Although it looks like a tail recursive at first look. If we take a closer look, we can see that the value returned by fact(n-1) is used in fact(n), so the call to fact(n-1) is not the last thing done by fact(n)
#因为不用存stack的东西。
The above function can be written as a tail recursive function. The idea is to use one more argument and accumulate the factorial value in second argument. When n reaches 0, return the accumulated value.
#include<iostream>
using namespace std;
// A tail recursive function to calculate factorial
unsigned factTR(unsigned int n, unsigned int a)
{
if (n == 0) return a;
return factTR(n-1, n*a);
}
// A wrapper over factTR
unsigned int fact(unsigned int n)
{
return factTR(n, 1);
}
'''
def fact(n):
if n==0: return 1
return n*fact(n-1)
|
# encoding=utf-8
'''
What is the Minimum Amount not possible using an infinite supply of coins (Unbounded knapsack)
You are given coins of
Denominations {v1, v2 , v3, v4 ....vn } of weight {w1, w2, w3 .....wn}
Now that you have a bag of capacity W .
Find the smallest Value V that is not possible to have in the bag.
(Note , you are not trying to maximize the value V)
'''
'''
1) Use knapsack problem to find the minimum value(instead of maximum) for Weight W. In the original algo instead of taking maximum value take minimum value for each Array[i] , 0<i<=W.
2) Now for each value of n, find the minimum index i in Array such that i+w[n]> W and note the value as Array[i]+v[n]. Update this value if the old value is greater than the new value
'''
#暴力法应当是正解。
#普通的dfs
#combination sum
class Solution:
# @param candidates, a list of integers
# @param target, integer
# @return a list of lists of integers
def combinationSum(self, vals, weights, target):
self.vals = [(vals[i], weights[i]) for i in range(len(vals))];
self.dfs(0, target, []); self.ret = set()
i=1
while True:
if i not in self.ret: return i
i+=1
def dfs(self, n1, c, cur):
self.ret.add(cur)
for i in range(n1, len(self.vals)):
x = self.vals[i][0]; y=self.vals[i][1]
if c>=y:
self.dfs(i, c-x, cur+[x])
'''
#感觉用dp是错误的。
#dp
class Solution:
def knapSack(self, weight, vals, c):
m = len(vals); n=len(weight)
dp = [[0 for x in range(n+1)] for j in range(m+1)]
setV = set()
for x in range(n+1):
for j in range(m+1):
if weight[x-1]<=c: dp[x][j] = min(vals[x-1]+dp[x-1][c-weight[x-1]], dp[x-1][j])
else: dp[x][j] = dp[x-1][j]
setV.add(dp[x][j])
x=0
while True:
if x not in setV: return x
x+=1
''' |
# encoding=utf-8
'''
Maximum sum such that no two elements are adjacent
Question: Given an array of positive numbers, find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array. So 3 2 7 10 should return 13 (sum of 3 and 10) or 3 2 5 10 7 should return 15 (sum of 3, 5 and 7).Answer the question in most efficient way.
'''
'''
Algorithm:
Loop for all elements in arr[] and maintain two sums incl and excl where incl = Max sum including the previous element and excl = Max sum excluding the previous element.
Max sum excluding the current element will be max(incl, excl) and max sum including the current element will be excl + current element (Note that only excl is considered because elements cannot be adjacent).
At the end of the loop return max of incl and excl.
Example:
arr[] = {5, 5, 10, 40, 50, 35}
inc = 5
exc = 0
For i = 1 (current element is 5)
incl = (excl + arr[i]) = 5
excl = max(5, 0) = 5
For i = 2 (current element is 10)
incl = (excl + arr[i]) = 15
excl = max(5, 5) = 5
For i = 3 (current element is 40)
incl = (excl + arr[i]) = 45
excl = max(5, 15) = 15
For i = 4 (current element is 50)
incl = (excl + arr[i]) = 65
excl = max(45, 15) = 45
For i = 5 (current element is 35)
incl = (excl + arr[i]) = 80
excl = max(5, 15) = 65
'''
'''
IncludeSum = ExcludeSum(i-1) + arr[i]
ExcludeSum = max (IncludeSum(i-1), ExcludeSum(i-1))
'''
#Given a Binary Tree, find size of the Largest Independent Set(LIS) in it.
#有道树的题目有点像
class Solution: #比较难。 背下
def find(self, arr):
if not arr:return
incl=excl=0
for x in arr:
incl, excl = excl+x, max(incl, excl)
return max(excl, incl)
s = Solution()
print s.find([3 ,2 ,10 ,7])
print s.find([5, 5, 10, 40, 50, 35]) |
# encoding=utf-8
a = [1, 3, 2]
b = a[1:3]
print a, b
print id(a[-1])
print id(b[-1])
b[1]=1
print id(a[-1])
print id(b[-1])
# 可以看出。 用了slice,是一种shallow copy. a, b是独立的。 但是如果你不改变b的话, 也没有消费新的空间。
# 也就是说。
# a[1:3] == b[:]. 并没有开辟新的空间。
#因为python 很 smart.
#所以可以放心使用。 |
# encoding=utf-8
'''
Find the number of zeroes
Given an array of 1s and 0s which has all 1s first followed by all 0s. Find the number of 0s. Count the number of zeroes in the given array.
Examples:
Input: arr[] = {1, 1, 1, 1, 0, 0}
Output: 2
Input: arr[] = {1, 0, 0, 0, 0}
Output: 4
Input: arr[] = {0, 0, 0}
Output: 3
Input: arr[] = {1, 1, 1, 1}
Output: 0
'''
#又碰到了。。
'''
Binary Search to find the first occurrence of 0. Once we have index of first element, we can return count as n – index of first zero.
'''
class Solution:
def isMajority(self, arr):
r = self.rightS(arr, 1)
if r==-1: return 0
return r+1
def rightS(self, arr, x):
l=0; h = len(arr)-1
while l<=h:
m = (l+h)/2
if (m==len(arr)-1 or arr[m+1]!=x) and arr[m]==x: return m
elif arr[m]>x: h=m-1
else: l=m+1 #其他时候,相等的时候,也是在右边
return -1 #没找到返回一个flag |
# encoding=utf-8
'''
Maximum size square sub-matrix with all 1s
Maximum size square sub-matrix with all 1s
Given a binary matrix, find out the maximum size square sub-matrix with all 1s.
For example, consider the below binary matrix.
0 1 1 0 1
1 1 0 1 0
0 1 1 1 0
1 1 1 1 0
1 1 1 1 1
0 0 0 0 0
The maximum square sub-matrix with all set bits is
1 1 1
1 1 1
1 1 1
Algorithm:
Let the given binary matrix be M[R][C]. The idea of the algorithm is to construct an auxiliary size matrix S[][] in which each entry S[i][j] represents size of the square sub-matrix with all 1s including M[i][j] where M[i][j] is the rightmost and bottommost entry in sub-matrix.
1) Construct a sum matrix S[R][C] for the given M[R][C].
a) Copy first row and first columns as it is from M[][] to S[][]
b) For other entries, use following expressions to construct S[][]
If M[i][j] is 1 then
S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1
Else /*If M[i][j] is 0*/
S[i][j] = 0
2) Find the maximum entry in S[R][C]
3) Using the value and coordinates of maximum entry in S[i], print
sub-matrix of M[][]
For the given M[R][C] in above example, constructed S[R][C] would be:
0 1 1 0 1
1 1 0 1 0
0 1 1 1 0
1 1 2 2 0
1 2 2 3 1
0 0 0 0 0
The value of maximum entry in above matrix is 3 and coordinates of the entry are (4, 3). Using the maximum value and its coordinates, we can find out the required sub-matrix.
Time Complexity: O(m*n) where m is number of rows and n is number of columns in the given matrix.
Auxiliary Space: O(m*n) where m is number of rows and n is number of columns in the given matrix.
Algorithmic Paradigm: Dynamic Programming
和leetcode不同在于这个是正方形。
还是leetcode更加通用一些
'''
class Solution:
def printMaxSubSquare(self, matrix):
m = len(matrix); n = len(matrix[0]); ret = 0
dp = [x[:] for x in matrix]
for i in range(m):
for j in range(n):
if i and j and matrix[i][j] == 1: dp[i][j] = min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) + 1 #正方形。第四角 至少要前面3个部分
ret = max(ret, dp[i][j])
return ret
s = Solution()
print s.printMaxSubSquare([[1, 1]]) |
# encoding=utf-8
#n boxes, k balls, expected number of empty boxes.
'''
比如If you have 10 balls and 5 boxes what is the expected number of boxes with no balls.
#期望 : 取值xi与对应的概率Pi(=xi)之积的和称为该离散型随机变量的数学期望
x[i] 代表第几个盒子为空。的概率。
x = sum(x[i] for i in range(5) )
x[i] = 4**10/5**10 # 有一个box没有ball的概率
x = 5* (4**10/5**10) #
结果是 4**10/5**10 。
期望=x*prob(x) =1* prob(1)
x = n*((n-1)**k)/(n)**k #这个是概率吧~
'''
# http://math.stackexchange.com/questions/66077/how-to-find-the-expected-number-of-boxes-with-no-balls
'''
类似的.
Expected Number with $1$ Ball
x = sum(x[i] for i in range(5) )
x[i] =10* ( 4**9/ 5**10 ) #有某个盒子有一个球 的概率。
x = 5* x[i] = 5*10* ( 4**9/ 5**10 ) # 错误的。
'''
# 分母总是种类。
#不完全正确。 x[0], x[1], x[2]可能会重叠。 |
# encoding=utf-8
'''
Search in an almost sorted array
Given an array which is sorted, but after sorting some elements are moved to either of the adjacent positions, i.e., arr[i] may be present at arr[i+1] or arr[i-1]. Write an efficient function to search an element in this array. Basically the element arr[i] can only be swapped with either arr[i+1] or arr[i-1].
For example consider the array {2, 3, 10, 4, 40}, 4 is moved to next position and 10 is moved to previous position.
Example:
# 3和10混淆了, 40和20混淆了。
Input: arr[] = {10, 3, 40, 20, 50, 80, 70}, key = 40
Output: 2
Output is index of 40 in given array
Input: arr[] = {10, 3, 40, 20, 50, 80, 70}, key = 90
Output: -1
-1 is returned to indicate element is not present
'''
class Solution:
def bs(self, arr, x):
l=0; h=len(arr)-1
while l<=h:
m = l+(h-l)/2
if x==arr[m]: return m
elif m!=0 and arr[m-1]==x: return m-1
elif m!=len(arr)-1 and arr[m+1]==x: return m+1 #每次都检查3个点
elif arr[m]>x: h =m-2 #比较赞的题目
else: l=m+2
|
# encoding=utf-8
'''
String compressor that turns "123abkkkkkc" to "123ab5xkc". Decompressor
is already written and must remain unchanged. take into account of strings
like: "123xk", "123xx" ...etc as input
'''
# 普通的话。 就是如果cnt==1。 就不加上cnt了。
#按照微软的思路。 x=> -ord(x) . 用正负标记比如5个k。 变成-5
class Solution:
# @return a string
def countAndSay(self, chArr):
ret = []; pre = chArr[0]; cnt=1
for j in range(1, len(chArr)):
if chArr[j]==pre: cnt+=1
else:
self.help(cnt, pre, ret)
cnt=1; pre = chArr[j]
self.help(cnt, pre, ret)
return ret
def help(self, cnt, pre, ret):
t = ord(pre)
if pre=='x': t = -t
if cnt==1: ret+=t
else: ret+=[ord(str(cnt)), t]
return t
#微软那道题目。
'''
Compress a given string "aabbbccc" to "a2b3c3"
constraint: inplace compression, no extra space to be used
assumption : output size will not exceed input size.. ex input:"abb" -> "a1b2" buffer overflow.. such inputs will not be given.
'''
class Solution:
# @return a string
def countAndSay(self, chArr):
ret = []; pre = chArr[0]; cnt=1
for j in range(1, len(chArr)):
if chArr[j]==pre: cnt+=1
else:
self.help(cnt, pre, ret)
cnt=1; pre = chArr[j]
self.help(cnt, pre, ret)
return ret
def help(self, cnt, pre, ret):
t = ord(pre)
if cnt==1: ret+=[-t]
else: ret+=[ord(str(cnt)), t]
return t
|
# encoding=utf-8
'''
Program to find amount of water in a given glass
There are some glasses with equal capacity as 1 litre. The glasses are kept as follows:
1
2 3
4 5 6
7 8 9 10
You can put water to only top glass. If you put more than 1 litre water to 1st glass, water overflows and fills equally in both 2nd and 3rd glasses. Glass 5 will get water from both 2nd glass and 3rd glass and so on.
If you have X litre of water and you put that water in top glass, how much water will be contained by jth glass in ith row?
Example. If you will put 2 litre on top.
1st – 1 litre
2nd – 1/2 litre
3rd – 1/2 litre
The approach is similar to Method 2 of the Pascal’s Triangle. If we take a closer look at the problem, the problem boils down to Pascal’s Triangle.
1 ---------------- 1
2 3 ---------------- 2
4 5 6 ------------ 3
7 8 9 10 --------- 4
Each glass contributes to the two glasses down the glass. Initially, we put all water in first glass. Then we keep 1 litre (or less than 1 litre) in it, and move rest of the water to two glasses down to it. We follow the same process for the two glasses and all other glasses till ith row. There will be i*(i+1)/2 glasses till ith row.
'''
class Solution:
def findWater(self, r, c, x):
assert c<r
glass = [0 for k in range((r+1)*r/2)] #等差数列,
glass[0] = x; p = 0
for i in range(1, r+1):
for j in range(1, c+1):
x = glass[p]
glass[p] = min(x, 1) #一班是1. 也可能是x
x -=glass[p]
glass[p+i] += x/2
glass[p+i+1] +=x/2
p+=1
return glass[r*(r-1)/2+c-1] #因为从0开始。所以最后减一. 可以拿r=c=0测试下
|
# encoding=utf-8
'''
Majority Element: A majority element in an array A[] of size n is an element that appears more than n/2 times (and hence there is at most one such element).
Write a function which takes an array and emits the majority element (if it exists), otherwise prints NONE as follows:
'''
#G家考过 O(1) space, O(n)
# sort 后, arr[n/2]就是。。 O(nlogn)
# hash则要O(n)
'''
算法的基本思想非常简洁: 每次都找出一对不同的元素,从数组中删掉,直到数组为空或只有一种元素。 不难证明,如果存在元素e出现频率超过半数,那么数组中最后剩下的就只有e。当然,最后剩下的元素也可能并没有出现半数以上。比如说数组是[1, 2, 3],最后剩下的3显然只出现了1次,并不到半数。排除这种false positive情况的方法也很简单,只要保存下原始数组,最后扫描一遍验证一下就可以了。
'''
'''
现在来分析一下复杂度。删除元素可以在常数时间内完成,但找不同元素似乎有点麻烦。实际上,我们可以换个角度来想,用一个小trick来重新实现下该算法。
在算法执行过程中,我们使用常量空间实时记录一个候选元素c以及其出现次数f(c),c即为当前阶段出现次数超过半数的元素。在遍历开始之前,该元素c为空,f(c)=0。然后在遍历数组A时,
如果f(c)为0,表示当前并没有候选元素,也就是说之前的遍历过程中并没有找到超过半数的元素。那么,如果超过半数的元素c存在,那么c在剩下的子数组中,出现次数也一定超过半数。因此我们可以将原始问题转化为它的子问题。此时c赋值为当前元素, 同时f(c)=1。
如果当前元素A[i] == c, 那么f(c) += 1。(没有找到不同元素,只需要把相同元素累计起来)
如果当前元素A[i] != c,那么f(c) -= 1 (相当于删除1个c),不对A[i]做任何处理(相当于删除A[i])
如果遍历结束之后,f(c)不为0,那么再次遍历一遍数组,记录c真正出现的频率,从而验证c是否真的出现了超过半数。上述算法的时间复杂度为O(n),而由于并不需要真的删除数组元素,我们也并不需要额外的空间来保存原始数组,空间复杂度为O(1)。实际上,在Moore大牛的主页上有针对这个算法的一个演示,感兴趣的同学可以直接移步观看。
'''
#hash是O(n), O(n)
#其他元素看做-1, 这个元素看做1??。。
class Solution: #
# @param num, a list of integers
# @return an integer
def majorityElement(self, arr):
maj = self.findCandidate(arr)
assert arr.count(maj)>len(arr)/2 ## verify arr[x] really appears
return maj
def findCandidate(self, arr):
ret =arr[0]; cnt=0
for x in arr:
if x==ret: cnt+=1
else: cnt-=1
if cnt==0: #之前部分没有出现超过半数的元素。 继续到剩下的部分找。
ret=x; cnt=1
return ret
'''
一个不错的方法。 O(32 N )
Runtime: O(n) — Moore voting algorithm: We maintain a current candidate and a counter initialized to 0. As we iterate the array, we look at the current element x:
If the counter is 0, we set the current candidate to x and the counter to 1.
If the counter is not 0, we increment or decrement the counter based on whether x is the current candidate.
After one pass, the current candidate is the majority element. Runtime complexity = O(n).
Runtime: O(n) — Bit manipulation: We would need 32 iterations, each calculating the number of 1's for the ith bit of all n numbers. Since a majority must exist, therefore, either count of 1's > count of 0's or vice versa (but can never be equal). The majority number’s ith bit must be the one bit that has the greater count.
Update (2014/12/24): Improve algorithm on the O(n log n) sorting solution: We do not need to 'Find the longest contiguous identical element' after sorting, the n/2th element is always the majority.
public int majorityElement(int[] num) {
int ret = 0;
for (int i = 0; i < 32; i++) {
int ones = 0, zeros = 0;
for (int j = 0; j < num.length; j++) {
if ((num[j] & (1L << i)) != 0) {
++ones;
}
else
++zeros;
}
if (ones > zeros)
ret |= (1L << i);
}
return ret;
}
''' |
# encoding=utf-8
#简单做法是用hash
'''
Check if array elements are consecutive | Added Method 3
Given an unsorted array of numbers, write a function that returns true if array consists of consecutive numbers.
Examples:
a) If array is {5, 2, 3, 1, 4}, then the function should return true because the array has consecutive numbers from 1 to 5.
b) If array is {83, 78, 80, 81, 79, 82}, then the function should return true because the array has consecutive numbers from 78 to 83.
c) If the array is {34, 23, 52, 12, 3 }, then the function should return false because the elements are not consecutive.
d) If the array is {7, 6, 5, 5, 3, 4}, then the function should return false because 5 and 5 are not consecutive.
'''
#方法一'
'''
O(n) space
1) max – min + 1 = n where max is the maximum element in array, min is minimum element in array and n is the number of elements in array.
2) All elements are distinct.
'''
class Solution:
def find(self, arr):
return max(arr)-min(arr)+1==len(arr) == len(set(arr)) # set实质是hashtable。用了 O(n) space
#方法2
'''
第一步一样。 第二步:it changes the original array and it works only if all numbers are positive.
arr[arr[i] - min]] as a negative value. If we see a negative value again then there is repetition.
'''
# Find duplicates in O(n) time and O(1) extra space
#inplace
class Solution3: #假定没有负数出现
def isCon(self, arr): #利用index, 以及正负标记. 来check是否重复
small = min(arr)
if max(arr)-small+1!=len(arr): return False #注意,置为负数时候,必须为arr[i]-minVal
for i in range(len(arr)):
t = abs(arr[i])-small #因为max-min = length。 所以abs(arr[i])-small一定OK
if arr[t]<0: return False
else: arr[t]=-arr[t]
return True |
# encoding=utf-8
'''
有两个一样的树A和B,每个节点都有父指针,要求写一个
函数,参数是A的一个子节点x,和B的根节点,要求返回B中对应x的那个节点。也就是
说A的根节点未知。这题挺简单,所以我没怎么想就说了先找到A的根节点,然后同时对
A和B做一个DFS或者BFS来找出B中对应x的节点。面试官说可以,让我写代码,写完以后
分析了一下复杂度。然后就问有没有更好的方法,我马上就意识到不需要用DFS或者BFS
,只需要在找A的根节点时记录下当前路径就行了(只需记录每个子结点是父节点的第
几个孩子),然后按同样的路径扫一下B树。复杂度只有O(height),
'''
class Solution:
def find(self, x, bRoot): #路径。 左代表-1. 右边代表1
stack = []
while x.parent:
t = x.parent
if t.right == x: stack.append(1)
else: stack.append(-1)
x = t
while stack:
if stack.pop()==1: bRoot=bRoot.right
else: bRoot=bRoot.left
return bRoot |
# encoding=utf-8
'''
Count number of bits to be flipped to convert A to B
'''
class Solution:
def cntBits(self, n):
cnt = 0
while n:
cnt+=n&1
n>>=1
return cnt
def countFlip(self, a, b):
return self.cntBits(a^b)
'''
# Turn off the rightmost set bit
class Solution:
def cntBits(self, n):
cnt=0
while n:
n&=n-1
cnt+=1
return cnt
def countFlip(self, a, b):
return self.cntBits(a^b)
Solution:
1. Calculate XOR of A and B.
a_xor_b = A ^ B
2. Count the set bits in the above calculated XOR result.
countSetBits(a_xor_b)
''' |
# encoding=utf-8
'''
There are a large number of leaves eaten by caterpillars. There are 'K"' caterpillars which jump onto the leaves in a pre-determined sequence. All caterpillars start at position 0 and jump onto the leaves at positions 1,2,3...,N. Note that there is no leaf at position 0.
Each caterpillar has an associated 'jump-number'. Let the jump-number of the i-th caterpillar be A [i]. A caterpillar with jump number 7 keeps eating leaves in the order 1,241,3*1,... till it reaches the end of the leaves - i.e, it eats the leaves at the positions which are multiples of /'.
Given a set 'A' of 'IC elements. 'e<=15.,. 'N'<=109, we need to determine the number of uneaten leaves.
Input Format:
N -number of leaves
A - Given array of integers
Output Format:
An integer denoting the number of uneaten leaves.
Sample Input:
N = 10. (1~10)
A = [2,4,5]
Sample Output:
4
Explanation
1,3,7,9 are the leaves which are never eaten. All leaves which are multiples of 2, 4, and 5 have been eaten.
题目太长懒得看。 直接看input, output
#hashtable 可以秒杀40%的题目!!!!!!
'''
class Solution:
def countUneaten(self, n, arr):
return n-len(set(y for x in arr for y in range(x, n+1, x)))
'''
class Solution:
def countUneaten(self, n, arr):
d = {}
for i in arr:
for j in range(i, n+1, i): #类似于sieve prime那道题目
if j not in d: d[j] = 1
print d
return n-len(d)
'''
s = Solution()
print s.countUneaten(10, [2, 4, 5])
#素数题目。 解法用sieve prime |
#DFS is more common. BFS can find the shortest path
#BFS uses while loop. DFS uses recursion
__author__ = 'zhenglinyu'
def BFS(s, adj):
level = {}
level[s] = 0
parent = {}
parent[s] = None
i = 1
frontier = [s]
while frontier:
next = []
for u in frontier:
for v in adj[u]:
if v not in level:
level[v] = i
parent[v] = u
next.append(v)
frontier = next
i+=1
parents = {}
def DFS(V, adj):
parents = {}
for s in V:
if s not in parents:
parents[s] = None
DFS_visit(adj, s)
def DFS_visit( adj, s):
for i in adj[s]:
if i not in parents:
parents[i] = s
DFS_visit( adj, i)
|
# encoding=utf-8
'''
given a board with black (1) and white (0), black are all connected. find the max rectangle that contains all black.
example:
0 0 0 0 0
0 1 1 1 0
0 1 1 0 0
0 1 0 0 0
0 0 0 0 0
the max rectangle contains all black (1) is the rectangle from (1,1) - (3, 3)
'''
#leetcode maximal rectangle 用histogram来做 |
# encoding=utf-8
'''
Given a circle with N defined points and a point M outside the circle, find the point that is closest to M among the set of N. O(LogN)
'''
#我们就先假定是sorted的吧。
#
'''
Assuming that the points on the circumference of the circle are "in-order" (i.e. sorted by angle about the circle's center) you could use an angle-based binary search, which should achieve the O(log(n)) bounds.
Calculate the angle A from the point M to the center of the circle - O(1).
Use binary search to find the point I on the circumference with largest angle less than A - O(log(n)).
Since circles are convex the closest point to M is either I or I+1. Calculate distance to both and take the minimum - O(1).
'''
# 就是比较的时候,用角度比较。 寻找最接近的。 然后。 return min (arr[i], arr[i+1])
#大概是这样子做。 具体还得看具体的order的情况
class Solution:
def orient(self, p, q, r):
c = self.cross(p, q, r)
if c==0: return 0
elif c>1: return 1
else: return -1
def cross(self, a, b, c):
ab = [b[0]-a[0], b[1]-a[1]]
ac = [c[0]-a[0], c[1]-a[1]]
return ab[0]*ac[1]-ab[1]*ac[0]
def search(self, x, arr):
zero = (0, 0)
l=0; h = len(arr)-1
while l<=h:
m = (l+h)/2
c = self.orient(zero, x, arr[m])
if c==0: return arr[m]
elif c>0: l=m+1
else: h=m-1
# calculate distance of both |
# encoding=utf-8
import math
'''
0x for hexadecimal, 0 for octal and 0b for binary
Find n’th number in a number system with only 3 and 4
Given a number system with only 3 and 4. Find the nth number in the number system. First few numbers in the number system are: 3, 4, 33, 34, 43, 44, 333, 334, 343, 344, 433, 434, 443, 444, 3333, 3334, 3343, 3344, 3433, 3434, 3443, 3444, …
0, 1, 00, 01, 10, 11, 000, 001, 010, .......
但是不是二进制计数。 而是某种二进制排列。
例子
14
14 最大为8
14-8 = 6
结果为第七个数。 也就是111
'''
# 和上面拿到题目一样的 An Interesting Method to Generate Binary Numbers from 1 to n
class Solution:
def biNumbers(self, n):
ret = ['3', '4']; pre=ret[:]
k = int(math.log(n, 2))
for i in range(k):
cur = []
for j in pre:
cur.append(j+'3')
cur.append(j+'4')
ret+=cur
pre = cur
return ret[n-1]
s = Solution()
print s.biNumbers(14)
print s.biNumbers(5)
'''
#2+4+8+16
# log(n) 取决于二进制的位数
class Solution:
def find(self, n): #转换为二进制来做就好。
r = n-2**(int(math.log(n, 2))) #转换为二进制来做就好。
t= list(bin(r+1)[2:]) # math.log(n,2 ) 与 math.log(n, 2)写法一样。
return ''.join([chr(ord(ch)+3) for ch in t])
s = Solution()
print s.find(14)
print s.find(5)
print s.find(8)
以前的方法:
class Solution:
def find(self, n): #转换为二进制来做就好。
divider =2**(int(math.log(n, 2))) # math.log(n,2 ) 与 math.log(n, 2)写法一样。
remain = n%divider #转换为二进制来做就好。
t= list(bin(remain+1)[2:])
return ''.join([chr(ord(ch)+3) for ch in t])
''' |
# encoding=utf-8
# 如何判断一棵二叉树实际上是一个链表
#但面试完发现只要保证每个节点都只有一个子嗣即可,否则返回非 不需要遍历所有元素
class Solution:
def solve(self, root):
while root:
if root.left and root.right: return False
elif root.left: root=root.left
elif root.right: root=root.right
else: break
return True
|
# encoding=utf-8
'''
Given the relative positions (S, W, N, E, SW, NW, SE, NE) of some pairs of points on a 2D plane, determine whether it is possible. No two points have the same coordinates.
e.g., if the input is "p1 SE p2, p2 SE p3, p3 SE p1", output "impossible".
'''
# build 2 graphs。 x, cooridinates. y coordinates
'''
One idea, not sure whether this is correct..
Construct two graphs, one for x-coordinate--Gx, one for y-coordinate--Gy.
For Gx, If x1 < x2, then we have an edge from x1->x2, if x1 > x2, one edge x1<-x2. If x1 == x2, combine x1 and x2 together.
Similarly for Gy.
In the end, we check whether there exists a cycle in Gx or Gy. If this is true, then the answer is impossible.
For example, p1 SE p2, we have x1 > x2 and y1 < y2.
Gx: x1 <-- x2 Gy: y1 -->y2
p2 SE p3, we have x2 > x3 and y2 < y3.
Gx: x1 <-- x2 <-- x3 Gy: y1 -->y2 -->y3
p3 SE p1, we have x3 > x1 and y3 < y1
In Gx, we have a cycle from x1 <-- x2 <-- x3 <-- x1. So it is impossible.
''' |
# encoding=utf-8
'''
意思是swap子树。
Swap 2 nodes in a Binary tree.(May or Maynot be a BST)
Swap the nodes NOT just their values.
(preferably in Java please..(My requirement not theirs :p))
ex:
5
/ \
3 7
/ \ /
2 4 6
swap 7 and 3
5
/ \
7 3
/ / \
6 2 4
'''
#注意跟面试官clear 一个是另一个parent的情况
#level order traversal
class Solution:
def swap2(self, n1, n2, root):
if n1==root or n2==root: return False
if not n1 or not n2: return False
pre, ret = [root], [] # 除了pre, cur之外,还用了第三个vals
p1=p2=None;
while pre and (not p1 or not p2):
cur = [] #必须用array。 因为是有序的。 并且不会有重复
for n in pre:
if n1 in (n.left, n.right): p1 = n
if n2 in (n.left, n.right): p2=n
if n.left: cur.append(n.left)
if n.right: cur.append(n.right)
pre = cur
if not p1 or not p2: return False
if p1.left ==n1: p1.left = n2
else: p1.right = n2
if p2.left == n2: p2.left =n1
else: p2.right = n1 |
# encoding=utf-8
'''
Following is a simple algorithm to find out whether a given graph is Birpartite or not using Breadth First Search (BFS).
1. Assign RED color to the source vertex (putting into set U).
2. Color all the neighbors with BLUE color (putting into set V).
3. Color all neighbor’s neighbor with RED color (putting into set U).
4. This way, assign color to all vertices such that it satisfies all the constraints of m way coloring problem where m = 2.
5. While assigning colors, if we find a neighbor which is colored with same color as current vertex, then the graph cannot be colored with 2 vertices (or graph is not Bipartite)
'''
#思想就是所有node和它的邻居颜色必须不同
class Solution:
def isBiparty(self, graph, src):
colors = {src: False}
pre = [src]
while pre:
cur = []
for x in pre:
for y in x.neighbors:
if y not in colors:
colors[y] = not colors[x]
cur.append(y)
else:
if colors[y] == colors[x]: return False
pre = cur
return True
'''
#graph。 BFS都是用一个hashmap代替visited。 然后
for n in pre:
for n in x.neigbors.
if not in map
''' |
# encoding=utf-8
'''
What is the difference between a computers heap and it's stack?
'''
#看看下面这个stack overflow就理解了.
'''
You can cause a stack overflow quite easily in python, as in any other language, by building an infinately recursive funcion. This is easier in python as it doesn't actually have to do anything at all other than be recursive.
>>> def foo():
... return foo()
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
.......
File "<stdin>", line 2, in foo
RuntimeError: maximum recursion depth exceeded
>>>
As for the heap, that is managed by a garbage collector. You can allocate lots of objects and eventually run out of heap space and Python will raise a MemoryError, but it's going to take a fair amount of time. You actually did that with your 'stack overflow' example in the question. You stored a reference to a string on the stack, this string took up all the free memory available to the process. As a rule of thumb, Python stores a reference to a heap structure on the stack for any value that it can't guarantee the size of.
Physically stack and heap both are allocated on RAM and their implementation varies from language, compiler and run time
Stack is used for local variables of functions and to track function calling sequences. (考虑recursion无限循环 ,用的stack)
Heap is used for allocating dynamically created variables using malloc, calloc or new.
Stack memory is freed whenever the function completes execution.
but the heap memory needs to be freed explicitly using delete, free or by garbage collector of the language.
Stack memory of a process is fixed size and
heap is variable memory.
Stack is faster than heap as allocating memory on stack is simpler just moving stack pointer up.
In case of multi threading, each thread of process will have a different stack but all threads share single heap
''' |
# encoding=utf-8
'''
Given an array A of N integers, we draw N discs in a 2D plane such that the I-th disc is centered on (0,I) and has a radius of A[I]. We say that the J-th disc and K-th disc intersect if J ≠ K and J-th and K-th discs have at least one common point.
Write a function:
int number_of_disc_intersections(int A[], int N);
that, given an array A describing N discs as explained above, returns the number of pairs of intersecting discs. For example, given N=6 and:
A[0] = 1 A[1] = 5 A[2] = 2
A[3] = 1 A[4] = 4 A[5] = 0
intersecting discs appear in eleven pairs of elements:
0 and 1,
0 and 2,
0 and 4,
1 and 2,
1 and 3,
1 and 4,
1 and 5,
2 and 3,
2 and 4,
3 and 4,
4 and 5.
so the function should return 11.
The function should return −1 if the number of intersecting pairs exceeds 10,000,000.
Assume that:
N is an integer within the range [0..10,000,000];
each element of array A is an integer within the range [0..2147483647].
Complexity:
expected worst-case time complexity is O(N*log(N));
expected worst-case space complexity is O(N), beyond input storage (not counting the storage required for input arguments).
Elements of input arrays can be modified.
'''
'''
rearrange them in the format of interval: [-1,1] [-4,6] ...
then the problem becomes checking overlapping intervals.
just sort them on the base of starting point and binary search each end point in the sorted list
'''
class Solution:
def findNumConference(self, intervals): #假设每个都是tuple
affairs = []; d={x:0 for x in affairs}
for i in intervals:
affairs+=[ (i[0], 1, i), (i[1], -1, i)]
affairs.sort()
sCnt = 0; eCnt=0
for x in affairs:
if x[1]==1:
sCnt+=1; d[x[-1]]=-eCnt
elif x[1]==-1:
eCnt+=1; d[x[-1]]+=sCnt-1 #不包括自己。-1.
return sum(d.values())/2 #end
'''
def bsearch(self, start, x, arr): #start的数目就是i了。 end的数目就是binary search了。
l =start; h=len(arr)-1
while h>l: #float型的binary search。 可以把accuracy提前到前面。 少了一行
if h-l==1: break
m =(l+h)/2
if arr[m]>x: h = m
else: l=m
return int(l-start)
'''
s = Solution()
print s.cnt([1, 5, 2 ,1 ,4 ,0]) |
# encoding=utf-8
'''
flatten array
'''
class Solution:
def flatten(self, arr):
ret = []
for i in arr:
if isinstance(i, list): ret+=self.flatten(i)
else: ret.append(i)
return ret
s = Solution()
print s.flatten( [ [1,2], [3,[4,5]], 6]) |
# encoding=utf-8
'''
Given a string of digits, find the minimum number of additions required for the string to equal some target number. Each addition is the equivalent of inserting a plus sign somewhere into the string of digits. After all plus signs are inserted, evaluate the sum as usual. For example, consider the string "12" (quotes for clarity). With zero additions, we can achieve the number 12. If we insert one plus sign into the string, we get "1+2", which evaluates to 3. So, in that case, given "12", a minimum of 1 addition is required to get the number 3.
'''
#没想到好办法。 暴力吧。
class Solution:
def solve(self, s, target): # 2**n 相当于recursion
self.ret = len(s)+10
self.dfs(s, target, 0, '')
return self.ret
def dfs(self, s, target, cnt, pre):
if cnt>self.ret or target<0: return
if not s:
if target ==0 and not pre: self.ret = min(self.ret, cnt-1)
return
if not s or target<0: return
self.dfs(s[1:], target, cnt, pre+s[0]) #举例 123. 1+23, 12+3 , 1+2+3, 123
self.dfs(s[1:], target-int(pre+s[0]), cnt+1, '')
s = Solution()
print s.solve('12', 3)
print s.solve('123', 6)
'''
class Solution:
def solve(self, s, target): # 2**n 相当于recursion
n = len(s); ret = n+10
for i in range(2**(n-1)):
cur =s= cnt=0
for j in range(n):
cur = cur*10+int(s[j]) #1<<j作用是, 在第k位设置一个set bit
if (1<<j) & i:
s+=cur; cnt+=1; cur=0
s+=cur #最后再加一次
if s==target: ret = min(ret, cnt)
if ret==n+10: return -1
return ret
s = Solution()
print s.solve('12', 3)
''' |
# encoding=utf-8
'''
check whether a given binary tree is complete or not
Given a Binary Tree, write a function to check whether the given Binary Tree is Complete Binary Tree or not.
A complete binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible. See following examples.
The following trees are examples of Complete Binary Trees
1
/ \
2 3
1
/ \
2 3
/
4
1
/ \
2 3
/ \ /
4 5 6
The following trees are examples of Non-Complete Binary Trees
1
\
3
1
/ \
2 3
\ / \
4 5 6
1
/ \
2 3
/ \
4 5
基本上就是level order
BFS
注意看不通过的定义。 也有很多说complete就是满地意思。
就是加上一个flag。表示不能再有leave了. 然后不需要ret。也不需要vals了,
'''
class Solution:
def isComplete(self, root):
if not root: raise ValueError
prev = [root]; stop = False # #if f==True, means we can not meet any more leaves.
while prev:
cur = []
for node in prev:
if node.left:
cur.append(node.left) # once a node is found which is NOT a Full Node, all the following nodes must be leaf nodes.
if stop: return False
else: stop = True
if node.right:
cur.append(node.right)
if stop: return False
else: stop = True
prev = cur
return True
'''
Given a Binary tree,find the level at which the tree is complete.
Complete Binary tree-All leaves should be at same level and every internal node should have two children.
Asked to write both Recursive and iterative code.
'''
#误以为是 Minimum Depth of Binary Tree, 结果差很多。 那个是任意tree, 求最浅的叶子。
class Solution6:
def checkLevel(self, root):
return self.dfs(root, 0)
def dfs(self, root, lvl):
if not root: return lvl
return min(self.dfs(root.left, lvl+1), self.dfs(root.right, lvl+1))
'''
class Solution6:
def checkLevel(self, root):
return self.dfs(root, 0)
def dfs(self, root, lvl):
if not root: return lvl
if root.left and root.right: return min(self.dfs(root.left, lvl+1), self.dfs(root.right, lvl+1))
return lvl+1 #加上root这一层. 若
''' |
# encoding=utf-8
'''
there are N nuts and N bolts, all unique pairs of Nuts and Bolts. You cant compare Nut with Nut and a Bolt with Bolt. Now ,how would you figure out matching pairs of nut and bolt from the given N Nuts and Bolts.
'''
'''
方法就是类似快排,随便找一个螺母a,用它把所有螺栓分成小于a、大于a和等于a(只有一个)。再用那个等于a的螺栓把所有螺母也划分一遍。于是就得到了一对匹配和“大于a的螺母螺栓”、“小于a的螺母螺栓”两部分,递归处理。复杂度和随机选取pivot的快排的复杂度一样。
'''
#code很难写。 懒得写了。
#G家面经也有这道题目
# encoding=utf-8
'''
# encoding=utf-8
import random
class Solution:
def partition(self, v, pv, start, end):
p = v[start:end].index(pv) + start
v[p], v[end-1] = v[end-1], v[p] #pivot存到最后......
evict_idx = i =start
while i<end:
if v[i] < pv:
v[evict_idx], v[i] = v[i], v[evict_idx]
evict_idx+=1
i+=1
v[evict_idx], v[end-1] = v[end-1], v[evict_idx]
return evict_idx
def qSort(self, bolts, nuts, start, end):
if end-start>1:
a_bolt = random.choice(bolts[start: end])
a_nut_idx = self.partition(nuts, a_bolt, start, end) #这是与标准的不同。 拷贝了2次
a_nut = nuts[a_nut_idx]
a_bolt_idx =self.partition(bolts, a_nut, start, end)
self.qSort(bolts, nuts, start, a_bolt_idx)
self.qSort(bolts, nuts, a_bolt_idx+1, end)
random.seed(1)
N = 10
b = [ random.randint(1,20) for _ in range(N) ]
n = b[:]
random.shuffle(n)
print("b = ", b)
print("n = ", n)
s = Solution()
s.qSort(b,n, 0, N)
print("b = ", b)
print("n = ", n)
'''
#我还是适合简单版本
import random
def quickSort(arr1, arr2):
assert len(arr1)==len(arr2)
if len(arr1) <=1: return arr1, arr2
pivot = random.choice(arr1)
s2, m2, b2 = partition(arr2, pivot)
assert m2!=[]
pivot = m2[0]
s1, m1, b1 = partition(arr1, pivot)
s1, s2 = quickSort(s1, s2)
b1, b2 = quickSort(b1, b2)
return s1+m1+b1, s2+m2+b2
def partition(arr, pivot):
s = [i for i in arr if i < pivot]
m = [ i for i in arr if i== pivot]
b = [i for i in arr if i>pivot]
return s, m, b
N = 10
b = [ random.randint(1,20) for _ in range(N) ]
n = b[:]
random.shuffle(n)
print b, n
print quickSort(b, n) |
# encoding=utf-8
'''
Find the seed of a number.
Eg : 1716 = 143*1*4*3 =1716 so 143 is the seed of 1716. find all possible seed for a given number.
'''
#暴力法
class Solution:
def findseed(self, x):
results = []
for n in range(x):
a = [int(i) for i in list(str(n))]
product = n
for i in a: product*=i
if product==x: results.append(n)
return results
s = Solution()
print s.findseed(1716)
print s.findseed(64)
|
# encoding=utf-8
'''
A soda water machine,press button A can generate 300-310ml, button B can generate 400-420ml and button C can generate 500-515ml, then given a number range [min, max], tell if all the numbers of water in the range can be generated.
'''
#很特别的dp
class Solution:
def generate(self, minV, maxV):
canGen=set(range(300, 311)+range(400, 421)+range(500, 516))
for i in range(maxV+1): # i从0开始的。
if i not in canGen:
for j in canGen:
if i-j in canGen:
canGen.add(i); break
return all(x in canGen for x in range(minV, maxV))
s = Solution()
print s.generate(700, 721)
'''
class Solution:
def generate(self, minV, maxV):
dp = [False ] *(maxV+1)
for i in range(300, 516):
if 300<=i<=310 or 400<=i<=420 or 500<=i<=515: dp[i] = True
for i in range(516, maxV+1):
if not dp[i]:
for j in range(300, 311):
if dp[i-j]:
dp[i] = True; break
if not dp[i]:
for j in range(400, 421):
if dp[i-j]:
dp[i] = True; break
if not dp[i]:
for j in range(500, 516):
if dp[i-j]:
dp[i] = True; break
return False not in [x for x in dp[minV:maxV+1]]
'''
|
# encoding=utf-8
'''
Given a very very very large integer(with 1 million digits, say), how would you convert this integer to an ASCII string
'''
# linked list
'''
It's like :
input - 12345678........8798989887873124234....(1 million digits)
output - "12345678............8798989887873124234...."
basically an itoa() kinda function but here the input is a very
very large integer
'''
'''
I think doing % and / is not the correct approach to this, the algorithm basically work, but if we consider a number with millions of digits, the datatype should be some sort of linked list containing a single digit peer bucket, in that way the "big" number can grow to million digits, so in my opinion the correct way should be visit from back to beginning the linked list an put each digit into a string buffer then return it.
'''
|
# encoding=utf-8
'''
Colorful Number:
A number can be broken into different sub-sequence parts. Suppose, a number 3245 can be broken into parts like 3 2 4 5 32 24 45 324 245. And this number is a colorful number, since product of every digit of a sub-sequence are different. That is, 3 2 4 5 (3*2)=6 (2*4)=8 (4*5)=20 (3*2*4)= 24 (2*4*5)= 40
But 326 is not a colorful number as it generates 3 2 6 (3*2)=6 (2*6)=12.
You have to write a function that tells if the given number is a colorful number or not.
'''
# subarray, subsequence
#其实题目意思是subarray。 。。。
class Solution:
def isColorFul(self, num):
if num<10: return True
candidates = [int(i) for i in sorted(list(str(num)))]
if 0 in candidates or 1 in candidates or len(candidates)>=9 or len(candidates)!=len(set(candidates)): return False
self.result = []
self.dfs(1, candidates) #1开始,逐个相乘
p = self.result[1:]
return len(p) == len(set(p)) #shizhi
def dfs(self, cur, candidates):
self.result.append(cur)
for i in range(len(candidates)):
self.dfs(cur*candidates[i], candidates[i+1:])
s = Solution()
print s.isColorFul(3245) |
# encoding=utf-8
'''
Print Nodes in Top View of Binary Tree
Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes can be printed in any order. Expected time complexity is O(n)
A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance of a child of a node x is equal to horizontal distance of x minus 1, and that of right child is horizontal distance of x plus 1.
1
/ \
2 3
/ \ / \
4 5 6 7
简单的说,就是column形式的view。每个colum取顶端一个。
Top view of the above binary tree is
4 2 1 3 7
1
/ \
2 3
\
4
\
5
\
6
Top view of the above binary tree is
2 1 3 6
基本上和vertical columns一模一样。
'''
#hashmap值同时也存lvl的值
# top view是最难的。 同时要rlvl, clvl
class Solution:
def findVertical(self, root):
self.d = {} #用hashtable是因为不知道最左边index有多左。
self.dfs(root, 0, 0)
return [min(self.d[x])[-1] for x in sorted(self.d)]
def dfs(self, root, r, c):
if not root: return
if c not in self.d: self.d[c] = []
self.d[c].append((r, root.val))
self.dfs(root.left, r + 1, c - 1)
self.dfs(root.right, r + 1, c + 1)
'''
class Solution:
def findVertical(self, root):
self.d = {} #用hashtable是因为不知道最左边index有多左。
self.dfs(root, 0, 0)
result = []
for key in sorted(self.d):
top = min(self.d[key])
result.append(top[-1])
return result
def dfs(self, root, rlvl, clvl):
if not root: return
if clvl not in self.d: self.d[clvl] = []
self.d[clvl].append((rlvl, root.val))
self.dfs(root.left,rlvl+1, clvl-1)
self.dfs(root.right, rlvl+1, clvl+1)
'''
'''
geeks的做法时间复杂度比较高。
我这个耗费空间。
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
t1 = TreeNode(1)
t2 = TreeNode(2)
t3 = TreeNode(3)
t4 = TreeNode(4)
t5 = TreeNode(5)
t6 = TreeNode(6)
t1.left = t2
t1.right = t3
t2.right = t4
t4.right = t5
t5.right = t6
s = Solution()
print s.findVertical(t1) |
# encoding=utf-8
'''
Write a method to determine if two strings are anagrams of each other.
e.g. isAnagram(“secure”, “rescue”) → false
e.g. isAnagram(“conifers”, “fir cones”) → true
e.g. isAnagram(“google”, “facebook”) → false
'''
# O(n)
# 也可以keep an asicii array of 256. 不过一般都可以用hashtable替代。 尽量用hashtable
class Solution:
def isAnagram(self, s1, s2):
d1= self.cnt(s1)
d2 = self.cnt(s2)
if len(d1)!=len(d2): return False #注意检查长度
for ch in d1:
if ch not in d2 or d2[ch]!=d1: return False
return True
def cnt(self, s):
d={}
for ch in s:
if ch ==' ': continue #忽略空格
if ch not in d: d[ch]=0
d[ch]+=1
return d |
# encoding=utf-8
'''
Merge k sorted arrays | Set 1
Given k sorted arrays of size n each, merge them and print the sorted output.
Example:
Input:
k = 3, n = 4
arr[][] = { {1, 3, 5, 7},
{2, 4, 6, 8},
{0, 9, 10, 11}} ;
Output: 0 1 2 3 4 5 6 7 8 9 10 11
A simple solution is to create an output array of size n*k and one by one copy all arrays to it. Finally, sort the output array using any O(nLogn) sorting algorithm. This approach takes O(nkLognk) time.
类似leetcode那道题。 用merge sort. nklog(k).
Recursive Algo:
void mergeK(int a[][MAX],int low,int high,int n){
1: if(low>=high)
return;
2 : int mid=(low+high)/2;
3: mergeK(a,low,mid,n);
4 : mergeK(a,mid+1,high,n);
// now merge two sorted array a[low][n] to a[high][n]
5 : merge(arr, low*n, (mid+1)*n ,(mid+1)*n, (high+1)*n);
}
变体是这个n=k的情况。 类似的。
Print all elements in sorted order from row and column wise sorted matrix
Given an n x n matrix, where every row and column is sorted in non-decreasing order. Print all elements of matrix in sorted order.
Example:
Input: mat[][] = { {10, 20, 30, 40},
{15, 25, 35, 45},
{27, 29, 37, 48},
{32, 33, 39, 50},
};
Output:
Elements of matrix in sorted order
10 15 20 25 27 29 30 32 33 35 37 39 40 45 48 50
'''
import heapq
#heap和merge 复杂度一样。 但是heap代码只有8行。 merge代码要三倍
#三元tuple。存了本身array的位置,以及目前array的pointer。
class Solution:
# @param a list of ListNode
# @return a ListNode
def mergeKLists(self, arrs):
h =[(arrs[i][0], i, 0) for i in range(len(arrs)) if arrs[i]]
heapq.heapify(h); ret = []
while h:
val, i, j = heapq.heappop(h)
ret.append(val); j+=1
if j<len(arrs[i]): heapq.heappush(h, (arrs[i][j], i, j))
return ret #复杂度 O(nkLogk) 是最优解. 暴力法是nk log(nk)
#好处是代码特别短。7行
# 稍微注意while里边的三行就可以=
#和heap和merge sort复杂度一样
'''
class Solution:
def mergeK(self, matrix):
if len(matrix)<=1: return matrix
while len(matrix)>1:
newLists = []
for i in range(0, len(matrix)-1, 2):
newLists.append(self.merge2(matrix[i], matrix[i+1]))
if len(matrix)%2==1: newLists.append(matrix[-1])
matrix = newLists
return matrix[0]
def merge2(self, part1, part2):
result = []
i=j=0
while i<len(part1) and j<len(part2):
if part1[i]<part2[j]:
result.append(part1[i])
i+=1
else:
result.append(part2[j])
j+=1
if i<len(part1): result+=part1[i:]
if j<len(part2):result+=part2[j:]
return result
s = Solution()
print s.mergeK([[1, 3, 5], [2, 4, 9], [3, 4, 5]])
'''
s = Solution()
print s.mergeKLists([[1, 3, 5], [2, 4, 9], [3, 4, 5]]) |
# encoding=utf-8
'''
Microsoft Excel numbers cells as 1...26 and after that AA, AB.... AAA, AAB...ZZZ and so on.
Given a number, convert it to that format and vice versa.
A-Z: 26
AA- ZZ: 后面的26*26
AAA-ZZZ: 后面的26*26*26
'''
#就是十进制与26进制转换。 变成了26进制计数。
class Solution:
def toStr(self, n):
out = ''
while n>0:
n-=1
d, n = n%26, n/26 #因为以1为base。 每次减去1
out = chr(ord('A')+d)+out #因为我们总是先解决低位的。 所以最后取反
return out
def toNum(self, s):
cur = 0 #有点像subset那种iteration. 不断改变自身的recursion
for ch in s: #每增加一位。 可能性*6
cur = cur*26 + ord(ch)-ord('A') + 1
return cur
s = Solution()
arr = [1, 26, 27, 53, 30, 131, 1111]
for i in arr:
tmp = s.toStr(i)
print str(i) +' convert to: '+ s.toStr(i)
print str(i) +' convert to: '+ str( s.toNum(tmp))
'''
转化成任意的x进制:
不断while n
n, d = n/x, d%x
''' |
# encoding=utf-8
'''
There are 10,000 balls and may be 500 different colors of ball
Example: There are:
4 - red ball
5900 - Blue ball
3700 - Green ball
396 - mintcream ball
Or there may be 10,000 red balls.
Or all balls are has same range, i.e. 500 red, 500 blue, etc.
We don’t know the range of any ball and number of color balls, but the minimum is 1 color and maximum is 500 colors, and we have auxiliary array of size 500. how to arrange all same color ball together in minimum passes over balls? is it possible to do in less than two passes ??
'''
'''
arr[500]
for ball in balls:
aux_array[ball.color].append(ball)
''' |
# encoding=utf-8
'''
给个Binary Search Tree. 中间有很多重复的数字(你没看错,就是有重复的)。要求找到出现次数最多的那个数字。现场coding的话关键注意点在如何inorder遍历的同时刷新max。此外如果max是最后的一组数是个边界条件。
'''
class Solution4:
def findSucPre(self, root):
self.pre = None; self.cnt=0
self.ret = (0, None)
self.dfs(root)
return self.ret
def dfs(self, root):
if not root: return
self.dfs(root.left)
if self.pre!=None and root.val==self.pre:
self.cnt+=1
else: self.cnt=1
self.ret = max(self.ret, (self.cnt, root))
self.pre=root.val
self.dfs(root.right) |
# encoding=utf-8
'''
Asked by SG
Given an array in which all numbers except two are repeated once. (i.e. we have 2n+2 numbers and n numbers are occurring twice and remaining two have occurred once). Find those two numbers in the most efficient way.
第一想法用hash。 用 extra space. but efficient
XOR of two different numbers x and y results in a number which contains set bits at the places where x and y differ. So if x and y are 10...0100 and 11...1001, then result would be 01...1101.
So the idea is to XOR all the elements in set. In the result xor, all repeating elements would nullify each other. The result would contain the set bits where two non-repeating elements differ.
Now, if we take any set bit of the result xor and again do XOR of the subset where that particular bit is set, we get the one non-repeating element. And for other non-repeating element we can take the subset where that particular bit is not set.
We have chosen the rightmost set bit of the xor as it is easy to find out.
第一道题,是说你知道(n&(n-1))得出什么结果吗?
“n&(n-1)”改变最后一位digit 是1得. 最后一个set bit 设置为0
举个例子就好。 3&(3-1)
'''
class Solution:
def get2NonRepeatingNos(self, arr):
xor = 0
for x in arr: xor ^= x # 完成后, x^y = xor
bit = xor & ~(xor-1) #Get the rightmost set bit in set_bit_no.
a = b =0
for x in arr:
if bit & x: a ^=x
else: b ^=x
return a, b
s = Solution()
print s.get2NonRepeatingNos([2, 3, 7, 9, 11, 2, 3, 11])
#和这道题目重复: Find the two numbers with odd occurrences in an unsorted array
# leetcode single number 变体 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.