text
stringlengths 37
1.41M
|
---|
import pandas as pd
import numpy as np
import os
from pprint import pprint
from sklearn.cluster import KMeans
import csv
"""
Reads the data from CSV files, each attribute column can be obtained via its name
:param filePath: the file path of the input data frame
:type filePath: str
:returns: return the dataframe after read the data from the .csv file
:rtype: pandas.DataFrame
"""
def getDataframe(filePath):
data = pd.read_csv(filePath)
return data
"""
Perform the K-means algorithm to cluster the data.
:param filePath: the file path of the input data frame
:param numClusters: number of clusters, which is a hyper-parameter for K-means algorithm.
:param output: whether we will result the result
:type filePath: str
:type numClusters: int
:type outfilename: str
:returns kmeans: return the Kk-means model after we fit the data from the filePath
:rtype kmeans: sklearn.cluster.KMeans
"""
def cluster_by_category(filePath, numClusters, output):
categories = getDataframe(filePath)
X = categories.drop('index', axis=1)
i = categories['index']
kmeans = KMeans(n_clusters=numClusters, random_state=0)
kmeans.fit(X)
if output is True:
n = categories.shape[0]
output = np.zeros((n,2))
output[:,0] = i
output[:,1] = kmeans.labels_
path = os.path.dirname(os.getcwd())
if not os.path.exists(path + "/Data/After Processing"):
os.makedirs(path + "/Data/After Processing")
np.savetxt(path + '/Data/After Processing/clustered_by_category.csv', output, delimiter = ',', newline = '\n')
return kmeans
path = os.path.dirname(os.getcwd())
file = r'/Data/business_categories.csv'
numClusters = 8
cluster_by_category(path + file, numClusters, True) |
import pandas as pd
import numpy as np
import sys
import os
from pprint import pprint
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
import csv
"""
Reads the data from CSV files, each attribute column can be obtained via its name
:param filePath: the file path of the input data frame
:type filePath: str
:returns: return the dataframe after read the data from the .csv file
:rtype: pandas.DataFrame
"""
def getDataframe(filePath):
data = pd.read_csv(filePath)
return data
"""
Perform the PCA, fit the PCA based on the dataframe from "filePath" and perform the transformation to that dataframe, write
the result to the "outfilename" if needed
:param filePath: the file path of the input data frame
:param limitComponents: determine whether there is a limiation on the components we selected after PCA; if no, we just selected every
components after the PCA
:param numComponents: the number of components we selected after the PCA
:param output: whether we will result the result
:param outfilename: the place where we will write the data after PCA transformation
:type filePath: str
:type limitComponents: bool
:type numComponents: int
:type output: bool
:type outfilename: str
:returns pca: return the PCA model after we fit the data from the filePath
:returns standard_scaler: return the standard scaler after we fit the data from the filePath
:rtype pca: sklearn.decomposition.PCA
:rtype standard_scaler: sklearn.preprocessing.StandardScaler
"""
def perform_PCA(filePath, limitComponents, numComponents, output, outfilename):
data = getDataframe(filePath)
y = data['stars_review']
X = data.drop('stars_review', axis=1)
standard_scaler = StandardScaler()
standard_scaler.fit(X)
X = standard_scaler.transform(X)
if limitComponents is True:
pca = PCA(n_components=numComponents).fit(X)
else:
pca = PCA().fit(X)
if output is True:
n = data.shape[0]
m = pca.components_.shape[0] + 1
output = np.zeros((n,m))
output[ : , 0] = y
output[ : , 1 :] = pca.transform(X)
np.savetxt(outfilename, output, delimiter = ',', newline = '\n')
print(pca.explained_variance_ratio_.cumsum()) #Print the variance contribution (cumulatively) for each components
return pca, standard_scaler
"""
Perform the normalization transforamtion and PCA transformation based on already fitted model. Perform the PCA tranforamtion
on the dataframe from "filePath" and write the result to the "outfilename"
:param filePath: the file path of the input data frame
:param pca: the already fitted PCA model, which we can use to transforma the data
:param standard_scaler: the already fitted scaler, which we can use to transforma the data
:param outfilename: the place where we will write the data after PCA transformation
:type filePath: str
:type pca: sklearn.decomposition.PCA
:type standard_scaler: sklearn.preprocessing.StandardScaler
:type outfilename: str
"""
def transform_PCA(filePath, pca, standard_scaler, outfilename):
data = getDataframe(filePath)
y = data['stars_review']
X = data.drop('stars_review', axis=1)
X = standard_scaler.transform(X)
n = data.shape[0]
m = pca.components_.shape[0] + 1
output = np.zeros((n,m))
output[ : , 0] = y
output[ : , 1 :] = pca.transform(X)
np.savetxt(outfilename, output, delimiter = ',', newline = '\n')
path = os.path.dirname(os.getcwd())
if not os.path.exists(path + "/Data/After Processing"):
os.makedirs(path + "/Data/After Processing")
#Please customize this by changing the input and output path location
join_train_queries = path + r'/Data/After Processing/join_train_queries.csv'
train_queries_pca = path + r'/Data/After Processing/train_queries_pca.csv'
#Please customize this by changing the input and output path location
join_validate_queries = path + r'/Data/After Processing/join_validate_queries.csv'
validate_queries_pca = path + r'/Data/After Processing/validate_queries_pca.csv'
pca_model, scalar = perform_PCA(join_train_queries, False, 0, True, train_queries_pca)
transform_PCA(join_validate_queries, pca_model, scalar, validate_queries_pca) |
# from PyPDF2 import PdfFileWriter,PdfFileReader
# pdf1=PdfFileReader(open("readme.pdf"))
# pdf2=PdfFileReader(open("readme.pdf"))
# writer = PdfFileWriter()
# # add the page to itself
# for i in range(0,pdf1.getNumPages()):
# writer.addPage(pdf1.getPage(i))
# # write to file
# with file("destination.pdf", "wb") as outfp:
# writer.write(outfp)
# from PyPDF2 import PdfFileWriter, PdfFileReader
# # a reader
# reader=PdfFileReader(open("readme.pdf",'rb'))
# # a writer
# writer=PdfFileWriter()
# outfp=open("sample.pdf",'wb')
# writer.write(outfp)
|
#Russian Peasants Algo
def Peasants (a,b):
x = a; y = b
z = 0
while x > 0:
#This timesing algorythm works by selecting if x is even, halving that, then doubling y. If x is odd, the value of y is added to z, y is doubled for the next iteration.
if x % 2 = 1: z = z + y
y = y << 1
x = x >> 1
return z
#Example of the sequence
#checking update.
"""
20, 7
x = 20, y = 7
z = 0
x > 0
x != odd
y = y * 2 (14)
x = 10
x != odd
y = 28
x = 5
x = odd
z = 0 + 28
y = 56
x = 2
x != odd
y = 112
x = 1
x = odd
z = 28 + 112
y = 224
x = 0
returns z = 140
20 * 7 = 140
"""
|
#Please remember to play here: http://www.codeskulptor.org/ - the simplegui library is not standard.
# implementation of card game - Memory
import simplegui
import random
HEIGHT = 100
WIDTH = 800
# helper function to initialize globals
def new_game():
global state, exposed, state, cards, card1, card2, moves
state = 0
cards = [(int % 8) for int in range(16)]
random.shuffle(cards)
exposed = [False]*16
card1 = -1
card2 = -1
moves = 0
# define event handlers
def mouseclick(pos):
global state, moves, card1, card2
DIndex = list(pos)[0]//50
if not exposed[DIndex]:
if state == 0:
card1 = DIndex
exposed[DIndex] = True
state = 1
elif state == 1:
card2 = DIndex
exposed[DIndex] = True
state = 2
else:
state = 1
if cards[card1] != cards[card2]:
exposed[card1] = False
exposed[card2] = False
exposed[DIndex] = True
card1 = DIndex
card2 = -1
moves += 1
# cards are logically 50x100 pixels in size
def draw(canvas):
for i in range(16):
if exposed[i]:
canvas.draw_polygon([[i*50, 0], [(i+1)*50, 0], [(i+1)*50, 100], [i*50, 100]], 1, "Black", "White")
canvas.draw_text(str(cards[i]), (i*50+11, 69), 55, "Black")
else:
canvas.draw_polygon([[i*50, 0], [(i+1)*50, 0], [(i+1)*50, 100], [i*50, 100]], 1, "Black", "Blue")
label.set_text("Turns = " + str(moves))
# create frame and add a button and labels
frame = simplegui.create_frame("Memory", 800, 100)
frame.add_button("Reset", new_game)
label = frame.add_label("Turns = 0")
# register event handlers
frame.set_mouseclick_handler(mouseclick)
frame.set_draw_handler(draw)
# get things rolling
new_game()
frame.start()
|
import urllib
website = raw_input("Enter website: ")
html = urllib.urlopen(website).read()
valid = urllib.urlopen(website).getcode()
print valid
if valid != 200:
print "This is not a valid page."
else:
print html[:3000]
count = len(html)
print count
|
import operator
class HighScoreManager:
"""
Class for handling a list of Highscore instances
"""
def __init__(self, data, poker=False):
self.heading = data.pop(0)
self.highscore_list = self.create_list(data)
self.poker = poker
def create_list(self, data):
"""
Creates instances of Highscore for each row in data
and appends them to the highscore_list
"""
list = []
for d in data:
list.append(Highscore(d[0], int(d[1]), int(d[2]), int(d[3]), float(d[4])))
return list
def sort_list(self, key_value):
"""
Sorts the list of highscore instances using the
key_value as key with operator.attrgetter
"""
self.highscore_list.sort(key=operator.attrgetter(key_value))
if not self.poker and key_value == 'item2':
pass # Mastmind score does not need to be reversed
else:
self.highscore_list.reverse()
def print_heading(self):
"""
Prints the heading formatted as a table
"""
print(f'{self.heading[0]}\t{self.heading[1]}\t{self.heading[2]}'\
f'\t{self.heading[3]}\t{self.heading[4]}\t')
def print_table(self):
"""
Prints header and the items in highscore_list
formatted as a table
"""
print()
self.print_heading()
for item in self.highscore_list:
print(item)
def show_best_five(self, poker):
"""
Shows the five best averages or win rates with
at least five rounds played
"""
best_five = []
self.sort_list('item4') # average/winrate is stored in item4
for highscore in self.highscore_list:
if highscore.item1 >= 5:
best_five.append(highscore)
if len(best_five) >= 5:
if poker:
# if its poker, the highest 5 values are the best
best_five = best_five[-5:]
else:
# if mastermind, the lowest 5 values are the best
best_five = best_five[:5]
print()
self.print_heading()
for score in best_five:
print(score)
def show_results_by_player(self, name):
"""
Method for displaying games made by a player
with the given name
"""
player_scores = []
for item in self.highscore_list:
if item.name == name:
player_scores.append(item)
print()
if not player_scores:
print('No player with that name has recorded a highscore')
else:
self.print_heading()
for item in player_scores:
print(item)
class Highscore:
"""
This class holds information about a highscore
converted from a worksheet table
"""
def __init__(self, name, item1, item2, item3, item4):
self.name = name
self.item1 = item1
self.item2 = item2
self.item3 = item3
self.item4 = item4
def __str__(self):
"""
Sets the default return value when print(highscore) is called
"""
return f'{self.name}\t{self.item1}\t\t{self.item2}'\
f'\t\t{self.item3}\t\t{self.item4}'
|
##Muataz Badr
## [email protected]
import re
## It seems like it was not necessary to create Multiple versions of the code as the REGEX call covers multiple aspects
## of the different questions asked and covers the bonus questions as well.
## odler versions are found at the end of the file.(EDITED)
# VERSION 2 , BONUS QUESTIONS (covers everything)
def Add(nums):
if not nums: ## An empty string acts like a false statement, which means it return False.
return print(0)
totalSum = 0
numsV2 = re.findall("[-]?[0-9]+",nums)
for x in numsV2:
# x = x.strip("\n") ## NOT necessary as the REGEX call strips the numbers for everything else.
if int(x) < 0:
negativeNums = [int(x) for x in numsV2 if int(x)<0]
raise Exception("Negative numbers are not allowed: {}".format(negativeNums))
if int(x) > 1000:
continue
totalSum += int(x)
return totalSum
#####################################################################
## Regression testing
test_add = [
{'inputs' : '//@\n1@3@4@2@5\n@7',
'outputs': 22,
'reason' : 'the function should accept new line characters'},
{'inputs' : '//@,$$,;\n1;3@5$$1001$$100\n;9000@1',
'outputs': 110,
'reason' : 'the function should accept multiple delimiters with arbitrary lengths'},
{'inputs' :'//@@@\n1@@@3@@@5@@@1001@@@100@@@9000@@@1',
'outputs': 110,
'reason' : 'the function should accept delimiters with arbitrary lengths'},
{'inputs' : '""',
'outputs': 0,
'reason' : 'It is an empty string'},
{'inputs' : "1\n,2\n,3\n,4,5",
'outputs': 15,
'reason' : 'function should accept new line characters'},
{'inputs' : "//;\n1\n;2001\n;3053\n;4634;1000",
'outputs': 1001,
'reason' : 'any number larger than a 1000 must not be added to the sum.'},
]
for t in test_add:
args_in = t['inputs']
expected = t['outputs']
# checking the results and our expectations
if Add(args_in) != expected:
print('Test add: Error in add(): expected SUM', expected,
' but found', Add(args_in), '--', t['reason'])
##testing for negative numbers seperately.
test_add_negative = [
{'inputs' : "1\n,2\n,3\n,4,-5, -3, 2, 1",
'outputs': 5},
{'inputs' : "-1\n,-2\n,-3\n,-4,-5",
'outputs': -15},
{'inputs' : "-1\n,-2\n,-3\n,-4,-5,5",
'outputs': -15}
]
for t in test_add_negative:
args_in = t['inputs']
expected = t['outputs']
# checking the results and our expectations
try:
if Add(args_in) == expected:
continue
except:
print("function is working, error for \n {",args_in,"} \n pops up as it contains negative numbers.")
print()
print()
#### OLDER VERSIONS OF THE CODE WITH SOME EDITS FOR REFERENCE
##VERSION 1 for question 1 and 2
# numbers = "1\n,2\n,3\n,4,5"
# def Add(nums):
# totalSum = 0
# numsSplitted = nums.split(",")
# print(numsSplitted)
# for x in numsSplitted:
# x = x.strip("\n")
# totalSum += int(x)
# print(x)
#
# print(totalSum)
#
# Add(numbers)
#VERSION 1.5 for question 1, 2 , 3 and 4
# ting2 = '//@\n1@3@4@2@5\n@7'
# def Add(nums):
# if not nums: ## An empty string acts like a false statement, which means it return False.
# return print(0)
#
# totalSum = 0
#
# numsV2 = re.findall("[-]?[0-9]+",nums)
#
# for x in numsV2:
# # x = x.strip("\n") ## NOT necessary as the REGEX call strips the numbers for everything else.
# if int(x) < 0:
# negativeNums = [int(x) for x in numsV2 if int(x)<0]
# raise Exception("Negative numbers are not allowed: {}".format(negativeNums))
# totalSum += int(x)
# print(totalSum)
#
# Add(ting2)
|
import sqlite3
import json
import math
class Pothole(object):
def __init__(self, creation_date, status, completion_date, response_time,\
service_num, current_activity, action, potholexblock, \
street, zip_num, ward, lat, lon, urgency_level, \
traffic_count, street_only):
'''
Creates an object representing a single pothole
'''
self.creation_date = creation_date
self.status = status
self.completion_date = completion_date
self.response_time = response_time
self.service_num = service_num
self.current_activity = current_activity
self.action = action
self.potholexblock = potholexblock
self.street = street
self.street_only = street_only
self.zip = zip_num
self.ward = ward
self.lat = lat
self.lon = lon
self.urgency_level = urgency_level
self.traffic_count = traffic_count
self.begin =int(creation_date[8:])
if self.completion_date != "":
self.end = int(completion_date[8:])
else:
self.end = 32
def distance_traffic(self, tlat, tlon):
'''
Finds the distance between the traffic object and
pothole object
Inputs:
tlat: latitude of traffic object
tlon: longitude of traffic object
Returns:
miles: distance in miles
Source: http://gis.stackexchange.com/a/56589/15183
Direct Copy
'''
# convert decimal degrees to radians
lon1, lat1, lon2, lat2 = map(math.radians, [self.lon, self.lat, tlon, tlat])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
c = 2 * math.asin(math.sqrt(a))
miles = 6367 * c*0.62137119
return miles
def __repr__(self):
return self.service_num
class Traffic(object):
def __init__(self, ID,count_location,street , \
total_passing_volume , volume_by_direction , \
latitude ,longitude):
'''
Creates an object representing a single traffic point
'''
self.id = int(ID)
self.count_location = count_location
self.total_passing_volume = int(total_passing_volume)
self.volume_by_direction = volume_by_direction
self.latitude = float(latitude)
self.longitude = float(longitude)
self.street = street
def __repr__(self):
return "The traffic on "+ self.count_location+ " " +\
self.street
class Alderman(object):
def __init__(self, name, email, ward):
self.email_address = str(email)
self.name = name
self.ward = ward
def email(self, message):
'''
Sends an email message to the Alderman
Inputs:
message: message of the email
'''
#### Direct Copy From Automate the Boring Stuff ####
##### https://automatetheboringstuff.com/chapter16/ ###
import smtplib
sender = '[email protected]'
receivers = self.email_address
smtpObj = smtplib.SMTP("smtp.mail.yahoo.com", 587)
smtpObj.ehlo()
smtpObj.starttls()
smtpObj.login('[email protected]', \
'shutyourpothole')
x = smtpObj.sendmail(sender,receivers,message)
smtpObj.quit()
def __repr__(self):
return "Alderman " + self.name
|
import sqlite3
sl_conn = sqlite3.connect('demo_data.sqlite3')
sl_cur = sl_conn.cursor()
# Creating table demo
table = """
CREATE TABLE demo(
s VARCHAR (10),
x INT,
y INT
);
"""
sl_cur.execute('DROP TABLE demo')
sl_cur.execute(table)
# Checking for table creation accuracy
sl_cur.execute('PRAGMA table_info(demo);').fetchall()
demo_insert = """
INSERT INTO demo (s, x, y)
VALUES ('g', 3, 9), ('v', 5, 7), ('f', 8, 7);
"""
sl_cur.execute(demo_insert)
sl_cur.close()
sl_conn.commit()
# Testing demo file
sl_conn = sqlite3.connect('demo_data.sqlite3')
sl_cur = sl_conn.cursor()
# Number of rows
sl_cur.execute('SELECT COUNT(*) FROM demo')
result = sl_cur.fetchall()
print(f'There are {result} rows.\n')
# How many rows are there where both x and y are at least 5?
sl_cur.execute("""
SELECT COUNT(*)
FROM demo
WHERE x >= 5
AND y >= 5;
""")
result = sl_cur.fetchall()
print(f'There are {result} rows with values of at least 5.\n')
# How many unique values of y are there?
sl_cur.execute("""
SELECT COUNT(DISTINCT y)
FROM demo
""")
result = sl_cur.fetchall()
print(f"There are {result} unique values of 'y'.")
# Closing connection and committing
sl_cur.close() |
"""
5. Activity Planner
The following information is stored in a personal activity planner:
Person: person_id, name, phone_number
Activity: activity_id, person_id - list, date, time, description
Create an application to:
1. Manage persons and activities. The user can add, remove, update, and list both persons and activities.
2. Add/remove activities. Each activity can be performed together with one or several other persons, who are already in the user’s planner. Activities must not overlap (user cannot have more than one activity at any given time).
3. Search for persons or activities. Persons can be searched for using name or phone number. Activities can be searched for using date/time or description. The search must work using case-insensitive, partial string matching, and must return all matching items.
4. Create statistics:
- Activities for a given date. List the activities for a given date, in the order of their start time.
- Busiest days. This will provide the list of upcoming dates with activities, sorted in descending order of the free time in that day (all intervals with no activities).
- Activities with a given person. List all upcoming activities to which a given person will participate.
5. Unlimited undo/redo functionality. Each step will undo/redo the previous operation performed by the user. Undo/redo operations must cascade and have a memory-efficient implementation (no superfluous list copying).
"""
from repository.myrepo import Repository
from ui.GUI import GUI
from ui.console import UI
if __name__ == '__main__':
print(' Hello!\n')
# ctr = Repository()
# ui = GUI(ctr)
ui = UI()
ui.start()
|
class Collection:
class Iterator:
def __init__(self, collection):
self.__collection = collection
self.__id_iterator = iter(self.__collection._data)
def __iter__(self):
return self
def __next__(self):
return self.__collection._data[next(self.__id_iterator)]
def __init__(self):
self._data = {}
def __iter__(self):
return Collection.Iterator(self)
def __getitem__(self, key):
return self._data[key] if key in self._data else None
def __setitem__(self, id, entity):
self._data[id] = entity
def __delitem__(self, key):
del self._data[key]
def __len__(self):
return len(self._data)
def values(self):
return list(self._data.values())
def add(self, entity):
self._data[entity.id] = entity
def reorder(self, new_order):
self._data = {k: self._data[k] for k in new_order}
# c = Collection()
# c.add(Person(2, 'name2', 'number'))
# c.add(Person(3, 'name3', 'number'))
# c.add(Person(4, 'name4', 'number'))
# c.add(Person(5, 'name5', 'number'))
# c.add(Person(1, 'name1', 'number'))
# c.add(Person(6, 'name6', 'number'))
#
# print(c._data)
# for person in c:
# print(person)
# gnome_sort(c, id_comparison)
# for person in c:
# print(person)
|
from repository.repo import Repo
from settings import ROWS, COLS
class Service:
def __init__(self):
self.repo = Repo()
self.player = 1
def board(self):
return self.repo.board()
def empty_board(self):
"""
Empties board
"""
self.repo.empty_board()
def available_square(self, row, col):
"""
Checks if the position (row, col) is free on the board
:param row: int
:param col: int
:return: True or False
"""
try:
col = int(col)
except:
return False
if -1 < col < COLS and -1 < row < ROWS:
for i in range(row, ROWS):
if self.board()[i][col] == 0:
return True
return False
def board_full(self):
"""
Checks if the board is full
:return: True or False
"""
for row in range(ROWS):
for col in range(COLS):
if self.board()[row][col] == 0:
return False
return True
def check_win(self, board):
"""
Checks if any player has won
-if there is a winner, returns the player who won, type of win and winning move
-if there is no winner, returns only 0 values
:param board: current board
:return: winning_player, x_type, y_type, x, y
"""
for row in range(ROWS):
for col in range(COLS):
if board[row][col] != 0:
ok = 0
row2 = 0
col2 = 0
if row + 3 < ROWS and board[row + 3][col] == board[row + 2][col] == board[row + 1][col] == \
board[row][col]:
ok = 1
row2 = 3
col2 = 0
elif col + 3 < COLS and board[row][col + 3] == board[row][col + 2] == board[row][col + 1] == \
board[row][col]:
ok = 1
row2 = 0
col2 = 3
elif row + 3 < ROWS and col + 3 < COLS and board[row + 3][col + 3] == board[row + 2][
col + 2] == board[row + 1][col + 1] == board[row][col]:
ok = 1
row2 = 3
col2 = 3
elif row + 3 < ROWS and col - 3 > -1 and board[row + 3][col - 3] == board[row + 2][col - 2] == \
board[row + 1][col - 1] == board[row][col]:
ok = 1
row2 = 3
col2 = -3
if ok != 0:
return board[row][col], row2, col2, row, col
return 0, 0, 0, 0, 0
|
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精
'''
题目:给定一个 n × n 的二维矩阵表示一个图像。将图像顺时针旋转 90 度。
你必须在原地旋转图像,这意味着你需要直接修改输入的二维矩阵。请不要使用另一个矩阵来旋转图像。
例1
给定 matrix =
[
[1,2,3],
[4,5,6],
[7,8,9]
],
原地旋转输入矩阵,使其变为:
[
[7,4,1],
[8,5,2],
[9,6,3]
]
分析:
思路:
先转置再左右对称翻转。
比如:
输入为:[
[1,2,3],
[4,5,6],
[7,8,9]
],
转置可以得到:[
[1,4,7],
[2,5,8],
[3,6,9],
]
再对每一行进行翻转,即可得到答案:[
[7,4,1],
[8,5,2],
[9,6,3],
]
'''
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: None Do not return anything, modify matrix in-place instead.
"""
# 先转置再左右对称翻转
if not matrix or not matrix[0]:
return matrix
n = len(matrix)
for i in range(n):
for j in range(i + 1, n):
matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]
for row in matrix:
for i in range(n // 2):
row[i], row[n - 1 - i] = row[n - 1 - i], row[i]
return matrix
#___________________________________ 练习1 ______________________________#
'''
这里有个主要的问题 是进行 90度旋转时,只能从本身形式上进行调整,而不能使用其他的结构。
这里基本的思路是 旋转的过程 不能一步而就,而是进行两步的过程。
第一步:转置。
第二步:左右对称翻转。
可参考最上面的形式变换 来理解上面的两步骤。
'''
def fun1(matrix):
# 边界条件: 对矩阵的判别
if not matrix or not matrix[0]:
return matrix
# 获取的n是 行数也是 列数
n=len(matrix)
# 第一步: 进行转置操作吧,操作比较简答, 直接 轴的交换即可
for i in range(n):
for j in range(i+1,n):
matrix[i][j],matrix[j][i]=matrix[j][i],matrix[i][j]
# 第二步: 进行 对称翻转操作,很简单,针对于每一行row 进行交换吧 。 这里i序号是列内
for row in matrix:
for i in range(n//2):
row[i],row[n-1-i]=row[n-1-i],row[i]
#最后就是 两步操作的结果,非常简单
return matrix
|
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精
'''
题目:给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。
假设只有一个重复的整数,找出这个重复的数。
示例 1:
输入: [1,3,4,2,2]
输出: 2
示例 2:
输入: [3,1,3,4,2]
输出: 3
说明:
不能更改原数组(假设数组是只读的)。
只能使用额外的 O(1) 的空间。
时间复杂度小于 O(n2) 。
数组中只有一个重复的数字,但它可能不止重复出现一次。
分析:
思路:思路非常多,这里我使用两种吧,标记法和双指针法。
【1】标记法,把每个元素的值当做指向下个元素的下标指针,因为有重复的元素,所以必然有至少两个元素的值相同,因此它们会指向同一个元素,
所以可以从下标为i = 0的元素开始,依次访问对应的元素nums[i],然后把nums[i]变成相反数,
如果第一次访问,那么访问到的元素就是正数,
如果不是第一次访问,那么访问到的元素就是负数, 代表i 就是重复的数,在下一次循环前更新 i 为nums[i]。
注意这种方法修改了nums,虽然可以过OJ,但是不符合要求。
【2】双指针法,把每个元素的值当做指向下个元素的下标指针,问题即可转化为链表的求环问题,
分别设定一个快指针fast,一个慢指针slow,快指针一次走两步,慢指针一次走一步, 如果快慢指针重合了,就代表有环,
此时,如果把fast重置为0,fast和slow每次走一步,那么它们下一次相遇的那个点就是环的起点。
'''
#标记法
class Solution1(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i = 0
while (1):
val = nums[i]
if val > 0:
nums[i] = -1 * nums[i]
i = val
else:
return i
#双指针法
class Solution2(object):
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
slow, fast = 0, 0
while (1):
slow = nums[slow]
fast = nums[nums[fast]]
# print slow, fast
if slow == fast: # loop exists
fast = 0
while (nums[slow] != nums[fast]):
slow = nums[slow]
fast = nums[fast]
# print slow, fast
return nums[fast]
#___________________________________ 练习1 ______________________________#
# 这道题 极其简单,主要转换成链表上的求环问题进行求解, 把每个元素的值当做指向下个元素的下标指针
# 现在使用方法来找到环结点,训练环结点,就是最为常用的如下思路:
'''
分别设定一个快指针fast,一个慢指针slow,
[1]快指针一次走两步,慢指针一次走一步, 如果快慢指针重合了,就代表有环,
[2]此时,如果把fast重置为0,fast和slow每次走一步,那么它们下一次相遇的那个点就是环的起点。
begin 吧.....
'''
# 空间复杂度为O(1) 时间复杂度为O(N)
def fun1(nums):
slow,fast=0,0
while 1:
#获取 快慢指针 所指向的索引位置. 走一次和走两次的区别
slow=nums[slow]
fast=nums[nums[fast]]
#当出现重合后
if slow==fast:
# 第二步骤了
fast=0
while(nums[slow]!=nums[fast]):
# 接下来每次走一步吧
slow=nums[slow]
fast=nums[fast]
#这就是最后知道重合的点,返回即可
return nums[fast] |
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精
'''
题目:给定一个整数数组,你需要寻找一个连续的子数组,如果对这个子数组进行升序排序,那么整个数组都会变为升序排序。
你找到的子数组应是最短的,请输出它的长度。
示例 1:
输入: [2, 6, 4, 8, 10, 9, 15]
输出: 5
解释: 你只需要对 [6, 4, 8, 10, 9] 进行升序排序,那么整个表都会变为升序排序
分析:
思路:先使用sorted()函数将原列表排序,将排序后的列表与原列表中的数据一一对应,找出左边第一个不同的元素与右边起第
一个不同的元素,二者之间数据个数即为输出结果。
'''
# 如下是 第一种方法,比较简单的 排序后,进行逐个比较的方法。 思路过于简单
class Solution(object):
def findUnsortedSubarray(self, nums):
#使用sorted()函数将原列表排序
nums_ordered = sorted(nums)
r = -1
l = len(nums)
#很简单 找到左边第一个不同
for i in range(len(nums)):
if nums_ordered[i] != nums[i]:
l = i
break
#同时找到 右边第一个不同的地方
for i in range(len(nums) - 1, 0, -1):
if nums_ordered[i] != nums[i]:
r = i
break
#二者之间数据个数即为输出结果。
if r <= l:
return 0
else:
return r - l + 1
#___________________________________ 练习1 ______________________________#
# 接下来,试下 不进行预排序的方法。 下面的思路也非常简单,但是比较耗时,2倍的O(N)时间复杂度
class Solution1(object):
def findUnsortedSubarray(self, nums):
# 边界条件的设置
if not nums:
return 0
n = len(nums)
# 正序遍历,根据局部最小值,更新最左端索引。
max_ = nums[0]
right = 0
for i in range(n):
if nums[i] > max_:
max_ = nums[i]
elif nums[i] < max_:
right = i
# 逆序遍历,根据局部最大值,更新最右端索引
min_ = nums[-1]
left = n - 1
for i in range(n - 1, -1, -1):
if nums[i] < min_:
min_ = nums[i]
elif nums[i] > min_:
left = i
# 按照左右比较的索引,来获取出 目标连续的子数组的长度
if left >= right:
return 0
return right - left + 1
'''
另一种简单书写的方式:
1.升序排列数组存入目标数组targ;
2.将原始数组nums和目标数组targ比对;
3.将首尾相同的元素删掉,直到有不同;
4.记住首尾不同元素的位置,切片即可。
'''
def findUnsortedSubarray(nums):
# 第一步
targ=sorted(nums)
if targ==nums:
return 0
# 第二三步,不断比较,找到开始的不同的左右 索引位置
i,j=0,len(nums)-1
while nums[i]==targ[i]:
i=i+1
while nums[j]==targ[j]:
j=j-1
#最后 返回 位置长度
return len(nums[i:j+1])
|
'''
Ŀ
һжǷл
Ϊ˱ʾеĻʹ pos ʾβӵеλã 0 ʼ pos -1ڸûл
ʾ 1
룺head = [3,2,0,-4], pos = 1
true
ͣһβӵڶڵ㡣
ʾ 2
룺head = [1,2], pos = 0
true
ͣһβӵһڵ㡣
ʾ 3
룺head = [1], pos = -1
false
ͣûл
ĿԺһУ
posǸٷɻ
ɺģеhead
ֻҪжǷΡǾǺܼ ָ⡣ ͳб˼·
˼·
dz;һ⣬Ҿֱ λͽˣоǽָԭ⡣ Ҫÿռ䣬ʱ临ӶΪO(N)
˼·ɣһ ʹÿָķʽһʹĹϣǵķ
'''
#˼· һֱȽ ϣǶ߹ӱǣ ֮ߵǣǻ
def hasCycle(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head:
return False
# Ĺнֵÿ (ÿշʱ ǰλÿ) עhead.valǸؼǰΪʱֿܣһǷǻһ־DZǻȴԼÿˣ˼·dz档
while head.next and head.val != None:
head.val = None
head = head.next
# head.val==Nonenextָʱ˵ ǻ
if not head.next:
return False
# head.val==Nonenextָʱ˵ valDZǿÿյģǻ
return True
#___________________________________ ϰ1 ______________________________#
# ʹãdz ڻбĿָ뷨ɣgood
# ʹÿָ뷽 бǷлҵɻĽ㣬 бЩµķʽ
def fun1(head):
# ߽б
if not head or not head.next:
return False
# ָ
slow,fast=head,head
# пָߣע ָÿָÿһбɡ
while fast:
slow=slow.next
fast=fast.next
if fast:
fast=fast.next
# вظλõб𡣺ĵ лָضص
if slow==fast:
return True
# ͷfastˣûл
return False
#___________________________________ ϰ2 ______________________________#
# ǹϣֵǷбǷ л൱ ǡ
def fun2(self, head):
"""
:type head: ListNode
:rtype: bool
"""
record = dict()
p = head
while p:
# ֮ǰ߹ֵͱΪ1˵ǰ߹
if p not in record:
record[p] = 1
#Ҫģ ѾֹˣǾͲ.....
else:
return True
p = p.next
return False
|
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精
'''
题目:根据一棵树的前序遍历与中序遍历构造二叉树。
例如,给出 前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
分析:
思路:使用迭代方法深度构建即可
首先根据前序遍历的定义可以知道,preorder这个数组的第一个元素preorder[0]一定是root,再根据中序遍历的定义,
在inorder这个数组里,root前面的元素都属于root的左子树,root后面的元素都属于右子树,
从这一步得到了left_inorder和right_inorder,接下来我们只需要把root在inorder里的位置index = inorder.index(preorder[0])查找出来,
就可以知道其左子树和右子树的长度,然后再回到preorder,root后面先是左子树,然后是右子树,因为上一步我们已经知道了它们的长度,
所以可以得到left_preorder和left_preorder,然后递归不就完事了。
'''
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
if not preorder:
return None
root = TreeNode(preorder[0])
left_inorder = inorder[: inorder.index(root.val)]
right_inorder = inorder[inorder.index(root.val) + 1:]
l_left = len(left_inorder)
left_preorder = preorder[1:l_left + 1]
right_preorder = preorder[l_left + 1:]
root.left = self.buildTree(left_preorder, left_inorder)
root.right = self.buildTree(right_preorder, right_inorder)
return root
'''
这里是剑指中的原题:
就是一般的 数据结构的问题,利用 前序遍历结果 和 中序遍历结果来确定一棵树
思路:前序的第一个元素是根结点的值,在中序中找到该值,中序中该值的左边的元素是根结点的左子树,右边是右子树,然后递归的处理左边和右边
根本思想还是 利用树的性质做 递归,很简单的递归【不断延伸完成树的构建】
'''
class TreeNode1():
def __init__(self,val):
self.val=val
self.left=None
self.right=None
def construct_tree(preorder=None,inorder=None):
# 首先是递归截止条件
if not preorder or not inorder:
return None
#根据 先序遍历的位置找到 根节点。
index=inorder.index(preorder[0])
left=inorder[0:index]
right=inorder[index+1:]
#创建节点树 (不断嵌入搭建好整个树,注意 一个树下前序和中序的长度肯定是一致的)
root=TreeNode(preorder[0])
root.left=construct_tree(preorder[1:1+len(left)],left)
root.right=construct_tree(preorder[-len(right)],right)
return root
#___________________________________ 练习1 ______________________________#
# 这个是比较 有趣的, 考研中 经常会用到的题吧,根据前中序遍历列表 来进行二叉树的构建,还原出原二叉树。
# 传递前序 和 中序 序列。
# 先找到的根节点索引 不断切分左右子树 进行整体构建
# 时间复杂度为O(N) 空间复杂度为O(N)
class Solution1(object):
def buildTree(self, preorder, inorder):
"""
:type preorder: List[int]
:type inorder: List[int]
:rtype: TreeNode
"""
# 边界条件
if not preorder:
return None
# 先根据 先序和中序序列 找到根节点位置
index=inorder.index(preorder[0])
# 根据找到的根节点索引 切分左右子树
left=inorder[:index]
right=inorder[index+1:]
#根据 左右子树 来创建节点树吧. 分别创建根节点 和 左右节点指向,从而完成整个树的搭建
root=TreeNode(preorder[0])
# 这里左右子树的指向 分别是根节点切分后的 递归需要传递的前序和 中序序列.....
root.left=self.buildTree(preorder[1:1+index],left)
root.right=self.buildTree(preorder[index+1:],right)
# 不断的递归和回溯,完整整个树的所有工作。
return root
|
'''
һжǷǸ߶ƽĶ
Уһø߶ƽΪһÿڵ ĸ߶Ȳľֵ1
'''
# һʱ ˢɣ ֱͨĸ߶Ƚеݹб
# ʱ临ӶΪO(NlogN)ռ临ӶΪO(log(N))
class Solution(object):
# ȡƽ Ľ
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
else:
# ƽһ ȲСЩҶƽ
return abs(self.deep(root.left) - self.deep(root.right)) <= 1 and self.isBalanced(
root.left) and self.isBalanced(root.right)
def deep(self, root):
if not root:
return 0
else:
left = self.deep(root.left) + 1
right = self.deep(root.right) + 1
return max(left, right) |
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精
'''
题目:给定一个会议时间安排的数组,每个会议时间都会包括开始和结束的时间 [[s1,e1],[s2,e2],...] (si < ei),
为避免会议冲突,同时要考虑充分利用会议室资源,请你计算至少需要多少间会议室,才能满足这些会议安排。
示例 1:
输入: [[0, 30],[5, 10],[15, 20]]
输出: 2
示例 2:
输入: [[7,10],[2,4]]
输出: 1
分析:
思路:根据输入的intervals数组,我希望能知道每个时刻 i 需要用多少个会议室 record[i],
这样我返回所需的最大值即可,
这道题类似于作区间加法,在开会的时候区间内加一,所以利用前缀和数组来计算。对于每个interval,
将它开始的时刻 record[begin] + 1, 结束的时刻 record[end] - 1,然后利用前缀和计算整个区间。
'''
class Solution(object):
def minMeetingRooms(self, intervals):
"""
:type intervals: List[List[int]]
:rtype: int
"""
if not intervals:
return 0
if not intervals[0]:
return 1
intervals = sorted(intervals, key=lambda x: x[1])
record = [0 for _ in range(intervals[-1][1] + 1)]
for interval in intervals:
# print record
begin, end = interval[0], interval[1]
record[begin] += 1
record[end] -= 1
for i, x in enumerate(record):
if i > 0:
record[i] += record[i - 1]
return max(record)
#___________________________________ 练习1 ______________________________#
# 这道题还是非常简单的,主要是计算重合情况。 做下统计即可
def fun1(intervals):
# 边界条件
if not intervals:
return 0
if not intervals[0]:
return 1
# 首先进行初始的排序 根据结束时间来排序
intervals=sorted(intervals,key=lambda x:x[1])
# 获取 所有范围时间点上的 房间安排初始设定
record=[0 for _ in range(intervals[-1][1]+1)]
# 进行时间点 安排情况的统计吧
for interval in intervals:
# 分别根据起始、终止时间点进行附加
begin,end=interval[0],interval[1]
# 这是个关键,起始时说明 占用,end时表示解除占用
record[begin]+=1
record[end]-=1
# 最后直接做从起点开始的 累加统计即可. 这里会对每个时间点都记性统计,长度很长,但是因为有之前的+1 -1操作,这种统计是绝对有效的
for i,x in enumerate(record):
if i>0:
record[i]+=record[i-1]
return max(record)
fun1([[7,10],[2,4]]) |
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精
'''
题目:给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。
如果 pos 是 -1,则在该链表中没有环。
示例 1:
输入:head = [3,2,0,-4], pos = 1
输出:tail connects to node index 1
解释:链表中有一个环,其尾部连接到第二个节点。
示例 2:
输入:head = [1], pos = -1
输出:no cycle
解释:链表中没有环
分析:
思路:快慢指针法。先判断链表有没有环,如果链表有环,则让快指针回到链表的头重新出发,当快慢指针相遇的那个节点即是
链表环的起点。
思路非常简单,就是三步,也是在 题目141快慢指针基础上再加一步。
(1)快慢指针走, 直到快慢指针碰头。 一个每次走两步,一个每次走一步。
(2)重新一个指针从碰头位置走、一个从起点走,都每次走一步, 当这两个行走再碰头时,位置点就是 环的入点。
至于 为什么第二步能行,能可以看图和推导出来,先可以记住这种方式。 一点解释:
第一个慢指针走过的路程长度是x1 + x2 + k1 * (x2 + x3)。
第二个快指针走过的路程长度是x1 + x2 + k2 * (x2 + x3)。
由快慢指针的速度关系得:(x1 + x2) * 2 + 2 * k1 * (x2 + x3) = x1 + x2 + k2 * (x2 + x3),
因此x1 + x2 = (k2 - 2 * k1) * (x2 + x3),进而有x1 - x3 = (k2 - 2 * k1 - 1) * (x2 + x3)。
这说明x1和x3的距离差值刚好是环长(x2 + x3)的整数倍。因此,我们只需令其中一个指针指向虚拟头节点,
而另一个指针则仍然在相遇的那个节点,一起移动这两个指针,直到这两个指针相遇,这个新的相遇点就是链表开始入环的第一个节点。
'''
class Solution(object):
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
#边界条件 判别
if not head or not head.next:
return None
# (1)跟 141一样的,快慢指针法,如果快慢指针会和,那就是有环。
slow, fast = head, head
while fast:
slow = slow.next
fast = fast.next
if fast:
fast = fast.next
if slow == fast:
break
# 小过程吧,没环就可以退出了。
if slow != fast: # 链表无环
return None
# (2)主要的地方,在确定有环后, 分别从fast与slow相遇点 、起点 开始走,两者每次走一步,当再次走到重合点,那就是 链表入环点,很经典的思路。
fast = head
while slow:
if slow == fast: # 此点即是环起点
return slow
slow = slow.next
fast = fast.next
#___________________________________ 练习1 ______________________________#
'''
说曹操,曹操到,我141题还在纳闷来,为什么只是判断是否是 链表,而没有 让找 链表的环位置。
这题就刚好,让找到这个环的入点位置。以前做过这道题,很经典的思路吧,进行了两次走 即可。
'''
def detectCycle(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
#边界条件 判别
if not head or not head.next:
return None
# (1)跟 141一样的,快慢指针法,如果快慢指针会和,那就是有环。
slow, fast = head, head
while fast:
slow = slow.next
fast = fast.next
if fast:
fast = fast.next
if slow == fast:
break
# 小过程吧,没环就可以退出了。
if slow != fast: # 链表无环
return None
# (2)主要的地方,在确定有环后, 分别从fast与slow相遇点 、起点 开始走,两者每次走一步,当再次走到重合点,那就是 链表入环点,很经典的思路。
fast = head
while slow:
if slow == fast: # 此点即是环起点
return slow
slow = slow.next
fast = fast.next
|
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精
'''
题目:给定一个整数 n,求以 1 ... n 为节点组成的二叉搜索树有多少种?
输入: 3
输出: 5
解释:
给定 n = 3, 一共有 5 种不同结构的二叉搜索树:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
分析:
假设n个节点存在二叉排序树的个数是res(n) 【注意起点要求是 二叉排序树】
当n = 0时,结果为1,
当n = 1时, 结果为1,
当n = 2时, 结果为2,
当n = 3时, 结果为5,从上面题目的解释里可以看到:
*当1是根节点的时候,左子树节点个数(比1小的数的个数)为0,右子树节点个数为 3-1-0 = 2, 所以这种情况的答案总共有res(0) * res(2),
*当2是根节点的时候,左子树节点个数为1, 右子树节点个数为3-1-1 = 1,答案共有res(1) * res(1)
*当3是根节点的时候,左子树节点个数为2,右子树节点个数为0,答案共有res(2) * res(0)
所以实际上res(3) = 5 = res(0) * res(2) + res(1) * res(1) + res(2) * res(0)
可得出通项公式res(n) = res(0)*res(n-1) + res(1) * res(n-2) +......+ res(n-2) * res(2) + res(n-1) * res(0),
即卡特兰数,h(n)=C(2n,n)/(n+1) (n=0,1,2,...)
但是找规律的方法 算不算旁门左道
思路:
'''
class Solution(object):
def numTrees(self, n):
"""
:type n: int
:rtype: int
"""
res = [0] * (n + 1)
res[0] = 1
res[1] = 1
for i in range(2, n + 1):
for j in range(i):
res[i] += res[j] * res[i - j - 1]
return res[n]
#___________________________________ 练习1 ______________________________#
# 这里就从 之前解析处的 推断来 设定方程吧, 可以获知 通项式子,满足卡特兰数的公式情况:h(n)=C(2n,n)/(n+1)
def fun1(n):
# 设定初始 推断项。 res是指i+1树的目标搜索树数量
res=[0] * (n+1)
res[0]=1
res[1]=1
# 进行自下往上的 式子推进,借用 卡特兰数
for i in range(2,n+1):
#通式中的C部分, 会逐减做累乘
for j in range(i):
#公式代入
res[i]+=res[j]*res[i-j-1]
# 最终的结果。最后一个位置
return res[n]
#___________________________________ 练习2(非找规律方法) ______________________________# |
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精
'''
题目:给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例如 给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
分析:
思路:
简单直接的思路是使用BFS的方法,处理每一层的时候记录下一层的节点,并把当前这一层每个节点的值记录到结果里。
此外就是使用队列的方式,进行遍历,也是非常常用的方式。
'''
class Solution(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
if not root:
return []
node = [root]
result = list(list())
self.generate(node, result)
return result
def generate(self, node, result):
next_layer_node = []
current_layer_result = []
for node in node:
if node.left:
next_layer_node.append(node.left)
if node.right:
next_layer_node.append(node.right)
current_layer_result.append(node.val)
result.append(current_layer_result)
if len(next_layer_node) == 0:
return
self.generate(next_layer_node, result)
#这里是 利用辅助工具,使用队列的方式。
class Solution1(object):
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
queue = [root]
res = []
while queue:
next_queue = []
layer = []
for node in queue:
if node:
layer.append(node.val)
next_queue += [node.left, node.right]
queue = next_queue[:]
if layer:
res.append(layer[:])
return res
#___________________________________ 练习1 ______________________________#
# 这里层次遍历,分为递归方法 和 非递归方法两种, 但是最为直观 且好理解的就是 非递归方法,这里使用队列的方式来实现把,很easy
# 这里有个特点,就是 题目中 每层是放在一个数组中的, 所以看样子 必须是按照每个layer合在一起了,因此 上面的队列写法是必须的
def fun1(root):
# 创建 队列,用于承载每一层
queue=[root]
res=[]
# 进行队列的压入和弹出. 这里每个queue存储单层的所有节点信息
while queue:
# 进行下一队列和 下一层上节点的收集 两者各有含义,一个是指针,另一个是具体指
next_queue=[]
layer=[]
# 对于当前队列,进行层上遍历吧
for node in queue:
if node:
# layer 和 next_queue 附加信息, 其中layer 附加的是 要遍历的值, next_queue 是指向下层的孩子。
layer.append(node.val)
next_queue+=[node.left,node.right]
# 将收集的 队列 进行 含义替换吧
queue=next_queue[:]
# 对层遍历结果 做 附加
if layer:
res.append(layer[:])
# 返回。
return res
|
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精
'''
题目:给定一个数组 nums,有一个大小为 k 的滑动窗口从数组的最左侧移动到数组的最右侧。你只可以看到在滑动窗口 k 内
的数字。滑动窗口每次只向右移动一位。返回滑动窗口最大值。
输入: nums = [1,3,-1,-3,5,3,6,7], 和 k = 3
输出: [3,3,5,5,6,7]
滑动窗口的位置 最大值
--------------- -----
[1 3 -1] -3 5 3 6 7 3
1 [3 -1 -3] 5 3 6 7 3
1 3 [-1 -3 5] 3 6 7 5
1 3 -1 [-3 5 3] 6 7 5
1 3 -1 -3 [5 3 6] 7 6
1 3 -1 -3 5 [3 6 7] 7
分析: 剑指offer原题,较为简单吧
思路: 按照之前的吧
'''
'''
题目:给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。
例如,如果输入数组{2,3,4,2,6,2,5,1}及滑动窗口的大小3,那么一共存在6个滑动窗口,他们的最大值分别为{4,4,6,6,6,5}。
分析:这里 很明显的, 就是 是需要以滑动窗口的形式,对于n大小滑动窗口、窗口大小为k, 需要产生的滑动窗口最大值数量应该为:n-k+1
主要按窗口逐步打出,基本思路包括以下几种:
(1)最为简单,直接能够相当的,就是每次圈定一个滑动窗口,圈定后对窗口内的数排序得到最大即可。
但是这种方法的时间复杂度太高了 O((n-k+1)*k),这里后面乘k是因为内部找最大,太慢了,虽然空间复杂度是O(1),但是这个方法太low了
(2)第二种 是较为经典的双端 队列的方式,双端操作的方式,非常经典,该方法可以有效的令时间复杂度为O(n),空间复杂度为O(k)
用容量为k的双端队列存储数组元素的索引!!是索引,主要的思考是(视频解释:https://www.youtube.com/watch?v=2SXqBsTR6a8):
【1】如果新来的值比队列尾部的数小,那就追加到后面,因为它可能在前面的最大值划出窗口后成为最大值
【2】如果新来的值比尾部的大,那就删掉尾部,再追加到后面
【3】如果追加的值的索引跟队列头部的值的索引 数量超过窗口大小k,那就删掉一个头部的值
【4】每次队列的头都是滑动窗口中值最大的
使用上面方式的思考,对于队列来说,其实就是每次在保障在有效的窗口范围内,队列的第一个始终是窗口对应最大的。
(3)第三种是 使用最大堆的方式,这个方法类同找topk问题一样,用堆方法特别好理解,构建一个窗口size大小的最大堆,
每次从堆中取出窗口的最大值,随着窗口往右滑动,需要将堆中不属于窗口的堆顶元素删除。
'''
class solution:
#数组num 和 窗口大小size
def maxinwindows(self,num,size):
n=len(num)
#边界条件
if not num or size<=0 or size>n:
return []
#定义一个双端队列
maxqueue=[]
#定义存放要打印的 窗口中的最大值
maxlist=[]
#开始正式的进行遍历吧
for i in range(n):
#之前的处理三, 当队列头部 对应下标 跟当前索引下标差 是否 超出了 滑动窗口的限制。 那么就需要弹出队首操作
if len(maxqueue)>0 and i-size>=maxqueue[0]:
maxqueue.pop(0)
#现在开始考虑处理二,如果新加入的大于前面的,那就不断pop吧 这里切记前面可不是全pop,而是只pop比当前值小的
while len(maxqueue)>0 and num[i]>num[maxqueue[-1]]:
maxqueue.pop()
#正常的处理一
maxqueue.append(i)
#最后,保存下要打印的即可,结束... 从第size个开始打印
if i>size-1:
maxlist.append(num[maxqueue[0]])
return maxlist
#___________________________________ 练习1 ______________________________#
# 比较简单的一道题吧,不断进行 窗口内最大值的统计, 接下来就再来一遍比较经典的双端队列解法。 维护一个长度为size的双端队列
# 时间复杂度为O(N),空间复杂度为O(k)
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
n=len(nums)
# 边界条件
if not nums or k<=0 or k>n:
return []
#定义双端队列 、 用于存储的窗口最大值 maxqueue中[0]表示最大的,然后后面的表示较小的候选的
maxqueue=[]
maxlist=[]
#进行正式的 队列遍历填充过程
for i in range(n):
# 处理方式三 如果追加的值的索引跟队列头部的值的索引 数量超过窗口大小k,那就删掉一个头部的值 (i-k>=maxqueue[0] 表示 头部位置失效了)
if len(maxqueue)>0 and i-k>=maxqueue[0]:
maxqueue.pop(0)
# 处理方式二 如果新来的值比尾部的大,那就删掉尾部,再追加到后面 (这个可以参考解析中的视频,可以弹弹弹,不断弹队尾)
while len(maxqueue)>0 and nums[i]>nums[maxqueue[-1]]:
maxqueue.pop()
# 处理方式1 这里能够保证队列前面都是较大的原因是 如果新来的比之前的大,就会弹出去,而且是从队尾开始弹,所以不用顾虑
maxqueue.append(i)
#最后 进行保存
if i>k-2: # 每次队列的头都是滑动窗口中值最大的
maxlist.append(nums[maxqueue[0]])
# 进行窗口最大值的返回
return maxlist
|
# coding: utf-8 使用学习生长法进行思考, 认真开始分析, 题不在多,在于精
'''
题目:编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性:
每行的元素从左到右升序排列。
每列的元素从上到下升序排列。
示例:
现有矩阵 matrix 如下:
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
给定 target = 5,返回 true。
给定 target = 20,返回 false。
分析:
思路:有两个解法吧。
【1】暴力搜索,直接扫描二维矩阵的全部元素,看能不能找到target。
【2】根据题意,每一行的第一个数字是这一行最小的数,每一列的最后一个数字是这一列最大的数,所以不妨从矩阵的左下角出发,
如果target比当前元素小,则说明target肯定不在这一行,因为 每一行的第一个数字是这一行最小的数,
因此最后一行可以被去掉。如果target比当前元素大,则说明target肯定不在这一列,因为 每一列的最后一个数字是这一列最大的数,
因此第一列可以被去掉。按照以上步骤依次处理,如果最后矩阵都为空了,还没有找到target,就说明target不存在于matrix中。
'''
#解法一
class Solution1(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
m, n = len(matrix), len(matrix[0])
for i in range(m):
for j in range(n):
if matrix[i][j] == target:
return True
return False
#解法二
class Solution2(object):
def searchMatrix(self, matrix, target):
"""
:type matrix: List[List[int]]
:type target: int
:rtype: bool
"""
if not matrix or not matrix[0]:
return False
m, n = len(matrix), len(matrix[0])
i, j = m - 1, 0
while 0 <= i < m and 0 <= j < n:
if matrix[i][j] == target:
return True
elif matrix[i][j] > target:
i -= 1
else:
j += 1
return False
#___________________________________ 练习1 ______________________________#
'''
感觉这就是一道原题吧,根据 矩阵的 位置上的大小比较关系,进行高效大的二维数值上的数字查找。
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22], 右下大于左上
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]
强行分治法。 从左下角开始寻找,不断缩小探索矩阵,每次移动后,都看作新的矩阵下的左下角。因为左下角的元素是这一行中最小的元素,同时又是这一列中最大的元素。最大的元素。
比较左下角元素和目标:
[1]若左下角元素等于目标,则找到
[2]若左下角元素大于目标,则目标不可能存在于当前矩阵的最后一行,问题规模可以减小为在去掉最后一行的子矩阵中寻找目标
[3]若左下角元素小于目标,则目标不可能存在于当前矩阵的第一列,问题规模可以减小为在去掉第一列的子矩阵中寻找目标
[4]若最后矩阵减小为空,则说明不存在
'''
# matrix 是有一定大小关系的矩阵,target是目标查找值。
def fun1(matrix,target):
# 获取行数,并进行边界条件判别,0是 矩阵不存在的
m = len(matrix)
if m == 0:
return False
# 同上,针对列,但是这里必须要错开,因为首先要保证matrix[0] 存在才行。
n = len(matrix[0])
if n == 0:
return False
# 设定开始于 左上角的坐标位置
i=m-1
j=0
while i>=0 and j<n:
# 对应 [1]情况
if matrix[i][j]==target:
return True
#对应 [3]情况的,挪动,往右走一步,缩小范围了。
elif matrix[i][j]<target:
j+=1
# 最后对应 【2】情况,往上走一步,搜小范围
else:
i-=1
# 最后如果都找不到,那就false吧
return False
|
__author__ = 'syedaali'
'''
12/25/2014
This is a small DCIM, or data-center inventory management tool.
It stores 3 items, hostname, admin name, and a field called active.
Hostname is obvious, it's the hostname. Admin name is the name of a person
who is in-charge of the server. Active field should be yes/no, and indicates
if the server is active or not. Active server indicates whether it is being
used or not.
This program reads input from a file called servers.txt. The file should have
one server entry per line of the format:
hostname, admin-name, yes or no
This program also creates a small SQLITE database called servers.db, that
you can manually query for now. In the future querying will be supported
through this program.
Hostname has to be unique, the program needs write permissions in the directory
you are running it from.
How to run this program: python dcim.py
'''
import sqlite3
class Server(object):
def __init__(self, **kwargs):
for k, v in kwargs.iteritems():
setattr(self, k, v)
@property
def name(self):
return self.__name
@name.setter
def name(self, name):
self.__name = name
@property
def admin(self):
return self.__admin
@admin.setter
def admin(self, admin):
self.__admin = admin
@property
def active(self):
return self.__active
@active.setter
def active(self, active):
self.__active = active
def Sql_Create():
sql_create = '''
CREATE TABLE IF NOT EXISTS servers(name TEXT PRIMARY KEY, admin TEXT, active TEXT)
'''
try:
with sqlite3.connect('servers.db') as con:
cur = con.cursor()
cur.execute(sql_create)
con.commit()
except Exception, e:
print e
def Sql_Insert(h):
sql_insert = '''
INSERT INTO servers (name,admin,active) VALUES('{0}','{1}','{2}')
'''.format(h.name, h.admin, h.active)
try:
with sqlite3.connect('servers.db') as con:
cur = con.cursor()
cur.execute(sql_insert)
con.commit()
except Exception, e:
print e
def main():
s_list = []
Sql_Create()
with open('servers.txt', 'r') as f:
for line in f:
line = line.rstrip('\n')
line = line.lower()
s_list = line.split(',')
h = Server(name=s_list[0], admin=s_list[1], active=s_list[2])
Sql_Insert(h)
main()
|
############################################################################
#
#Write a Python script to merge two Python dictionaries.
#
############################################################################
dict1 = {'roll_no' : 1, 'name' : 'Shreya', 'std' : '9th'}
dict2 = {'school' : 'xyz', 'college' : 'bvm'}
# update dict1 with dict2
dict1.update(dict2)
print(dict1)
|
######################################################################
#
#Write program using each function. (using lambda function and list.)
#
######################################################################
from functools import reduce
#1) filter
print("filter")
My_list = [1,2,3,4]
result = list(filter(lambda x : (x % 2 != 0), My_list))
print(result)
print()
#2) map
print("map")
result = list(map(lambda x : (x * 2), My_list))
print(result)
print()
#3) reduce
print("reduce")
result = reduce((lambda x,y : x + y), My_list)
print(result)
|
###############################################################################
#
# Define a function that can accept two strings as input and print the string
# with maximum length in console. If two strings have the same length, then
# the function should print all strings line by line.
#
###############################################################################
# define the function
def string_len(str1, str2):
#compare lengths
if(len(str1) - len(str2) > 0):
return str1
elif(len(str1) - len(str2) < 0):
return str2
else:
return 'both'
# take input from user
string1 = input("Enter 1st string ")
string2 = input("Enter 2nd string ")
# check if fuction retrun both
if(string_len(string1, string2) == 'both'):
print(string1)
print(string2)
else:
print(string_len(string1, string2))
|
############################################################################
#
# Write a python program which takes comma separated numbers from user and
# print sum of all the numbers.
#
############################################################################
from functools import reduce
numbers = input("Enter the , separated numbers ")
numbers = numbers.split(",")
numbers = [int(num) for num in numbers]
result = reduce((lambda sum, num : sum + num), numbers)
print("Sum of all the numbers using reduce function with lambda is: ", result)
print()
#define a function to sum all values in list
def sum_num(list):
sum = 0
for num in list:
sum += num
return sum
print("Sum of all numbers using sum function is : ", sum_num(numbers))
|
############################################################################
#
# Write a Python script to generate and print a dictionary that contains a
# number (between 1 and n) in the form (x, x*x).
# Sample Dictionary ( n = 5) :
# Expected Output : {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
#
############################################################################
#taking input from user
num= input("Enter the number ")
# validation
if num.isdigit == False:
print("Enter a valid number")
exit(0)
# convert string to int
num = int(num, 10)
#add items to this empty dictionary
dictionary = {}
for key in range(num + 1):
dictionary[key] = key * key # add items to dictionary
print(dictionary)
|
"""
Rotate an array of n elements to the right by k steps.
For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to
[5,6,7,1,2,3,4].
Note:
Try to come up as many solutions as you can, there are at least 3 different
ways to solve this problem.
"""
def reverselastk(a, k):
index = range(len(a))
k = len(a) - k-1
index_rev = index[k+1:] + index[:k+1]
res = map(lambda i: a[i], index_rev)
return res
a = ['a','c','4','3','ea']
k = 3
reverselastk(a,k)
|
"""
Given an array nums, write a function to move all 0's to the end of it while
maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums
should be [1, 3, 12, 0, 0].
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
"""
def moveZeros(nums):
n = len(nums)
j = 0
i = 0
counter = 0
while i < n-j:
if nums[i] ==0:
nums = nums[:i] + nums[i+1:]
j += 1 #remove a 0 from nums
else:
i += 1
counter += 1
return nums + [0] * (n-len(nums))
nums = [0, 1, 0, 3, 12]
moveZeros(nums)
|
"""
Write a function to find the longest common prefix string amongst an array of
strings.
"""
class Solution(object):
def longestCommonPrefix(self, strs):
if len(strs) == 0:
res = ""
elif len(strs) == 1:
res = strs[0]
else:
scan_length = len(strs[0])
res = ""
for i in range(scan_length):
letter = strs[0][i]
try:
if len(strs) == sum(map(lambda x: x[i] == letter, strs)):
res += letter
except IndexError:
break
return res
strs = ["abccccce","abc","abcea"]
Solution().longestCommonPrefix(strs)
|
"""
leetcode Question 27: Distinct Subsequences
Distinct Subsequences
Given a string S and a string T, count the number of distinct subsequences of T in S.
A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, "ACE" is a subsequence of "ABCDE"while "AEC" is not).
Here is an example:
S = "rabbbit", T = "rabbit"
Return 3.
Lessons:
1) Try not use to .remove in the recursion that can modify even the original input values
"""
def numDistinct(S, T):
if len(S) < len(T):
return 0
n = len(S)
m = len(T)
t = [0 for i in range(m + 1)]
t[0] = 1
for i in range(1, n + 1):
# j = m ... 1
for k in range(m):
j = m - k
if S[i - 1] == T[j - 1]:
t[j] += t[j - 1]
return t[m]
numDistinct(S,T)
def subseq(s_interval, k):
if k < 1:
return
elif k == 1:
queque = map(lambda x: [x], s_interval)
return queque
else:
queque = []
for i, num in enumerate(s_interval):
singlelist = [num]
for sub in subseq(s_interval[i+1:] , k-1):
new_ = singlelist+sub
new_.sort()
if new_ not in queque:
queque.append(new_)
return queque
class Solution(object):
def countSubsequence(self, S,T):
s_length = len(S)
t_length = len(T)
S = S.lower()
T = T.lower()
s_interval = range(s_length)
counter = 0
for idx in subseq(s_interval, t_length):
S_ = map(lambda i: S[i], idx)
S_ = "".join(S_)
if S_ == T:
counter += 1
return counter
S = "raaabbbiirit"
T = "rabbit"
Solution().countSubsequence(S,T)
|
"""
Find the kth largest element in an unsorted array. Note that it is the kth
largest element in the sorted order, not the kth distinct element.
For example,
Given [3,2,1,5,6,4] and k = 2, return 5.
Note: You may assume k is always valid, 1 <= k <= array's length.
"""
import os, sys
import numpy as np
def getmax(A):
max_ = max(A)
for i, num in enumerate(A):
if num == max_:
break
return (i, num)
class Solution(object):
def findkthlargest(self, A, k):
for i in range(k):
j, num = getmax(A)
A = A[:j] + A[j+1:]
return num
A=[3,2,1,5,6,4]
Solution().findkthlargest(A,2)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 14th, 2019
This is the solution to calculating 24 based on sequence of numbers provided, and
it will only use +, -, *, / operations
It needs Python 3
@author: M
"""
def cal24_v1(q, a, cache={}):
def equivalent(a, b):
if abs(a-b) < 1e-15:
return True
else:
return False
a = round(a, 20)
if len(q) <=1:
if q[0] == a:
cache[(q,a)] = str(a)
else:
cache[(q,a)] = None
return cache[(q, a)]
elif len(q)==2:
m1,m2 = q[0], q[1]
if equivalent(m1+m2, a):
cache[(q,a)] = "("+str(m2)+ "+"+ str(m1)+")"
elif equivalent(m2-m1, a):
cache[(q,a)] = "("+str(m2)+ "-"+ str(m1)+")"
elif equivalent(m1-m2, a):
cache[(q,a)] = "("+str(m1)+ "-"+ str(m2)+")"
elif equivalent(m2/m1, a):
cache[(q,a)] = str(m2)+ "/"+ str(m1)
elif equivalent(m1/m2, a):
cache[(q,a)] = str(m1)+ "/"+ str(m2)
elif equivalent(m2*m1, a):
cache[(q,a)] = str(m2)+ "*"+ str(m1)
else:
cache[(q,a)] = None
return cache[(q, a)]
else:
for i, v in enumerate(q):
q_ = tuple(list(q[:i]) + list(q[i+1:]))
if cache.get((q, a)) is None:
if (q_, a-v) not in cache:
cache[(q_, a-v)] = cal24_v1(q_, a-v, cache=cache)
if cache.get((q_, a-v)) is not None:
cache[(q, a)] = "(" + cache[(q_, a-v)] + "+" + str(v)+ ")"
if cache.get((q, a)) is None:
if (q_, v-a) not in cache:
cache[(q_, v-a)] = cal24_v1(q_, v-a, cache=cache)
if cache.get((q_, v-a)) is not None:
cache[(q, a)] = "(" + str(v) + "-" + cache[(q_, v-a)] + ")"
if cache.get((q, a)) is None:
if (q_, a*v) not in cache:
cache[(q_, a*v)] = cal24_v1(q_, a*v, cache=cache)
if cache.get((q_, a*v)) is not None:
cache[(q, a)] = "(" + cache[(q_, a*v)] + " / " + str(v) + ")"
if cache.get((q, a)) is None:
if (q_, a+v) not in cache:
cache[(q_, a+v)] = cal24_v1(q_, a+v, cache=cache)
if cache.get((q_, a+v)) is not None:
cache[(q, a)] = "(" + cache[(q_, a+v)] + " - " + str(v) + ")"
if cache.get((q, a)) is None:
if (q_, a/v) not in cache:
cache[(q_, a/v)] = cal24_v1(q_, a/v, cache=cache)
if cache.get((q_, a/v)) is not None:
cache[(q, a)] = "(" + cache[(q_, a/v)] + " * " + str(v) + ")"
if cache.get((q, a)) is None and abs(a)>1e-6:
if (q_, v/a) not in cache:
cache[(q_, v/a)] = cal24_v1(q_, v/a, cache=cache)
if cache.get((q_, v/a)) is not None:
cache[(q, a)] = "(" + str(v) + "/" + cache[(q_, v/a)] + ")"
if cache.get((q, a)):
return cache[(q, a)]
def solution(q, a):
res = cal24_v1(q, a, cache={}) # clear the cache
if res:
if res.startswith("("):
res = res[1:-1]
return res
################## Test Cases ##################
solution(q=(1,5,5,5), a=24)
solution(q=(2,2,13,13), a=24)
solution(q=(2,2,13,13,22,22,20,12,23,231,1,32,43,34), a=24)
|
"""
Given a non-negative integer num, repeatedly add all its digits until the
result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only
one digit, return it.
Follow up:
Could you do it without any loop/recursion in O(1) runtime?
Lessons:
1) The trick is to use recursion
"""
import os, sys
import numpy as np
class Solution(object):
def sumUp(self,num):
num_ = str(num)
num_list = list(num_)
sum_ = sum(map(lambda x: int(x),num_list))
# this is for getting single digit
if len(str(sum_)) > 1:
sum_ = self.sumUp(sum_)
else:
print("Final single digit is %s" %str(sum_))
return sum_
if __name__ == "__main__":
num = 38
Solution().sumUp(num)
|
"""
Longest Substring Without Repeating Characters
Given a string, find the length of the longest substring without repeating characters.
For example, the longest substring without repeating letters for "abcabcbb" is "abc",
which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
"""
def isReapeat(x):
#x = "aba"
x_list = list(x)
if len(x_list) != len(list(set(x_list))):
res = True
else:
res = False
return res
class Solution(object):
def getLongestNonRepeat(self, a):
length = len(a)
queue = []
for i in range(length-1):
for j in range(1,length):
sub_str = a[i:j+1]
if not(isReapeat(sub_str)) and sub_str not in queue:
queue.append(sub_str)
max_length = 0
max_str = ""
for c in queue:
if len(c) > max_length:
max_length = len(c)
max_str = c
return max_length, max_str
a = "abcabcbb"
Solution().getLongestNonRepeat(a)
|
"""
Given a sorted integer array without duplicates, return the summary of its
ranges.
For example, given [0,1,2,4,5,7], return ["0->2","4->5","7"].
"""
def getIntervals(S):
queue = []
for i in range(len(S)):
if len(queue)==0:
start = 0
else:
start = queue[-1][1]+1
if S[i] + 1 == S[min(i+1,len(S)-1)]:
end = i+1
continue
else:
end = i
queue += [[start, end]]
res = []
for i in queue:
if i[1] == i[0]:
res += [str(S[i[0]])]
else:
res += [str(S[i[0]]) + "->" + str(S[i[1]])]
return res
S = [0,1,2,4,5,7]
print getIntervals(S)
|
"""
Spiral Matrix I
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
You should return [1,2,3,6,9,8,7,4,5].
"""
def nextMove(move):
moves = ['right','down','left','up']
move_index = moves.index(move)
if move_index == 3:
nextmove = moves[0]
else:
nextmove = moves[move_index+1]
return nextmove
def nextIndex(idx, nextmove):
# idx=[0,1]
if nextmove == 'right':
return [idx[0],idx[1]+1]
elif nextmove == 'down':
return [idx[0]+1,idx[1]]
elif nextmove == 'left':
return [idx[0],idx[1]-1]
elif nextmove == 'up':
return [idx[0]-1,idx[1]]
def createSpiral(matrix):
nrow = len(matrix)
ncol = len(matrix[0])
for i in range(nrow):
for j in range(ncol):
if i ==0 and j==0:
to_visit =[[i,j]]
else:
to_visit += [[i,j]]
queue = [[0,0]]
count_elements = nrow * ncol
for i in range(1,count_elements):
if i == 1:
prev = [0,0]
to_visit.remove(prev)
nextmove = 'right'
curr = nextIndex(prev, nextmove)
queue += [curr]
else:
prev = curr[:]
curr = nextIndex(prev, nextmove)
if curr not in to_visit:
nextmove = nextMove(nextmove)
curr = nextIndex(prev, nextmove)
to_visit.remove(curr)
queue += [curr]
spiral = map(lambda i: matrix[i[0]][i[1]], queue)
return spiral
matrix = [
[ 1, 2, 3, 4],
[ 5, 6, 7, 8],
[ 9, 10, 11, 12 ]
]
createSpiral(matrix) |
"""
Longest Palindromic Substring
Given a string S, find the longest palindromic substring in S.
You may assume that the maximum length of S is 1000,
and there exists one unique longest palindromic substring.
"""
def isPalingdrom(x):
# x = "abba"
x = x.replace(" ","")
len_ = len(x)
if len_ <=1:
res = False
else:
idx = range(len_)
idx_reverse = map(lambda x: len_-1-x, idx)
res = True
for i in idx:
if x[idx[i]] != x[idx_reverse[i]]:
res = False
break
return res
class Solution(object):
def longestPalindrome(self, a):
queue = []
for i in range(len(a)-1):
for j in range(1+i, len(a)):
if isPalingdrom(a[i:j+1]):
if a[i:j+1] not in queue:
queue.append(a[i:j+1])
max_length = 0
max_string = ""
for q in queue:
if len(q) > max_length:
max_length = len(q)
max_string = q
return max_length, max_string
a = 'akaa2baakcbbc'
s = Solution()
s.longestPalindrome(a)
|
# Inspired by https://www.pythonforbeginners.com/code-snippets-source-code/script-password-generator
import string
from random import *
charset = string.ascii_letters + string.digits
def password(n):
print("Password of length ", n, ": ")
# See link above for source
password = "".join(choice(charset) for x in range(randint(8, 16)))
print(password)
password(18) |
# <user story> as an airport assistant I want to be able to create a flight_trip with a specific destination
# <user story> as an airport assistant I want to be able to create a flight_trip with a specific destination
class Flight_trip:
def __init__(self, flight_number, destination, origin, duration, passenger_list=None, passport_number_list=None):
self.flight_number = flight_number
self.destination = destination
self.origin = origin
self.duration = duration
if passenger_list is None:
passenger_list = []
self.passenger_list = passenger_list
if passport_number_list is None:
passport_number_list = []
self.passport_number_list = passport_number_list
def get_flight_number(self):
return self.flight_number
def create_flight_number(self, new_flight_number):
self.flight_number = new_flight_number
return new_flight_number
# create a flight trip with a specific destination
def flight_destination(self):
return self.destination
# enter the flight destination and store it
def flight_origin(self):
return self.origin
# need to link the origin with destination
# enter the origin of the flight (and link it to the destination)
# need to store the duration
def duration(self):
return self.duration
# enter flight duration, store it
# need to create a passenger list
def get_passenger_details(self):
return self.passenger_list, self.passport_number_list
def add_passenger_details(self, new_passenger, new_passport_number):
self.passenger_list.append(new_passenger)
self.passport_number_list.append(int(new_passport_number))
return self.passenger_list, self.passport_number_list
# def get_passenger_dict(self):
# return self.passenger_dict
# def create_passenger_dictionary(self):
# keys = self.passport_number_list
# values = self.passenger_list
# self.passenger_dict = {key: [] for key in set(keys)}
# for a, b in zip(keys, values):
# self.passenger_dict[a].append(b)
# return self.passenger_dict
# def return_string_list(self):
# return ''.join(self.create_passenger_dictionary())
|
import datetime
def convert_date_to_es_format(date):
try:
datetime.datetime.strptime(date, '%d/%m/%Y')
except ValueError:
raise ValueError("Incorrect data format, should be DD/MM/YYYY")
date_list = date.split('/')
new_date = date_list[2] + '-' + date_list[1] + '-' + date_list[0]
return new_date
def get_today_date():
return datetime.datetime.today().strftime('%Y-%m-%d')
|
'''z={"sb":"hello",23:32,"zhaohuaran":"shabi"}
print z["sb"]
print z[23]
print z["world"]'''
print "--------------------------------"
l=range(97,123)
s=list('abcdefghijklmnopqrstuvwxyz')
def m(a,b):
return a,b
lc=map(m,s,l)
print lc
print "--------------------------------"
'''s=range(97,123)
d={}
i=0
while i<len(s):
d={chr(s[i]):s[i]}
print d
i+=1
print "--------------------------------"
s=range(97,123)
l=map(chr,s)
q=zip(l,s)
print dict(q)
print "--------------------------------"
s=range(97,123)
l=map(chr,s)
q=zip(l,s)
d=dict(q)
k=d.keys()
for x in k:
print x,d[x]
print "--------------------------------"
s=range(97,123)
l=map(chr,s)
q=zip(l,s)
d=dict(q)
k=d.values()
for x in k:
print chr(x)
print "--------------------------------"
import random
k=random.randint(1000000,10000000)
v=random.randint(1000,1000000)
lk=list()
lv=list()
for x in range(0,100000):
k=random.randint(1000000,10000000)
v1=random.randint(1000,1000000)
v2=random.randint(1000,1000000)
v3=random.randint(1000,1000000)
v4=random.randint(1000,1000000)
lk.append(k)
lv.append([v1,v2,v3,v4])
d=dict(zip(lk,lv))
#print d
for k,v in d.items():
print k,v
print "--------------------------------"
import random
from datetime import datetime
k=random.randint(1000000,1000000)
lk=list()
lv=list()
d=dict()
i=0
for x in range(0,100000):
lv=[]
li=random.randint(100000,1000000)
lv1=random.randint(1000,10000000)
lv2=random.randint(1000,10000000)
lv4=random.randint(1000,10000000)
if i % 1000==0:
lv3=25000
print lv1,lv2,lv3,lv4
else:
lv3=random.randint(1000,10000000)
lk.append(li)
lv=[lv1,lv2,lv3,lv4]
d.setdefault(li,lv)
i+=1
b=datetime.now()
i=0
for k in d.keys():
if 25000 == d[k][2]:
print d[k]
i+=1
e=datetime.now()
print b
print e
print i
print "--------------------------------"
i = 0
kk = list()
vv = list()
d = dict()
for x in range(0,100000):
k = random.randint(1000000,10000000)
v1 = random.randint(1000,1000000)
v2 = random.randint(1000,1000000)
v4 = random.randint(1000,1000000)
if i % 10000 == 0:
v3 = 234
print [v1,v2,v3,v4]
else:
v3 = random.randint(1000,1000000)
kk.append(k)
vv = [v1,v2,v3,v4]
d.setdefault(k,vv)
i+=1
#d = dict(zip(kk,vv))
i = 0
for k in d.keys():
if 234 == d[k][2]:
print d[k]
i+=1
print "--------------------------------"
import random
lk = list()
dinfo = dict()
for x in xrange(0,1000000):
k = random.randint(100000,10000000)
lk.append(k)
print 'lk"len',len(lk)
k = random.sample(lk,100000)
print k[:10]
print k[99990:]
for x in xrange(0,100000):
name = "jeapedu" + str(k[x])
year = random.randint(1990,2000)
if x % 5 == 1:
race = 'meng'
else:
race = "han"
if x % 3 == 1:
sex = "f"
else:
sex = "m"
v = [name,year,race,sex]
dinfo.setdefault(k[x],v)
dk = dinfo.keys()
for x in dk[:10] + dk[99990:]:
print dinfo[x]
c=0
s=0
for k in dinfo.keys():
if 1995 == dinfo[k][1] :
c+=1
print 'name ->',dinfo[k][0]
if dinfo[k][3]=='f':
s+=1
print c,c*1.0/100000,s*1.0/c'''
print "----------------------------------"
|
j=1
while j<10:
i=1
while i<10:
print i*j,
i=i+1
j=j+1
print ""
print "------------------------"
j=1
while j<10:
i=1
while i<10:
if j>=i:
print i*j,
else:
print (" "),
i=i+1
j=j+1
print ""
print "-----------------------------"
j=1
while j<10:
print "*",
i=2
while i<10:
if j==i or j==9:
print "*",
else:
print (" "),
i=i+1
j=j+1
print ""
print "--------------------------------"
j=0
while j<9:
i=0
while i<9:
if j==i:
print j*j+2*i+1,
i=i+1
j=j+1
print "",
print "--------------------------"
j=1
while j<10:
i=1
while i<10:
if j==i or i==9 or j==1:
print "*",
else:
print (" "),
i=i+1
j=j+1
print ""
print "---------------------------------"
j=9
while j>0:
print "*",
i=2
while i<10:
if j==i or j==9:
print "*",
else:
print (" "),
i=i+1
j=j-1
print ""
print "---------------------------"
j=1
while j<10:
i=9
while i>0:
if j==i or j==9 or i==1:
print "*",
else:
print (" "),
i=i-1
j=j+1
print ""
print "-----------------------"
j=0
while j<10:
i=1
while i<20:
mid = 19/2+1
if i==mid+j or i==mid-j or j==9:
print "*",
else:
print (" "),
i=i+1
j=j+1
print ""
print "-----------------------------"
j=0
while j<10:
i=1
while i<20:
mid = 19/2+1
if i>=mid+j or i<=mid-j or j==9:
print " ",
else:
print ("*"),
i=i+1
j=j+1
print ""
print "----------------------------------------"
j=10
while j>=0:
i=19
while i>0:
mid = 19/2+1
if i==mid+j or i==mid-j or j==9:
print "*",
else:
print (" "),
i=i-1
j=j-1
print ""
print "-----------------------------"
j=10
while j>0:
i=20
while i>0:
mid = 19/2+1
if i>=mid+j or i<=mid-j or j==10:
print " ",
else:
print ("*"),
i=i-1
j=j-1
print ""
print "----------------------------------------" |
# 5 - Faça um Programa que converta metros para centímetros.
metros = int(input('Digite a quantidade de metros: '))
conversor = metros * 100
print(metros, ' metros, são ', conversor, ' centimetros.') |
#21. Write a NumPy program to create a vector of length 10 with values evenly distributed between 5 and 50.
import numpy as np
v = np.linspace(10, 49, 5)
print("Length 10 with values evenly distributed between 5 and 50:")
print(v)
#22. Write a NumPy program to create a vector with values from 0 to 20 and change the sign of the numbers in the range from 9 to 15.
import numpy as np
x = np.arange(20)
print("Original vector:")
print(x)
print("After changing the sign of the numbers in the range from 9 to 15:")
x[(x >= 9) & (x <= 15)] *= -1
print(x)
#23. Write a NumPy program to create a vector of length 5 filled with arbitrary integers from 0 to 10.
import numpy as np
x = np.random.randint(0, 11, 5)
print("Vector of length 5 filled with arbitrary integers from 0 to 10:")
print(x)
#24. Write a NumPy program to multiply the values of two given vectors.
import numpy as np
x = np.array([1, 8, 3, 5])
print("Vector-1")
print(x)
y= np.random.randint(0, 11, 4)
print("Vector-2")
print(y)
result = x * y
print("Multiply the values of two said vectors:")
print(result)
#25. Write a NumPy program to create a 3x4 matrix filled with values from 10 to 21.
import numpy as np
m= np.arange(10,22).reshape((3, 4))
print(m)
#26. Write a NumPy program to find the number of rows and columns of a given matrix.
import numpy as np
m= np.arange(10,22).reshape((3, 4))
print("Original matrix:")
print(m)
print("Number of rows and columns of the said matrix:")
print(m.shape)
#27. Write a NumPy program to create a 3x3 identity matrix, i.e. diagonal elements are 1, the rest are 0.
import numpy as np
x = np.eye(3)
print(x)
#28. Write a NumPy program to create a 10x10 matrix, in which the elements on the borders will be equal to 1, and inside 0.
import numpy as np
x = np.ones((10, 10))
x[1:-1, 1:-1] = 0
print(x)
#29. Write a NumPy program to create a 5x5 zero matrix with elements on the main diagonal equal to 1, 2, 3, 4, 5.
import numpy as np
x = np.diag([1, 2, 3, 4, 5])
print(x)
#30. Write a NumPy program to create a 4x4 matrix in which 0 and 1 are staggered, with zeros on the main diagonal.
import numpy as np
x = np.zeros((4, 4))
x[::2, 1::2] = 1
x[1::2, ::2] = 1
print(x)
#31. Write a NumPy program to create a 3x3x3 array filled with arbitrary values.
import numpy as np
x = np.random.random((3, 3, 3))
print(x)
#32. Write a NumPy program to compute sum of all elements, sum of each column and sum of each row of a given array.
import numpy as np
x = np.array([[0,1],[2,3]])
print("Original array:")
print(x)
print("Sum of all elements:")
print(np.sum(x))
print("Sum of each column:")
print(np.sum(x, axis=0))
print("Sum of each row:")
print(np.sum(x, axis=1))
#33. Write a NumPy program to compute the inner product of two given vectors.
import numpy as np
x = np.array([4, 5])
y = np.array([7, 10])
print("Original vectors:")
print(x)
print(y)
print("Inner product of said vectors:")
print(np.dot(x, y))
#34. Write a NumPy program to add a vector to each row of a given matrix.
import numpy as np
m = np.array([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
v = np.array([1, 1, 0])
print("Original vector:")
print(v)
print("Original matrix:")
print(m)
result = np.empty_like(m)
for i in range(4):
result[i, :] = m[i, :] + v
print("\nAfter adding the vector v to each row of the matrix m:")
print(result)
#35. Write a NumPy program to save a given array to a binary file .
import numpy as np
import os
a = np.arange(20)
np.save('temp_arra.npy', a)
print("Check if 'temp_arra.npy' exists or not?")
if os.path.exists('temp_arra.npy'):
x2 = np.load('temp_arra.npy')
print(np.array_equal(a, x2))
#36. Write a NumPy program to save two given arrays into a single file in compressed format (.npz format) and load it
import numpy as np
import os
x = np.arange(10)
y = np.arange(11, 20)
print("Original arrays:")
print(x)
print(y)
np.savez('temp_arra.npz', x=x, y=y)
print("Load arrays from the 'temp_arra.npz' file:")
with np.load('temp_arra.npz') as data:
x2 = data['x']
y2 = data['y']
print(x2)
print(y2)
#37. Write a NumPy program to save a given array to a text file and load it.
import numpy as np
import os
x = np.arange(12).reshape(4, 3)
print("Original array:")
print(x)
header = 'col1 col2 col3'
np.savetxt('temp.txt', x, fmt="%d", header=header)
print("After loading, content of the text file:")
result = np.loadtxt('temp.txt')
print(result)
#38. Write a NumPy program to convert a given array into bytes, and load it as array.
import numpy as np
import os
a = np.array([1, 2, 3, 4, 5, 6])
print("Original array:")
print(a)
a_bytes = a.tostring()
a2 = np.fromstring(a_bytes, dtype=a.dtype)
print("After loading, content of the text file:")
print(a2)
print(np.array_equal(a, a2))
#39. Write a NumPy program to convert a given array into a list and then convert it into a list again.
import numpy as np
a = [[1, 2], [3, 4]]
x = np.array(a)
a2 = x.tolist()
print(a == a2)
#40. Write a NumPy program to compute the x and y coordinates for points on a sine curve and plot the points using matplotlib.
import numpy as np
import matplotlib.pyplot as plt
# Compute the x and y coordinates for points on a sine curve
x = np.arange(0, 3 * np.pi, 0.2)
y = np.sin(x)
print("Plot the points using matplotlib:")
plt.plot(x, y)
plt.show()
|
arr=list()
n=int(input("enter the no. of elements "))
for i in range(0,n):
arr.append(int(input("num: ")))
sum =int(input("enter the sum of two numbers "))
sorted(arr)
l=0
h=n-1
c=0
while(l<h):
if(arr[l]+arr[h]==sum):
print("two numbers whose sum matches the given sum are",arr[l],arr[h])
c=1
break
elif(arr[l]+arr[h]<sum):
l=l+1
else:
h=h-1
if(c==0):
print("no matches found") |
n= int(input())
l=1
r= n*n+1
print("pattern is -")
for i in range(0,n):
for j in range(0,i):
print(" ", end="")
for j in range(i,n):
print(str(l)+"*", end="")
l=l+1
for j in range(i,n):
print(r, end="")
if(j<n-1):
print("*", end="")
r=r+1
r=r-((n-i)*2-1)
print()
|
def find_group(programs, program, group):
group |= {program}
for p in programs[program]:
if p not in group:
group |= find_group(programs, p, group)
return group
programs = {}
with open('input/day12_input', 'r') as f:
for program in f:
p = program.strip().split('<->')
programs[int(p[0])] = [int(pipe) for pipe in p[1].split(',')]
groups = []
for p in programs:
if not any(p in g for g in groups):
groups.append(find_group(programs, p, set()))
print('Part 1: {}'.format([len(g) for g in groups if 0 in g][0]))
print('Part 2: {}'.format(len(groups)))
|
UP = 0
RIGHT = 1
DOWN = 2
LEFT = 3
step = {
UP: lambda pos: [pos[0] - 1, pos[1]],
RIGHT: lambda pos: [pos[0], pos[1] + 1],
DOWN: lambda pos: [pos[0] + 1, pos[1]],
LEFT: lambda pos: [pos[0], pos[1] - 1],
}
def char_at(diagram, pos):
return diagram[pos[0]][pos[1]] if 0 <= pos[0] < len(diagram) and 0 <= pos[1] < len(diagram[pos[0]]) else ''
def is_valid_move(pos, d, p):
line_types = ['|', '+'] if d == UP or d == DOWN else ['-', '+']
ns = step[d](pos)
return (d != p
and (char_at(diagram, ns) in line_types or char_at(diagram, ns).isalpha()))
diagram = []
with open('input/day19_test', 'r') as f:
for line in f:
diagram.append([c for c in line[:-1]])
pos = [0, len(diagram[0]) - 1]
d = DOWN
letters = []
# while 0 <= pos[0] < len(diagram) and 0 <= pos[1] < len(diagram[pos[0]]):
while True:
pos = step[d](pos)
if char_at(diagram, pos).isalpha():
letters.append(char_at(diagram, pos))
if not is_valid_move(pos, UP, d) and not is_valid_move(pos, RIGHT, d) and not is_valid_move(pos, DOWN, d) and not is_valid_move(pos, LEFT, d):
break
if diagram[pos[0]][pos[1]] == '+':
ns = step[UP](pos)
if d != DOWN and (char_at(diagram, ns) == '|' or char_at(diagram, ns).isalpha()):
d = UP
continue
ns = step[RIGHT](pos)
if d != LEFT and (char_at(diagram, ns) == '-' or char_at(diagram, ns).isalpha()):
d = RIGHT
continue
ns = step[DOWN](pos)
if d != UP and (char_at(diagram, ns) == '|' or char_at(diagram, ns).isalpha()):
d = DOWN
continue
ns = step[LEFT](pos)
if d != RIGHT and (char_at(diagram, ns) == '-' or char_at(diagram, ns).isalpha()):
d = LEFT
continue
break
print('Part 1: {}'.format(''.join(letters)))
|
"""
Puzzle input:
To continue, please consult the code grid in the manual. Enter the code at row 2947, column 3029.
"""
def get_code(row, col):
code = 20151125
r = 2
while True:
r_i = r
c_i = 1
while r_i > 0:
code = (code * 252533) % 33554393
if r_i == row and c_i == col:
return code
r_i -= 1
c_i += 1
r += 1
def part_1():
code = get_code(2947, 3029)
print("Part 1: " + str(code))
part_1()
|
def isint(string):
try:
int(string)
return True
except:
return False
def execute_assembunny(instructions, registers):
pc = 0
while pc < len(instructions):
inst = instructions[pc]
if inst[0] == 'cpy':
registers[inst[2]] = int(inst[1]) if isint(inst[1]) else registers[inst[1]]
elif inst[0] == 'inc':
registers[inst[1]] += 1
elif inst[0] == 'dec':
registers[inst[1]] -= 1
elif inst[0] == 'jnz':
value = int(inst[1]) if isint(inst[1]) else registers[inst[1]]
if value != 0:
pc += int(inst[2])
continue
else:
print('Unknown instruction: ' + inst[0])
pc += 1
def part_1():
registers = {'a': 0, 'b': 0, 'c': 0, 'd': 0}
instructions = None
with open('input/day12_input.txt', 'r') as f:
instructions = [inst.strip().split() for inst in f]
execute_assembunny(instructions, registers)
print('Part 1: {}'.format(registers['a']))
def part_2():
registers = {'a': 0, 'b': 0, 'c': 1, 'd': 0}
instructions = None
with open('input/day12_input.txt', 'r') as f:
instructions = [inst.strip().split() for inst in f]
execute_assembunny(instructions, registers)
print('Part 2: {}'.format(registers['a']))
part_1()
part_2()
|
from itertools import groupby
INVALID_CHARACTERS = (ord("i"), ord("l"), ord("o"))
def is_run(c):
return c[1] == c[2] - 1 and c[0] == c[2] - 2
def is_valid(password):
# Passwords cannot contain "i", "l", or "o"
all_valid_chars = not any(c in password for c in INVALID_CHARACTERS)
# Check for double letters (need at least 2 non-overlapping pairs)
two_pairs = len([k for (k, g) in groupby(password) if len(list(g)) > 1]) > 1
# Detect consecutive runs of characters ("abc", "xyz", etc)
run_found = any([True for c in range(2, len(password)) if is_run(password[c - 2:c + 1])])
return all_valid_chars and two_pairs and run_found
def increment(password):
new_password = password
for i in range(len(new_password), 0, -1):
if new_password[i - 1] == ord("z") + 1:
new_password[i - 1] = 97
new_password[i - 1] += 1
if new_password[i - 1] == ord("z") + 1:
new_password[i - 1] = 97
elif new_password[i - 1] in INVALID_CHARACTERS:
new_password[i - 1] += 1
break
else:
break
return new_password
def get_next_password(password):
p_list = [ord(c) for c in password]
p_list = increment(p_list)
# Pre-process string to remove any invalid characters
invalid_found = False
for i in range(len(p_list)):
if invalid_found:
p_list[i] = ord("a")
elif p_list[i] in INVALID_CHARACTERS:
p_list[i] += 1
invalid_found = True
while not is_valid(p_list):
p_list = increment(p_list)
return "".join([chr(c) for c in p_list])
def part_1():
print("Part 1: " + get_next_password("hepxcrrq"))
def part_2():
print("Part 2: " + get_next_password("hepxxyzz"))
part_1()
part_2()
|
# String
# String di python dapat dideklarasi dengan single ('') atau double ("") quote,
# sebab python sangat sensitif dengan spasi,
# maka gunakan tiga single atau double quote untuk mendeklarasikan multiline string
theString = "Hello World"
thesMultiLineString = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
# NOTE
# String adalah list (array),
# maka kita bisa gunakna segala macam operasi list pada string
print(len(theString))
for x in theString:
print(x)
if "Hello" in theString:
print("Hi")
# Slicing
# Kalian dapat bereksperimen dengan kode di bawah dengan cara menghapus salah satu angka atau menambahkan negatif
print(theString[2:5])
# Escape Character
# Escape Character digunakan saat kalian ingin menggunakan sebuah character atau symbol yang dapat mengganggu string
print("I am \"ironman\"")
# Formatter
# Formatter membantu kalian untuk membuat string yang lebih dinamis
profession = "programmer"
verb = "slacking"
text = "i am a {}, and i will {}"
print(text.format(profession, verb))
# String method
# String method adalah fungsi-fungci yang dapat dioperasikan pada string
print(theString.upper())
print(theString.lower())
# NOTE
# python memiliki banyak string method, kalian dapat melihatnya di https://www.w3schools.com/python/python_strings_methods.asp
|
"""nested_list = [['a', 'b', 'c'], [1, 2, 3]]
# Use indexing to access the second element in the first nested list
element_within_nested_list = nested_list[0][1]
print(element_within_nested_list)"""
"""Slicing a nested list"""
start = 10
end = 21
num_list = list(range(start, end))
overall_list = [['a', 'b', 'c'], num_list, [6, 7, 8]]
# Assign and print the elements in indeces 2, 3, 4, 5, 6 from num_list
sublist = overall_list[1][2:7]
print(sublist) |
import csv
import numpy as np
ERROR_COLUMN = 1
TEST_SET = 0
TRAINING_SET = 1
class ExemplarProvider:
"""
This class provides and holds data for the sampler. It opens up the data
set file, then deals with any necessary transformations to the data set.
"""
def __init__(self, filename):
self.file = open(filename)
self.reader = csv.reader(self.file)
'Convert our data set into a list of list of floats'
self.test_set = list()
self.training_set = list()
'Retain the length of our list'
self.N = len(list(self.reader))
self.file.seek(0)
def read_next_line(self):
return next(self.reader)
'Normalize entire data set except for the last column'
def z_scale(self):
for i in range(len(self.test_set[0])-ERROR_COLUMN):
self.z_scale_column(i)
'Normalize a column'
def z_scale_column(self, column):
items = list()
"""
'Slides tell us to use the mean and SD from ONLY the training set'
'so we will omit this part'
"""
"""
for subList in self.test_set:
items.append(subList[column])
"""
for subList in self.training_set:
items.append(subList[column])
items_arr = np.asarray(items)
col_mean = np.mean(items_arr)
col_sd = np.std(items_arr)
#print("mean: ", col_mean, "sd: ", col_sd)
for subList in self.test_set:
subList[column] = (subList[column] - col_mean)/col_sd
for subList in self.training_set:
subList[column] = (subList[column] - col_mean)/col_sd
'Adds the next row in the csv file to a specified set'
def add_to_set(self, type):
row = list()
for item in next(self.reader):
row.append(float(item))
if type == TEST_SET:
self.test_set.append(row)
elif type == TRAINING_SET:
self.training_set.append(row)
'Getters & Setters'
def get_file_size(self):
return self.N
def get_training_set(self):
return self.training_set
def get_test_set(self):
return self.test_set |
# "my name is Wayne"
# 1
# -1
# 0
# 1.1
# -1.1
# 0.0
# True
# False
# a = str
# b = int
# c = float
# d = bool
# e = "My name is Wayne"
# f = 1
# g = 1.1
# h = True
# str1 = "Hello"
# str2 = "World"
# str3 = str1 + str2
# print(str3)
# a = "Hello"
# b = a
# print(b)
# c = "Hello"
# d = 1
# print(d)
# print(type(d))
# c = 1 + 1
# d = 1 - 1
# e = 2 * 2
# f = 3 / 2
# print(c, d, e, f)
# print(1.0 + 2.5)
# print(3.5 - 1.111)
# print(8.8 * 8.88)
# print(100.1 / 1.1)
# a = True
# b = False
# if a.isdigit():
# b = int(a)
# if b % 2 == 0:
# print("Your enter an even number")
# else:
# print("Your enter an odd number")
# else:
# print("Invalid input")
# import sys
# a = input("Please enter a number: ")
# while a.isdigit() == False:
# print("Invalid Input")
# a = input("Please enter a number: ")
# b = int(a)
# if b % 2 == 0:
# print("Your enter an even number")
# else:
# print("Your enter an odd number")
# for i in range(1, 10):
# print(i)
# for i in "abc":
# print(i)
# import sys
# a = input()
# counter = 0
# a.isalpha()
# for i in a:
# print(i)
# counter = counter + 1
# print("Your enter ", counter, " character(s)") |
import random
class RPSGame:
choice = ['rock', 'scissors', 'paper']
def main_menu(self):
username = self.greet()
starting_rating = self.check_user_in_rating(username)
choice_list = self.get_choices()
print("Okay, let's start")
while True:
user_choice = self.UI()
if user_choice == '!exit':
print("Bye!")
break
if user_choice == '!rating':
print(f"Your rating: {starting_rating}")
continue
bot_choice = random.choice(choice_list)
result = self.determine_winner(user_choice, bot_choice, choice_list)
starting_rating = self.update_rating(starting_rating, result)
self.print_result(bot_choice, result)
def get_choices(self):
uinput = input()
if uinput == '':
return self.choice
choice_list = uinput.split(',')
return choice_list
def update_rating(self, rating, result):
new_rating = rating
if result == 'win':
new_rating += 100
elif result == 'draw':
new_rating += 50
return new_rating
def greet(self):
name = input('Enter your name: ')
print("Hello, " + name)
return name
def check_user_in_rating(self, username):
user_rating_dict = {}
rating = open("rating.txt", 'r')
for line in rating:
name, value = line.split()
value = value.rstrip('\n')
user_rating_dict[name] = (int(value))
rating.close()
if username in user_rating_dict:
return user_rating_dict[username]
else:
return 0
def UI(self):
ui = input()
return ui
def determine_winner(self, user_choice, bot_choice, choice_list):
if user_choice not in choice_list:
return 'invalid'
if user_choice == bot_choice:
return 'draw'
if choice_list == self.choice:
if user_choice == 'rock':
if bot_choice == 'paper':
return 'lose'
return 'win'
if user_choice == 'paper':
if bot_choice == 'scissors':
return 'lose'
return 'win'
if user_choice == 'scissors':
if bot_choice == 'rock':
return 'lose'
return 'win'
x = choice_list.index(user_choice)
new_choices = choice_list[x:]
new_choices.extend(choice_list[:x])
del new_choices[0]
half_len = (len(new_choices) // 2)
bot_choice_index = new_choices.index(bot_choice)
if bot_choice_index < half_len:
return 'lose'
else:
return 'win'
def print_result(self, bot_choice, result):
if result == 'win':
print(f"Well done. Computer chose {bot_choice} and failed")
elif result == 'lose':
print(f"Sorry but computer chose {bot_choice}")
elif result == 'draw':
print(f"There is a draw ({bot_choice})")
elif result == 'invalid':
print("Invalid input")
game = RPSGame()
game.main_menu()
|
#Digite o nome de um cidade e eu te digo se ela começa com Santo
cidade = input('Digite o nome da sua cidade natal:').strip()
div = cidade.upper().split()
print('A sua cidade natal Começa com Santo? {}'.format('SANTO' in div[0])) |
import math
ang = float(input('Informe o valor do ângulo: '))
seno = math.sin(math.radians(ang))
print('O ângulo de {} tem o seno de {:.2f}'.format(ang, seno))
cosseno = math.cos(math.radians(ang))
print('O ângulo de {} tem o cosseno de {:.2f}'.format(ang, cosseno))
tangente = math.tan(math.radians(ang))
print('O ângulo de {} tem a tangente de {:.2f}'.format(ang,tangente)) |
largura = float(input('largura:'))
altura = float(input('altura:'))
area = largura * altura
litro = 2
tinta = area / litro
print('nessa parede será necessário {}L de tinta'.format(tinta)) |
def merge_sort(array):
""" merge sort """
if len(array) > 1:
mid = len(array) / 2
left = array[0:mid]
right = array[mid:]
merge_sort(left)
merge_sort(right)
# merge
l, r = 0, 0
for i in range(len(array)):
if (l < len(left)):
lval = left[l]
else:
lval = None
if ( r < len(right)):
rval = right[r]
else:
rval = None
# lval = left[l] if l < len(left) else None
# rval = right[r] if r < len(right) else None
if ((lval is not None) and (rval is not None) and lval < rval) or (rval is None):
array[i] = lval
l += 1
elif ((lval is not None) and (rval is not None) and lval >= rval) or (lval is None):
array[i] = rval
r += 1
else:
raise Exception('cannot merge')
# if( rval is not None or lval is not None):
# if lval < rval or rval is None:
# array[i] = lval
# l += 1
# elif lval >= rval or lval is None:
# array[i] = rval
# r +=1
# else:
# raise Exception('cannot merge')
#
|
import turtle
mp = turtle.Pen()
mp.speed(0)
#放置图案居中
mp.penup()
mp.goto(140,86)
mp.pendown()
#for循环绘制勾玉
for j in range(3):
#双曲线绘制勾
mp.fillcolor("black")
mp.begin_fill()
mp.dot(100,"black")
mp.backward(50)
mp.right(90)
mp.circle(100,-90)
mp.circle(50,150)
mp.end_fill()
#计算转向时考虑画笔方向
mp.right(90)
mp.penup()
mp.forward(300)
mp.pendown()
turtle.done() |
import abc
from typing import Union
class DataType(metaclass=abc.ABCMeta):
"""
Abstract parent class for all data types.
"""
# Constants for all data types.
INT = 1
STRING = 2
ARRAY = 3
# ------------------------------------------------------------------------------------------------------------------
@abc.abstractmethod
def debug(self, indent: int = 0) -> str:
"""
Returns a string for debugging.
:param int indent: The indentation level.
"""
raise NotImplementedError
# ------------------------------------------------------------------------------------------------------------------
@abc.abstractmethod
def dereference(self):
"""
Returns a clone of this data type.
:rtype: sdoc.sdoc1.data_type.DataType.DataType
"""
raise NotImplementedError
# ------------------------------------------------------------------------------------------------------------------
@abc.abstractmethod
def get_value(self) -> Union[int, str]:
"""
Returns the underling value of this data type.
"""
raise NotImplementedError
# ------------------------------------------------------------------------------------------------------------------
@abc.abstractmethod
def get_type_id(self) -> int:
"""
Returns the ID of this data type.
"""
raise NotImplementedError
# ------------------------------------------------------------------------------------------------------------------
@abc.abstractmethod
def is_constant(self) -> bool:
"""
Returns True if this data type is a constant. Returns False otherwise.
"""
raise NotImplementedError
# ------------------------------------------------------------------------------------------------------------------
@abc.abstractmethod
def is_defined(self) -> bool:
"""
Returns True if this data type is defined, i.e. has a value. Returns False otherwise.
"""
raise NotImplementedError
# ------------------------------------------------------------------------------------------------------------------
@abc.abstractmethod
def is_scalar(self) -> bool:
"""
Returns True if this data type is a scalar. Returns False otherwise.
"""
raise NotImplementedError
# ------------------------------------------------------------------------------------------------------------------
@abc.abstractmethod
def is_true(self) -> bool:
"""
Returns True if this data type evaluates to True. Returns False otherwise.
"""
raise NotImplementedError
# ----------------------------------------------------------------------------------------------------------------------
|
print('''Welcome to use Tony's tool box given by Nick Fury!
I'd like to introduce to you proudly that this tool box has three fantastic functions!
The first one is to encode or decode using base64 method
The second one is to create a dictionary via keys and values given here, print JavaScript Object Notation, and provide a new dictionary with opposite connections
The third one is to create a QRCode jpg via txt given to desktop
So tell me which one would you like to use?(1,2,3)''');
fact = input()
if fact == '1':
print('U want to encode or decode?(1=encode,2=decode)'),
fxc=input()
if fxc == '1':
OCode= bytes(input("Please type what U wanna encode here:"),encoding="UTF-8")
import base64
Encode = base64.b64encode(OCode)
print("The base64 str encoded is", str(Encode,'UTF-8'))
elif fxc == '2':
try:
TCode= bytes(input("Please type what U wanna dncode here:"),encoding="UTF-8")
import base64
Decode = base64.b64decode(TCode)
print("The base64 str decoded is", str(Decode,'UTF-8'))
except:
print("It seems that you didn't give me the correct things")
else:
print('You just made a mistake! 1 OR 2 PLEASE! Run again!')
elif fact == "2":
try:
Dic = {}
print("Tell me what U wanna make as a dictionary\n")
t = 0
while t != "1":
print("Key:")
key = input()
print("Value:")
value = input()
Dic[key]=value
print("Another one? If not, type 1")
t=input()
print("The Original Dic is",Dic)
import json
J = json.dumps(Dic)
print("JavaScript Object Notation made from the Dictionary is")
print(J), print("The type of it is,",type(J))
ADic = dict(zip(Dic.values(),Dic.keys()))
print("The new Dictionary which the value is the old key and the key for the old value is")
print(ADic),print("with type",type(ADic))
except:
print("There is something wrong! Check what U have typed!")
elif fact == '3':
try:
import qrcode
print('Type where the txt U wanna give me here, location please'),
fxe = input()
f = open(fxe,'r',encoding='UTF-8')
fc = f.read()
f.close()
print("This is what will be encoded to a QRCode,",fc)
img = qrcode.make(fc)
img.save('Target.jpg')
except:
print("There are something that I can't understand...")
else:
print("Please check what U typed. Only 1,2,3 will lead to the functions")
|
""" Random Variables """
import random # random is default package
# for i in range(3):
# print(random.random()) # random() by default print values between 0 and 1
# for i in range(7):
# print(random.randint(1, 10)) # randint() allows us to choose the random variable range
""" Exercise """
# class DiceGame:
# def roll(self):
# first_roll = random.randint(0, 6)
# second_roll = random.randint(0, 6)
# return first_roll, second_roll
#
#
# dice = DiceGame()
# print(dice.roll())
""" Reusable Functions """
# def reused_fun(message):
# if message == 'Hello'.upper().lower():
# print('Who is this?')
# else:
# print('Get Out!')
#
#
# message = input('> ')
# reused_fun(message)
#
|
""" FUNCTIONS """
# def hello_python():
# print('Hello world')
# print('How are you?')
#
#
# print('Good Morning') # after function definition leave 2 blank lines and continue (PEP 8: E305 expected 2 blank lines after class or function definition)
# hello_python()
# print('Thank You!')
""" Functions with parameters """
# def hello_world(name): # name is the parameter
# print(f'Hello {name} ')
# print('Welcome aboard')
# print('Stay safe')
#
#
# print('Greetings')
# hello_world("Hari") ## if you have a parameter you should pass a value to the parameter
# hello_world("Rahul") ## Hari and Rahul are arguments.... Arguments and parameters are not the same.
# print('Thank You!')
# def hello_world(first_name, last_name):
# print(f'Hello, {first_name} {last_name} ')
# print(f'Hello, {last_name} {first_name} ')
# print('Welcome aboard')
# print('Stay safe')
# print('Thank You')
# exit()
# print('Greetings')
# hello_world("Hari", "Sridhar") # these 2 arguments are called positional arguments
# hello_world(last_name="Sridhar", first_name="Hari") # this is called keyword argument (It is used to improve the readability of the code,especially if we want to declare multiple numeric values.
# #Always use positional arguments first and then keyword argument
""" FUNCTION USING RETURN STATEMENTS """
# #By Default all functions in Python return None
# #If we have a function that calculates something we can use return statement
#
# def calc_number(number):
# return number * number
#
#
# #print(calc_number(3))
# answer = calc_number(int(input('Please enter a number to calculate: ')))
# print(answer)
|
# Each new term in the Fibonacci sequence is generated by adding the previous two terms.
# By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
f1 = 1 # first term in Fibonacci sequence
f2 = 2 # second term in Fibonacci sequence
total = 0
while f2 <= 4000000: # stops from going over 4 million
if f2 % 2 == 0: # checks if even-valued
total += f2
temp = f2 # store the second term to a temporary term
f2 += f1 # adds the second and first term together to get your new second term
f1 = temp # replaces the first term with second term
print(total)
|
# 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
# What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?
x = 2520 # can start here because any number smaller than this won't meet half the requirements
while x % 20 or x % 19 or x % 18 or x % 17 or x % 16 or x % 15 or x % 14 or x % 13 or x % 12 or x % 11:
# covers all possible divisors
x = x + 20 # increment by 20 as it has to be divisible by 20
print(x)
|
#!/usr/bin/env python
# coding: utf-8
# In[9]:
a=list(input("Enter the number : "))
i=-3
while abs(i)<len(a):
a.insert(i,",")
i-=4
s= ''.join(a)
print("The Number In International System Is :",s)
# In[ ]:
# In[ ]:
|
#list
classes = []
#asking for all of the classes separated by a comma
class_name = (input("Please enter the names of all of the classes you are taking, separate with a comma: "))
#prints this message to the user
print ("Here are the classes you are taking: ")
#splits the inital input by the comma (and a space) and puts it into a new list called individual classes
individual_classes = class_name.split(", ")
#for each item in the new list, add it to the classes list
for i in individual_classes:
classes.append(i)
#prints the whole list
print(classes)
#for each item in the classes list, print a class on a separate line
for one_class in classes:
print(one_class)
|
matrix = []
for _ in range(5):
row = map(int, raw_input().split())
matrix.append(row)
row, column = 0, 0
for _row in range(5):
for _column in range(5):
if matrix[_row][_column] == 1:
row, column = _row, _column
break
print (abs(row - 2) + abs(column - 2))
|
from __future__ import print_function
from node import NodeD as Node
import random
class DList:
def __init__(self):
self.head = Node()
def insert(self, pos, data):
node = Node()
node.set_data(data)
if self.head.get_data() is None:
self.head = node
else:
if pos == 0:
node.set_next(self.head)
self.head.set_prev(node)
self.head = node
else:
i = 1
curr = self.head
while i < (pos - 1) and curr.has_next():
curr = curr.get_next()
i += 1
node.set_next(curr.get_next())
node.set_prev(curr)
curr.get_next().set_prev(node)
curr.set_next(node)
def delete(self, pos):
if pos == 0:
self.head = self.head.get_next()
self.head.set_prev(None)
else:
i = 1
curr = self.head
while i < (pos - 1) and curr.get_next().has_next():
curr = curr.get_next()
i += 1
d_node = curr.get_next()
next_node = d_node.get_next()
d_node.set_prev(None)
d_node.set_next(None)
next_node.set_prev(curr)
curr.set_next(next_node)
def traverse(self):
curr = self.head
while curr:
print (curr.data)
curr = curr.get_next()
if __name__ == '__main__':
l = DList()
print ('===== data =====')
for _ in range(5):
data = random.randint(45, 100)
print (data, end=" ")
l.insert(0, data)
print ('\n===== data ends here =====')
l.traverse()
print('-----')
l.delete(2)
print ('-----')
l.traverse() |
closing = ( ')', '}', ']')
opening = ('(', '{', '[')
brackets = opening + closing
eq = {
'(': ')',
'[': ']',
'{': '}'
}
def balanced_symbols(line):
stack = list()
is_balanced = True
for c in line:
if c not in brackets: continue
elif c in opening: stack.append(c)
elif c in closing:
paren = stack.pop()
# print 'paren', paren
if c != eq[paren]:
is_balanced = False
break
is_balanced = is_balanced and not len(stack)
return is_balanced
symbols = [
'(A+B)+(C-D)',
'((A+B)+(C-D)',
'((A+B)+[C-D])',
'((A+B)+[C-D]}'
]
for symbol in symbols:
print symbol, balanced_symbols(symbol) |
# Create a function that prints a triangle like this:
# *
# ***
# *****
# *******
# *********
# ***********
#
# It should take a number as parameter that describes how many lines the triangle has
def mistery_triangle(lines):
i = 1
while i <= lines:
print(" " * (lines - i), "*" * (i * 2 - 1))
i += 1
mistery_triangle(10) |
# Create a method that decrypts texts/encoded_zen_lines.txt
def decrypt(file_name):
decrypted = ""
text = open(file_name, "r")
encrypted = text.read()
text.close()
for lines in encrypted.splitlines():
for chars in lines:
if chars != ' ':
decrypted += chr(ord(chars) - 1)
else:
decrypted += ' '
decrypted += '\n'
return decrypted
|
# Create a method that decrypts the texts/duplicated_chars.txt
def decrypt(file_name):
decrypted = ""
text = open(file_name, "r")
encrypted = text.read()
text.close()
for lines in encrypted.splitlines():
if len(lines) > 2:
for i in range(0, len(lines), 2):
decrypted += lines[i]
decrypted += '\n'
return decrypted
|
# Create a student Class
# that has a method `add_grade`, that takes a grade from 1 to 5
# an other method `get_average`, that returns the average of the
# grades
class Student():
grade = 0
average = 0
grades = []
def __init__(self, student_name):
self.student_name = student_name
def add_grade(self, grade):
self.grade = grade
if self.grade > 5 and self.grade < 1:
print("Érvénytelen osztályzat!")
else:
self.grades.append(self.grade)
print(self.grades)
def get_average(self):
self.average = sum(self.grades) / len(self.grades)
return int(self.average)
Pistike = Student("Pistike")
Pistike.add_grade(1)
Pistike.add_grade(2)
Pistike.add_grade(5)
print(Pistike.get_average()) |
q = [4, 5, 6, 7]
# get the 3rd element of q
print("the 3rd element:", q[2])
|
# Write a Person class that have a name and a birth_date property
# It should raise an error of the birthdate is less than 0 or more than 2016
class Big_mistake(Exception):
print('[ *** Nagyon - nagyon - nagyon - nagyon - nagy hiba! *** ]')
class Person():
def name(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def birthdate(self, birth_date):
self.birth_date = birth_date.split('.')
self.birth_year = int(self.birth_date[0])
self.birth_month = int(self.birth_date[1])
self.birth_day = int(self.birth_date[2])
if self.birth_year < 0 or 2016 < self.birth_year:
raise Big_mistake
def greetings(self):
return "Hi! Your full name {}, and your birthdate is {} year, {} month, {} day." .format(self.first_name + " " + self.last_name, self.birth_year, self.birth_month, self.birth_day)
jozsi = Person()
jozsi.name("John", "Smith")
try:
jozsi.birthdate('2017.04.05')
except Big_mistake:
pass
print(jozsi.greetings()) |
af = 123
# create a function that doubles it's input
# double af with it
def dubles(number):
print("duble number: ", 2 * number)
dubles(af) |
# Adds a and b, returns as result
def add(a, b):
return a+b
# Returns the highest value from the three given params
def max_of_three(a, b, c):
return max(a, b, c)
# Returns the median value of a list given as param
def median(pool):
if len(pool) % 2 == 0:
return (sorted(pool)[len(pool)//2-1] + sorted(pool)[len(pool)//2]) / 2
else:
return sorted(pool)[len(pool) // 2]
# Returns true if the param is a vovel
def is_vovel(char):
return char.lower() in 'aeiouéáőúűöüóí'
# Create a method that translates hungarian into the teve language
def translate(hungarian):
teve = ''
for char in hungarian:
if is_vovel(char):
teve += (char+'v'+char)
else:
teve += char
return teve |
# Create an "elevator" class
# The class should track the following things:
# - elevator position
# - elevator direction
# - people in the elevator
# - add people
# - remove people
#
# Please remeber that negative amount of people would be troubling
# import view_elevator_template
class Elevator():
def elevator_move(self, new_level, max_level): # elevator mozgás lekezelése
max_level -= 1
if new_level < 0:
return 0
elif new_level >= max_level:
return max_level
else:
return new_level
def add_people(self, add_people, people_in_elevator, max_people_in_elevator):
if add_people <= 0:
add_people = 0
new_people = people_in_elevator + add_people
if new_people < 0:
new_people = 0
elif new_people > max_people_in_elevator:
new_people = max_people_in_elevator
return new_people
def remove_people(self, remove_people, people_in_elevator):
if remove_people < 0:
remove_people = 0
new_people = people_in_elevator - remove_people
if new_people < 0:
new_people = 0
return new_people |
# 9. Given a string, compute recursively a new string where all the
# adjacent chars are now separated by a "*".
def magic_string(string):
if len(string) <= 1:
return string[0]
else:
return string[0] + '*' + magic_string(string[1:])
print(magic_string('1234567890')) |
a = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
max1 = a[0]
maxrr = a[0]
for i in range(1, len(a)):
maxrr = max(a[i], maxrr + a[i])
max1 = max(max1, maxrr)
print(max1)
# 3rd
# https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3285/
|
class MinStack:
def __init__(self):
"""
initialize your data structure here.
"""
self.stack = []
self.min = []
def push(self, x: int) -> None:
if self.stack == []:
self.min.append(x)
self.stack.append(x)
else:
if x <= self.min[-1]:
self.min.append(x)
self.stack.append(x)
def pop(self) -> None:
if self.stack[-1] == self.min[-1]:
self.min.pop(-1)
elif self.stack == []:
return None
self.stack.pop(-1)
def top(self) -> int:
if self.stack == []:
return None
return self.stack[-1]
def getMin(self) -> int:
if self.stack == []:
return None
elif self.min == []:
return None
return self.min[-1]
# Your MinStack object will be instantiated and called as such:
obj = MinStack()
obj.push(0)
obj.push(1)
obj.push(0)
print(obj.getMin())
obj.pop()
print(obj.getMin())
|
#Bo Cen and Canopus Tong
#Lab Section D03
#Lecture Section A1
def cracker(pair): # Decrypt a encrypted text.
ALL_LETTERS = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"]
new_text = ""
if len(pair) == 1: # Check if Key is missing.
new_text = "Missing key!"
else:
text, key = pair[0], pair[1] # Given a pair of string in a list, assign the cyphertext and key.
for char in text: # Translate the cyphertext by its according key using a alphabetical ordered list.
index = ALL_LETTERS.index(char)
new_index = index - int(key) # Find the new index of each letter by subtracting the key.
while new_index >= 26:
new_index = new_index - 26
while new_index < 0:
new_index = new_index + 26
new_char = ALL_LETTERS[new_index]
new_text = new_text + new_char
return new_text
filename = input("Enter the input filename: ") # Main program to run function and print out the resuslt.
file = open(filename)
for line in file:
line = line.strip()
line = line.split(" ") # Split the cyphertext and key apart if applicable.
print(cracker(line))
|
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
def push(self, item):
self.items.append(item)
def insert(self,item):
self.items.insert(0,item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[len(self.items)-1]
def size(self):
return len(self.items)
# Function for reversing a stack and return the reversed stack.
def reverse_a_stack(stack):
reversed_stack = Stack()
for i in range(stack.size()):
reversed_stack.push(stack.pop())
return reversed_stack
# Function for flipping values in a stack and return the stack after being flipped.
def flip_cakes(lst):
initial_stack = Stack()
pancakes_stack = Stack()
to_be_flipped_stack = Stack()
# Push numbers to initial_stack from 1 to the first numeber of the input file.
for i in range(1, int(lst[0]) + 1):
initial_stack.push(i)
# Flip numbers in a stack for sets of times which the user desired.
for flip_num in lst[1:]:
# Push numbers that don't need to be flipped into pancakes_stack.
for i in range(int(lst[0]) - int(flip_num)):
pancakes_stack.push(initial_stack.pop())
# Push numbers that are needed to be flipped into a temporary stack.
for i in range(int(flip_num)):
to_be_flipped_stack.push(initial_stack.pop())
# Flipping the numbers by popping values from the temporary stack and push it into pancakes_stack.
for i in range(int(flip_num)):
pancakes_stack.push(to_be_flipped_stack.pop())
# Reverse pancakes_stack and assign it to initial_stack to proceed to the next set of flips.
initial_stack = reverse_a_stack(pancakes_stack)
# Empty pancakes_stack.
pancakes_stack.__init__()
# After all the flippings, reverse the initial_stack again back to the correct order and return it.
return reverse_a_stack(initial_stack)
# Ask user for input filename and open file.
filename = input("Enter input filename: ")
file = open(filename)
# Read the lines in the file.
for line in file:
# Call the flip_cakes function to start the flipping.
output = flip_cakes(line.split())
# Print all the values that are in the output stack.
for i in range(output.size()):
print(output.pop())
|
# typical mergeSort with inversion modifications
def count_inversions(lst):
count = 0 # initialize inversion implementation, set count to zero
mid = len(lst) // 2
if len(lst) > 1:
lefthalf = lst[:mid]
righthalf = lst[mid:]
count += count_inversions(lefthalf) # add every count in each recursion
count += count_inversions(righthalf) # add every count in each recursion
i=0
j=0
k=0
while i<len(lefthalf) and j<len(righthalf):
if lefthalf[i]<righthalf[j]:
lst[k]=lefthalf[i]
i=i+1
else:
count += len(lefthalf[i:]) # if both halves are not empty and item from the righthalf is chosen, add the remaining length of lefthalf that havn't been chosen to count
lst[k]=righthalf[j]
j=j+1
k=k+1
while i<len(lefthalf):
lst[k]=lefthalf[i]
i=i+1
k=k+1
while j<len(righthalf):
lst[k]=righthalf[j]
j=j+1
k=k+1
return count # return the total number of inversion
|
x = input("username : ")
y = input("password : ")
if x == "adimasfachri" and y == "paramore":
print("Login Berhasil")
else:
print("Login gagal")
"halo guys" |
x = 2
y = "2"
z = True
if type(x) is int:
print("Integer")
if type(y) is str:
print("String")
if type(z) is bool:
print("Boolean")
if (True or True and False):
print("True")
else:
print("False")
if ((True and False) and (True or False) or (False and False)):
print("True")
else:
print("False")
if (5 >= 5 and 2 is 2):
print("True")
else:
print("False")
if 2 in [1,3,5,7,9]:
print("True")
else:
print("False")
if (7 > 3 + 3):
print("True")
else:
print("False")
#This variable will trigger whenever the user enters an item that is not in the list
error = False
print("Pick your favorite animal from: Tiger, Lion, Fish")
animal = input().lower()
if animal not in ('tiger', 'lion', 'fish'):
error = True
print("Pick your favorite color from: Red, Blue, Purple")
color = input().lower()
if color not in ('red', 'blue', 'purple'):
error = True
animalChoice = ""
colorChoice = ""
if animal == 'tiger':
animalChoice = 'tiger'
if color == 'red':
colorChoice = 'red'
elif color == 'blue':
colorChoice = 'blue'
elif color == 'purple':
colorChoice = 'purple'
else:
print("Error - An unknown error has occured.")
elif animal == 'lion':
animalChoice = 'lion'
if color == 'red':
colorChoice = 'red'
elif color == 'blue':
colorChoice = 'blue'
elif color == 'purple':
colorChoice = 'purple'
else:
print("Error - An unknown error has occured.")
elif animal == 'fish':
animalChoice = 'fish'
if color == 'red':
colorChoice = 'red'
elif color == 'blue':
colorChoice = 'blue'
elif color == 'purple':
colorChoice = 'purple'
else:
print("Error - An unknown error has occured.")
if error:
print("Error - Incorrect user input. Please check your spelling and try again.")
else:
print(f"""The user chose:
Animal: {animalChoice}
Color: {colorChoice}""") |
# Palindrome Exercise
string = input("Enter a word: ")
if string.lower() == string[::-1].lower():
print("'%s' is a palindrome!" % string)
else:
print("'%s' is not a palindrome." % string)
|
import json
import requests
response = requests.get('https://raw.githubusercontent.com/everypolitician/everypolitician-data/master/countries.json')
countries = json.loads(response.content)
print(countries[0].keys())
print(len(countries))
#Pick a country.
print(countries[5])
#Extract the URL for the JSON data about the government of the country of your choice (if the country has more than one governmental body - like how Canada has both the House of Commons and the Senate - you can just pick one of them).
goverment_url = countries[5]['legislatures'][0]['popolo_url']
#Make another request to get that government-specific JSON data.
response_two = requests.get(goverment_url)
countries_two = json.loads(response_two.content)
print(countries_two.keys())
print(len(countries_two['persons']))
#Extract the name of one politician from that JSON response and save it in a variable.
name = countries_two['persons'][0]['name']
print(name) |
days = ["Mon", "Tue", "Wed", "Thur", "Fri", "Sat"]
print(type(days)) # <class 'list'>
print(days[3]) # Thur
print(len(days)) # 6
days.append("Sun") # list에 Sun 추가.
print(days)
print(len(days))
days.reverse() # List의 순서를 반대로
print(days)
# mutable =함수에서 변경 가능 값
# immutable = 변경 불가능한 값
|
from tkinter import *
window = Tk()
window.title("drop Down Menu")
def funct():
pass
#Creating a root menu to insert all the sub menus
root_menu = Menu(window)
window.config(menu = root_menu)
#creating sub menu in the root menu
file_menu = Menu(root_menu) # it initializes a new su menu in the root menu
root_menu.add_cascade(label = "File", menu = file_menu) # it creates the name of the sub menu
file_menu.add_command(label = "new file...", command = funct) #it adds a option to the sub menu
file_menu.add_command(label = "open File", command = funct)
file_menu.add_separator()# it adds a line after the openfile option
file_menu.add_command(label = "exit", command = window.quit)
#creatin a new sub menu
edit_menu = Menu(root_menu)
root_menu.add_cascade(label = "Edit", menu = edit_menu)
edit_menu.add_command(label = "Undo", command = funct)
edit_menu.add_command(label = "Redo", command = funct)
window.mainloop() |
def find_sum_pair(lst, N):
"""
lst: list of sorted integers
N: int
Given a list of sorted integers, e.g. [1, 3, 5, 7], and an integer N, return true if there is a pair of integers in the list that sum up to N. If there is no pair, return false.
Examples:
Input: [1, 2, 4, 5, 6], N = 8
Output: true
Input: [1, 1, 3, 4], N = 2
Output: true
Input: [3, 4, 7, 10], N = 0
Output: false
"""
# Get indices of first and last elements
low = 0
high = len(lst)-1
test_sum = lst[low]+lst[high]
while low < high:
test_sum = lst[low]+lst[high]
if test_sum == N:
return True
elif test_sum < N: # Move ahead from beginning of list
low += 1
elif test_sum > N: # Move back from end of list
high -= 1
return False
lst = [1, 2, 4, 5, 6]
N = 8
print(find_sum_pair(lst, N))
|
#!/usr/bin/env python
import sys
import re
isNumber = '^[1-9][0-9]*\.?[0-9]*([Ee][+-]?[0-9]+)?$';
if len(sys.argv) != 3:
print("Error: two arguments required.")
print("")
print("Usage: {} <arg1> <arg2>".format(sys.argv[0]))
exit(0)
if not re.search(isNumber, sys.argv[1]):
print("Error: the first argument must be a number")
print("")
print("Usage: {} <arg1> <arg2>".format(sys.argv[0]))
exit(0)
if not re.search(isNumber, sys.argv[2]):
print("Error: the second argument must be a number")
print("")
print("Usage: {} <arg1> <arg2>".format(sys.argv[0]))
exit(0)
a = float(sys.argv[1])
b = float(sys.argv[2])
print (a + b)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.