repo
stringlengths 7
55
| path
stringlengths 4
223
| func_name
stringlengths 1
134
| original_string
stringlengths 75
104k
| language
stringclasses 1
value | code
stringlengths 75
104k
| code_tokens
listlengths 19
28.4k
| docstring
stringlengths 1
46.9k
| docstring_tokens
listlengths 1
1.97k
| sha
stringlengths 40
40
| url
stringlengths 87
315
| partition
stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|
apache/incubator-superset
|
superset/data/birth_names.py
|
load_birth_names
|
def load_birth_names():
"""Loading birth name dataset from a zip file in the repo"""
data = get_example_data('birth_names.json.gz')
pdf = pd.read_json(data)
pdf.ds = pd.to_datetime(pdf.ds, unit='ms')
pdf.to_sql(
'birth_names',
db.engine,
if_exists='replace',
chunksize=500,
dtype={
'ds': DateTime,
'gender': String(16),
'state': String(10),
'name': String(255),
},
index=False)
print('Done loading table!')
print('-' * 80)
print('Creating table [birth_names] reference')
obj = db.session.query(TBL).filter_by(table_name='birth_names').first()
if not obj:
obj = TBL(table_name='birth_names')
obj.main_dttm_col = 'ds'
obj.database = get_or_create_main_db()
obj.filter_select_enabled = True
if not any(col.column_name == 'num_california' for col in obj.columns):
obj.columns.append(TableColumn(
column_name='num_california',
expression="CASE WHEN state = 'CA' THEN num ELSE 0 END",
))
if not any(col.metric_name == 'sum__num' for col in obj.metrics):
obj.metrics.append(SqlMetric(
metric_name='sum__num',
expression='SUM(num)',
))
db.session.merge(obj)
db.session.commit()
obj.fetch_metadata()
tbl = obj
defaults = {
'compare_lag': '10',
'compare_suffix': 'o10Y',
'limit': '25',
'granularity_sqla': 'ds',
'groupby': [],
'metric': 'sum__num',
'metrics': ['sum__num'],
'row_limit': config.get('ROW_LIMIT'),
'since': '100 years ago',
'until': 'now',
'viz_type': 'table',
'where': '',
'markup_type': 'markdown',
}
admin = security_manager.find_user('admin')
print('Creating some slices')
slices = [
Slice(
slice_name='Girls',
viz_type='table',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
groupby=['name'],
filters=[{
'col': 'gender',
'op': 'in',
'val': ['girl'],
}],
row_limit=50,
timeseries_limit_metric='sum__num')),
Slice(
slice_name='Boys',
viz_type='table',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
groupby=['name'],
filters=[{
'col': 'gender',
'op': 'in',
'val': ['boy'],
}],
row_limit=50)),
Slice(
slice_name='Participants',
viz_type='big_number',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='big_number', granularity_sqla='ds',
compare_lag='5', compare_suffix='over 5Y')),
Slice(
slice_name='Genders',
viz_type='pie',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='pie', groupby=['gender'])),
Slice(
slice_name='Genders by State',
viz_type='dist_bar',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
adhoc_filters=[
{
'clause': 'WHERE',
'expressionType': 'SIMPLE',
'filterOptionName': '2745eae5',
'comparator': ['other'],
'operator': 'not in',
'subject': 'state',
},
],
viz_type='dist_bar',
metrics=[
{
'expressionType': 'SIMPLE',
'column': {
'column_name': 'sum_boys',
'type': 'BIGINT(20)',
},
'aggregate': 'SUM',
'label': 'Boys',
'optionName': 'metric_11',
},
{
'expressionType': 'SIMPLE',
'column': {
'column_name': 'sum_girls',
'type': 'BIGINT(20)',
},
'aggregate': 'SUM',
'label': 'Girls',
'optionName': 'metric_12',
},
],
groupby=['state'])),
Slice(
slice_name='Trends',
viz_type='line',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='line', groupby=['name'],
granularity_sqla='ds', rich_tooltip=True, show_legend=True)),
Slice(
slice_name='Average and Sum Trends',
viz_type='dual_line',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='dual_line',
metric={
'expressionType': 'SIMPLE',
'column': {
'column_name': 'num',
'type': 'BIGINT(20)',
},
'aggregate': 'AVG',
'label': 'AVG(num)',
'optionName': 'metric_vgops097wej_g8uff99zhk7',
},
metric_2='sum__num',
granularity_sqla='ds')),
Slice(
slice_name='Title',
viz_type='markup',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='markup', markup_type='html',
code="""\
<div style='text-align:center'>
<h1>Birth Names Dashboard</h1>
<p>
The source dataset came from
<a href='https://github.com/hadley/babynames' target='_blank'>[here]</a>
</p>
<img src='/static/assets/images/babytux.jpg'>
</div>
""")),
Slice(
slice_name='Name Cloud',
viz_type='word_cloud',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='word_cloud', size_from='10',
series='name', size_to='70', rotation='square',
limit='100')),
Slice(
slice_name='Pivot Table',
viz_type='pivot_table',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='pivot_table', metrics=['sum__num'],
groupby=['name'], columns=['state'])),
Slice(
slice_name='Number of Girls',
viz_type='big_number_total',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='big_number_total', granularity_sqla='ds',
filters=[{
'col': 'gender',
'op': 'in',
'val': ['girl'],
}],
subheader='total female participants')),
Slice(
slice_name='Number of California Births',
viz_type='big_number_total',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
metric={
'expressionType': 'SIMPLE',
'column': {
'column_name': 'num_california',
'expression': "CASE WHEN state = 'CA' THEN num ELSE 0 END",
},
'aggregate': 'SUM',
'label': 'SUM(num_california)',
},
viz_type='big_number_total',
granularity_sqla='ds')),
Slice(
slice_name='Top 10 California Names Timeseries',
viz_type='line',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
metrics=[{
'expressionType': 'SIMPLE',
'column': {
'column_name': 'num_california',
'expression': "CASE WHEN state = 'CA' THEN num ELSE 0 END",
},
'aggregate': 'SUM',
'label': 'SUM(num_california)',
}],
viz_type='line',
granularity_sqla='ds',
groupby=['name'],
timeseries_limit_metric={
'expressionType': 'SIMPLE',
'column': {
'column_name': 'num_california',
'expression': "CASE WHEN state = 'CA' THEN num ELSE 0 END",
},
'aggregate': 'SUM',
'label': 'SUM(num_california)',
},
limit='10')),
Slice(
slice_name='Names Sorted by Num in California',
viz_type='table',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
groupby=['name'],
row_limit=50,
timeseries_limit_metric={
'expressionType': 'SIMPLE',
'column': {
'column_name': 'num_california',
'expression': "CASE WHEN state = 'CA' THEN num ELSE 0 END",
},
'aggregate': 'SUM',
'label': 'SUM(num_california)',
})),
Slice(
slice_name='Num Births Trend',
viz_type='line',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='line')),
Slice(
slice_name='Daily Totals',
viz_type='table',
datasource_type='table',
datasource_id=tbl.id,
created_by=admin,
params=get_slice_json(
defaults,
groupby=['ds'],
since='40 years ago',
until='now',
viz_type='table')),
]
for slc in slices:
merge_slice(slc)
print('Creating a dashboard')
dash = db.session.query(Dash).filter_by(dashboard_title='Births').first()
if not dash:
dash = Dash()
js = textwrap.dedent("""\
{
"CHART-0dd270f0": {
"meta": {
"chartId": 51,
"width": 2,
"height": 50
},
"type": "CHART",
"id": "CHART-0dd270f0",
"children": []
},
"CHART-a3c21bcc": {
"meta": {
"chartId": 52,
"width": 2,
"height": 50
},
"type": "CHART",
"id": "CHART-a3c21bcc",
"children": []
},
"CHART-976960a5": {
"meta": {
"chartId": 53,
"width": 2,
"height": 25
},
"type": "CHART",
"id": "CHART-976960a5",
"children": []
},
"CHART-58575537": {
"meta": {
"chartId": 54,
"width": 2,
"height": 25
},
"type": "CHART",
"id": "CHART-58575537",
"children": []
},
"CHART-e9cd8f0b": {
"meta": {
"chartId": 55,
"width": 8,
"height": 38
},
"type": "CHART",
"id": "CHART-e9cd8f0b",
"children": []
},
"CHART-e440d205": {
"meta": {
"chartId": 56,
"width": 8,
"height": 50
},
"type": "CHART",
"id": "CHART-e440d205",
"children": []
},
"CHART-59444e0b": {
"meta": {
"chartId": 57,
"width": 3,
"height": 38
},
"type": "CHART",
"id": "CHART-59444e0b",
"children": []
},
"CHART-e2cb4997": {
"meta": {
"chartId": 59,
"width": 4,
"height": 50
},
"type": "CHART",
"id": "CHART-e2cb4997",
"children": []
},
"CHART-e8774b49": {
"meta": {
"chartId": 60,
"width": 12,
"height": 50
},
"type": "CHART",
"id": "CHART-e8774b49",
"children": []
},
"CHART-985bfd1e": {
"meta": {
"chartId": 61,
"width": 4,
"height": 50
},
"type": "CHART",
"id": "CHART-985bfd1e",
"children": []
},
"CHART-17f13246": {
"meta": {
"chartId": 62,
"width": 4,
"height": 50
},
"type": "CHART",
"id": "CHART-17f13246",
"children": []
},
"CHART-729324f6": {
"meta": {
"chartId": 63,
"width": 4,
"height": 50
},
"type": "CHART",
"id": "CHART-729324f6",
"children": []
},
"COLUMN-25a865d6": {
"meta": {
"width": 4,
"background": "BACKGROUND_TRANSPARENT"
},
"type": "COLUMN",
"id": "COLUMN-25a865d6",
"children": [
"ROW-cc97c6ac",
"CHART-e2cb4997"
]
},
"COLUMN-4557b6ba": {
"meta": {
"width": 8,
"background": "BACKGROUND_TRANSPARENT"
},
"type": "COLUMN",
"id": "COLUMN-4557b6ba",
"children": [
"ROW-d2e78e59",
"CHART-e9cd8f0b"
]
},
"GRID_ID": {
"type": "GRID",
"id": "GRID_ID",
"children": [
"ROW-8515ace3",
"ROW-1890385f",
"ROW-f0b64094",
"ROW-be9526b8"
]
},
"HEADER_ID": {
"meta": {
"text": "Births"
},
"type": "HEADER",
"id": "HEADER_ID"
},
"MARKDOWN-00178c27": {
"meta": {
"width": 5,
"code": "<div style=\\"text-align:center\\">\\n <h1>Birth Names Dashboard</h1>\\n <p>\\n The source dataset came from\\n <a href=\\"https://github.com/hadley/babynames\\" target=\\"_blank\\">[here]</a>\\n </p>\\n <img src=\\"/static/assets/images/babytux.jpg\\">\\n</div>\\n",
"height": 38
},
"type": "MARKDOWN",
"id": "MARKDOWN-00178c27",
"children": []
},
"ROOT_ID": {
"type": "ROOT",
"id": "ROOT_ID",
"children": [
"GRID_ID"
]
},
"ROW-1890385f": {
"meta": {
"background": "BACKGROUND_TRANSPARENT"
},
"type": "ROW",
"id": "ROW-1890385f",
"children": [
"CHART-e440d205",
"CHART-0dd270f0",
"CHART-a3c21bcc"
]
},
"ROW-8515ace3": {
"meta": {
"background": "BACKGROUND_TRANSPARENT"
},
"type": "ROW",
"id": "ROW-8515ace3",
"children": [
"COLUMN-25a865d6",
"COLUMN-4557b6ba"
]
},
"ROW-be9526b8": {
"meta": {
"background": "BACKGROUND_TRANSPARENT"
},
"type": "ROW",
"id": "ROW-be9526b8",
"children": [
"CHART-985bfd1e",
"CHART-17f13246",
"CHART-729324f6"
]
},
"ROW-cc97c6ac": {
"meta": {
"background": "BACKGROUND_TRANSPARENT"
},
"type": "ROW",
"id": "ROW-cc97c6ac",
"children": [
"CHART-976960a5",
"CHART-58575537"
]
},
"ROW-d2e78e59": {
"meta": {
"background": "BACKGROUND_TRANSPARENT"
},
"type": "ROW",
"id": "ROW-d2e78e59",
"children": [
"MARKDOWN-00178c27",
"CHART-59444e0b"
]
},
"ROW-f0b64094": {
"meta": {
"background": "BACKGROUND_TRANSPARENT"
},
"type": "ROW",
"id": "ROW-f0b64094",
"children": [
"CHART-e8774b49"
]
},
"DASHBOARD_VERSION_KEY": "v2"
}
""")
pos = json.loads(js)
# dashboard v2 doesn't allow add markup slice
dash.slices = [slc for slc in slices if slc.viz_type != 'markup']
update_slice_ids(pos, dash.slices)
dash.dashboard_title = 'Births'
dash.position_json = json.dumps(pos, indent=4)
dash.slug = 'births'
db.session.merge(dash)
db.session.commit()
|
python
|
def load_birth_names():
"""Loading birth name dataset from a zip file in the repo"""
data = get_example_data('birth_names.json.gz')
pdf = pd.read_json(data)
pdf.ds = pd.to_datetime(pdf.ds, unit='ms')
pdf.to_sql(
'birth_names',
db.engine,
if_exists='replace',
chunksize=500,
dtype={
'ds': DateTime,
'gender': String(16),
'state': String(10),
'name': String(255),
},
index=False)
print('Done loading table!')
print('-' * 80)
print('Creating table [birth_names] reference')
obj = db.session.query(TBL).filter_by(table_name='birth_names').first()
if not obj:
obj = TBL(table_name='birth_names')
obj.main_dttm_col = 'ds'
obj.database = get_or_create_main_db()
obj.filter_select_enabled = True
if not any(col.column_name == 'num_california' for col in obj.columns):
obj.columns.append(TableColumn(
column_name='num_california',
expression="CASE WHEN state = 'CA' THEN num ELSE 0 END",
))
if not any(col.metric_name == 'sum__num' for col in obj.metrics):
obj.metrics.append(SqlMetric(
metric_name='sum__num',
expression='SUM(num)',
))
db.session.merge(obj)
db.session.commit()
obj.fetch_metadata()
tbl = obj
defaults = {
'compare_lag': '10',
'compare_suffix': 'o10Y',
'limit': '25',
'granularity_sqla': 'ds',
'groupby': [],
'metric': 'sum__num',
'metrics': ['sum__num'],
'row_limit': config.get('ROW_LIMIT'),
'since': '100 years ago',
'until': 'now',
'viz_type': 'table',
'where': '',
'markup_type': 'markdown',
}
admin = security_manager.find_user('admin')
print('Creating some slices')
slices = [
Slice(
slice_name='Girls',
viz_type='table',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
groupby=['name'],
filters=[{
'col': 'gender',
'op': 'in',
'val': ['girl'],
}],
row_limit=50,
timeseries_limit_metric='sum__num')),
Slice(
slice_name='Boys',
viz_type='table',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
groupby=['name'],
filters=[{
'col': 'gender',
'op': 'in',
'val': ['boy'],
}],
row_limit=50)),
Slice(
slice_name='Participants',
viz_type='big_number',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='big_number', granularity_sqla='ds',
compare_lag='5', compare_suffix='over 5Y')),
Slice(
slice_name='Genders',
viz_type='pie',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='pie', groupby=['gender'])),
Slice(
slice_name='Genders by State',
viz_type='dist_bar',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
adhoc_filters=[
{
'clause': 'WHERE',
'expressionType': 'SIMPLE',
'filterOptionName': '2745eae5',
'comparator': ['other'],
'operator': 'not in',
'subject': 'state',
},
],
viz_type='dist_bar',
metrics=[
{
'expressionType': 'SIMPLE',
'column': {
'column_name': 'sum_boys',
'type': 'BIGINT(20)',
},
'aggregate': 'SUM',
'label': 'Boys',
'optionName': 'metric_11',
},
{
'expressionType': 'SIMPLE',
'column': {
'column_name': 'sum_girls',
'type': 'BIGINT(20)',
},
'aggregate': 'SUM',
'label': 'Girls',
'optionName': 'metric_12',
},
],
groupby=['state'])),
Slice(
slice_name='Trends',
viz_type='line',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='line', groupby=['name'],
granularity_sqla='ds', rich_tooltip=True, show_legend=True)),
Slice(
slice_name='Average and Sum Trends',
viz_type='dual_line',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='dual_line',
metric={
'expressionType': 'SIMPLE',
'column': {
'column_name': 'num',
'type': 'BIGINT(20)',
},
'aggregate': 'AVG',
'label': 'AVG(num)',
'optionName': 'metric_vgops097wej_g8uff99zhk7',
},
metric_2='sum__num',
granularity_sqla='ds')),
Slice(
slice_name='Title',
viz_type='markup',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='markup', markup_type='html',
code="""\
<div style='text-align:center'>
<h1>Birth Names Dashboard</h1>
<p>
The source dataset came from
<a href='https://github.com/hadley/babynames' target='_blank'>[here]</a>
</p>
<img src='/static/assets/images/babytux.jpg'>
</div>
""")),
Slice(
slice_name='Name Cloud',
viz_type='word_cloud',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='word_cloud', size_from='10',
series='name', size_to='70', rotation='square',
limit='100')),
Slice(
slice_name='Pivot Table',
viz_type='pivot_table',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='pivot_table', metrics=['sum__num'],
groupby=['name'], columns=['state'])),
Slice(
slice_name='Number of Girls',
viz_type='big_number_total',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='big_number_total', granularity_sqla='ds',
filters=[{
'col': 'gender',
'op': 'in',
'val': ['girl'],
}],
subheader='total female participants')),
Slice(
slice_name='Number of California Births',
viz_type='big_number_total',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
metric={
'expressionType': 'SIMPLE',
'column': {
'column_name': 'num_california',
'expression': "CASE WHEN state = 'CA' THEN num ELSE 0 END",
},
'aggregate': 'SUM',
'label': 'SUM(num_california)',
},
viz_type='big_number_total',
granularity_sqla='ds')),
Slice(
slice_name='Top 10 California Names Timeseries',
viz_type='line',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
metrics=[{
'expressionType': 'SIMPLE',
'column': {
'column_name': 'num_california',
'expression': "CASE WHEN state = 'CA' THEN num ELSE 0 END",
},
'aggregate': 'SUM',
'label': 'SUM(num_california)',
}],
viz_type='line',
granularity_sqla='ds',
groupby=['name'],
timeseries_limit_metric={
'expressionType': 'SIMPLE',
'column': {
'column_name': 'num_california',
'expression': "CASE WHEN state = 'CA' THEN num ELSE 0 END",
},
'aggregate': 'SUM',
'label': 'SUM(num_california)',
},
limit='10')),
Slice(
slice_name='Names Sorted by Num in California',
viz_type='table',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
groupby=['name'],
row_limit=50,
timeseries_limit_metric={
'expressionType': 'SIMPLE',
'column': {
'column_name': 'num_california',
'expression': "CASE WHEN state = 'CA' THEN num ELSE 0 END",
},
'aggregate': 'SUM',
'label': 'SUM(num_california)',
})),
Slice(
slice_name='Num Births Trend',
viz_type='line',
datasource_type='table',
datasource_id=tbl.id,
params=get_slice_json(
defaults,
viz_type='line')),
Slice(
slice_name='Daily Totals',
viz_type='table',
datasource_type='table',
datasource_id=tbl.id,
created_by=admin,
params=get_slice_json(
defaults,
groupby=['ds'],
since='40 years ago',
until='now',
viz_type='table')),
]
for slc in slices:
merge_slice(slc)
print('Creating a dashboard')
dash = db.session.query(Dash).filter_by(dashboard_title='Births').first()
if not dash:
dash = Dash()
js = textwrap.dedent("""\
{
"CHART-0dd270f0": {
"meta": {
"chartId": 51,
"width": 2,
"height": 50
},
"type": "CHART",
"id": "CHART-0dd270f0",
"children": []
},
"CHART-a3c21bcc": {
"meta": {
"chartId": 52,
"width": 2,
"height": 50
},
"type": "CHART",
"id": "CHART-a3c21bcc",
"children": []
},
"CHART-976960a5": {
"meta": {
"chartId": 53,
"width": 2,
"height": 25
},
"type": "CHART",
"id": "CHART-976960a5",
"children": []
},
"CHART-58575537": {
"meta": {
"chartId": 54,
"width": 2,
"height": 25
},
"type": "CHART",
"id": "CHART-58575537",
"children": []
},
"CHART-e9cd8f0b": {
"meta": {
"chartId": 55,
"width": 8,
"height": 38
},
"type": "CHART",
"id": "CHART-e9cd8f0b",
"children": []
},
"CHART-e440d205": {
"meta": {
"chartId": 56,
"width": 8,
"height": 50
},
"type": "CHART",
"id": "CHART-e440d205",
"children": []
},
"CHART-59444e0b": {
"meta": {
"chartId": 57,
"width": 3,
"height": 38
},
"type": "CHART",
"id": "CHART-59444e0b",
"children": []
},
"CHART-e2cb4997": {
"meta": {
"chartId": 59,
"width": 4,
"height": 50
},
"type": "CHART",
"id": "CHART-e2cb4997",
"children": []
},
"CHART-e8774b49": {
"meta": {
"chartId": 60,
"width": 12,
"height": 50
},
"type": "CHART",
"id": "CHART-e8774b49",
"children": []
},
"CHART-985bfd1e": {
"meta": {
"chartId": 61,
"width": 4,
"height": 50
},
"type": "CHART",
"id": "CHART-985bfd1e",
"children": []
},
"CHART-17f13246": {
"meta": {
"chartId": 62,
"width": 4,
"height": 50
},
"type": "CHART",
"id": "CHART-17f13246",
"children": []
},
"CHART-729324f6": {
"meta": {
"chartId": 63,
"width": 4,
"height": 50
},
"type": "CHART",
"id": "CHART-729324f6",
"children": []
},
"COLUMN-25a865d6": {
"meta": {
"width": 4,
"background": "BACKGROUND_TRANSPARENT"
},
"type": "COLUMN",
"id": "COLUMN-25a865d6",
"children": [
"ROW-cc97c6ac",
"CHART-e2cb4997"
]
},
"COLUMN-4557b6ba": {
"meta": {
"width": 8,
"background": "BACKGROUND_TRANSPARENT"
},
"type": "COLUMN",
"id": "COLUMN-4557b6ba",
"children": [
"ROW-d2e78e59",
"CHART-e9cd8f0b"
]
},
"GRID_ID": {
"type": "GRID",
"id": "GRID_ID",
"children": [
"ROW-8515ace3",
"ROW-1890385f",
"ROW-f0b64094",
"ROW-be9526b8"
]
},
"HEADER_ID": {
"meta": {
"text": "Births"
},
"type": "HEADER",
"id": "HEADER_ID"
},
"MARKDOWN-00178c27": {
"meta": {
"width": 5,
"code": "<div style=\\"text-align:center\\">\\n <h1>Birth Names Dashboard</h1>\\n <p>\\n The source dataset came from\\n <a href=\\"https://github.com/hadley/babynames\\" target=\\"_blank\\">[here]</a>\\n </p>\\n <img src=\\"/static/assets/images/babytux.jpg\\">\\n</div>\\n",
"height": 38
},
"type": "MARKDOWN",
"id": "MARKDOWN-00178c27",
"children": []
},
"ROOT_ID": {
"type": "ROOT",
"id": "ROOT_ID",
"children": [
"GRID_ID"
]
},
"ROW-1890385f": {
"meta": {
"background": "BACKGROUND_TRANSPARENT"
},
"type": "ROW",
"id": "ROW-1890385f",
"children": [
"CHART-e440d205",
"CHART-0dd270f0",
"CHART-a3c21bcc"
]
},
"ROW-8515ace3": {
"meta": {
"background": "BACKGROUND_TRANSPARENT"
},
"type": "ROW",
"id": "ROW-8515ace3",
"children": [
"COLUMN-25a865d6",
"COLUMN-4557b6ba"
]
},
"ROW-be9526b8": {
"meta": {
"background": "BACKGROUND_TRANSPARENT"
},
"type": "ROW",
"id": "ROW-be9526b8",
"children": [
"CHART-985bfd1e",
"CHART-17f13246",
"CHART-729324f6"
]
},
"ROW-cc97c6ac": {
"meta": {
"background": "BACKGROUND_TRANSPARENT"
},
"type": "ROW",
"id": "ROW-cc97c6ac",
"children": [
"CHART-976960a5",
"CHART-58575537"
]
},
"ROW-d2e78e59": {
"meta": {
"background": "BACKGROUND_TRANSPARENT"
},
"type": "ROW",
"id": "ROW-d2e78e59",
"children": [
"MARKDOWN-00178c27",
"CHART-59444e0b"
]
},
"ROW-f0b64094": {
"meta": {
"background": "BACKGROUND_TRANSPARENT"
},
"type": "ROW",
"id": "ROW-f0b64094",
"children": [
"CHART-e8774b49"
]
},
"DASHBOARD_VERSION_KEY": "v2"
}
""")
pos = json.loads(js)
# dashboard v2 doesn't allow add markup slice
dash.slices = [slc for slc in slices if slc.viz_type != 'markup']
update_slice_ids(pos, dash.slices)
dash.dashboard_title = 'Births'
dash.position_json = json.dumps(pos, indent=4)
dash.slug = 'births'
db.session.merge(dash)
db.session.commit()
|
[
"def",
"load_birth_names",
"(",
")",
":",
"data",
"=",
"get_example_data",
"(",
"'birth_names.json.gz'",
")",
"pdf",
"=",
"pd",
".",
"read_json",
"(",
"data",
")",
"pdf",
".",
"ds",
"=",
"pd",
".",
"to_datetime",
"(",
"pdf",
".",
"ds",
",",
"unit",
"=",
"'ms'",
")",
"pdf",
".",
"to_sql",
"(",
"'birth_names'",
",",
"db",
".",
"engine",
",",
"if_exists",
"=",
"'replace'",
",",
"chunksize",
"=",
"500",
",",
"dtype",
"=",
"{",
"'ds'",
":",
"DateTime",
",",
"'gender'",
":",
"String",
"(",
"16",
")",
",",
"'state'",
":",
"String",
"(",
"10",
")",
",",
"'name'",
":",
"String",
"(",
"255",
")",
",",
"}",
",",
"index",
"=",
"False",
")",
"print",
"(",
"'Done loading table!'",
")",
"print",
"(",
"'-'",
"*",
"80",
")",
"print",
"(",
"'Creating table [birth_names] reference'",
")",
"obj",
"=",
"db",
".",
"session",
".",
"query",
"(",
"TBL",
")",
".",
"filter_by",
"(",
"table_name",
"=",
"'birth_names'",
")",
".",
"first",
"(",
")",
"if",
"not",
"obj",
":",
"obj",
"=",
"TBL",
"(",
"table_name",
"=",
"'birth_names'",
")",
"obj",
".",
"main_dttm_col",
"=",
"'ds'",
"obj",
".",
"database",
"=",
"get_or_create_main_db",
"(",
")",
"obj",
".",
"filter_select_enabled",
"=",
"True",
"if",
"not",
"any",
"(",
"col",
".",
"column_name",
"==",
"'num_california'",
"for",
"col",
"in",
"obj",
".",
"columns",
")",
":",
"obj",
".",
"columns",
".",
"append",
"(",
"TableColumn",
"(",
"column_name",
"=",
"'num_california'",
",",
"expression",
"=",
"\"CASE WHEN state = 'CA' THEN num ELSE 0 END\"",
",",
")",
")",
"if",
"not",
"any",
"(",
"col",
".",
"metric_name",
"==",
"'sum__num'",
"for",
"col",
"in",
"obj",
".",
"metrics",
")",
":",
"obj",
".",
"metrics",
".",
"append",
"(",
"SqlMetric",
"(",
"metric_name",
"=",
"'sum__num'",
",",
"expression",
"=",
"'SUM(num)'",
",",
")",
")",
"db",
".",
"session",
".",
"merge",
"(",
"obj",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"obj",
".",
"fetch_metadata",
"(",
")",
"tbl",
"=",
"obj",
"defaults",
"=",
"{",
"'compare_lag'",
":",
"'10'",
",",
"'compare_suffix'",
":",
"'o10Y'",
",",
"'limit'",
":",
"'25'",
",",
"'granularity_sqla'",
":",
"'ds'",
",",
"'groupby'",
":",
"[",
"]",
",",
"'metric'",
":",
"'sum__num'",
",",
"'metrics'",
":",
"[",
"'sum__num'",
"]",
",",
"'row_limit'",
":",
"config",
".",
"get",
"(",
"'ROW_LIMIT'",
")",
",",
"'since'",
":",
"'100 years ago'",
",",
"'until'",
":",
"'now'",
",",
"'viz_type'",
":",
"'table'",
",",
"'where'",
":",
"''",
",",
"'markup_type'",
":",
"'markdown'",
",",
"}",
"admin",
"=",
"security_manager",
".",
"find_user",
"(",
"'admin'",
")",
"print",
"(",
"'Creating some slices'",
")",
"slices",
"=",
"[",
"Slice",
"(",
"slice_name",
"=",
"'Girls'",
",",
"viz_type",
"=",
"'table'",
",",
"datasource_type",
"=",
"'table'",
",",
"datasource_id",
"=",
"tbl",
".",
"id",
",",
"params",
"=",
"get_slice_json",
"(",
"defaults",
",",
"groupby",
"=",
"[",
"'name'",
"]",
",",
"filters",
"=",
"[",
"{",
"'col'",
":",
"'gender'",
",",
"'op'",
":",
"'in'",
",",
"'val'",
":",
"[",
"'girl'",
"]",
",",
"}",
"]",
",",
"row_limit",
"=",
"50",
",",
"timeseries_limit_metric",
"=",
"'sum__num'",
")",
")",
",",
"Slice",
"(",
"slice_name",
"=",
"'Boys'",
",",
"viz_type",
"=",
"'table'",
",",
"datasource_type",
"=",
"'table'",
",",
"datasource_id",
"=",
"tbl",
".",
"id",
",",
"params",
"=",
"get_slice_json",
"(",
"defaults",
",",
"groupby",
"=",
"[",
"'name'",
"]",
",",
"filters",
"=",
"[",
"{",
"'col'",
":",
"'gender'",
",",
"'op'",
":",
"'in'",
",",
"'val'",
":",
"[",
"'boy'",
"]",
",",
"}",
"]",
",",
"row_limit",
"=",
"50",
")",
")",
",",
"Slice",
"(",
"slice_name",
"=",
"'Participants'",
",",
"viz_type",
"=",
"'big_number'",
",",
"datasource_type",
"=",
"'table'",
",",
"datasource_id",
"=",
"tbl",
".",
"id",
",",
"params",
"=",
"get_slice_json",
"(",
"defaults",
",",
"viz_type",
"=",
"'big_number'",
",",
"granularity_sqla",
"=",
"'ds'",
",",
"compare_lag",
"=",
"'5'",
",",
"compare_suffix",
"=",
"'over 5Y'",
")",
")",
",",
"Slice",
"(",
"slice_name",
"=",
"'Genders'",
",",
"viz_type",
"=",
"'pie'",
",",
"datasource_type",
"=",
"'table'",
",",
"datasource_id",
"=",
"tbl",
".",
"id",
",",
"params",
"=",
"get_slice_json",
"(",
"defaults",
",",
"viz_type",
"=",
"'pie'",
",",
"groupby",
"=",
"[",
"'gender'",
"]",
")",
")",
",",
"Slice",
"(",
"slice_name",
"=",
"'Genders by State'",
",",
"viz_type",
"=",
"'dist_bar'",
",",
"datasource_type",
"=",
"'table'",
",",
"datasource_id",
"=",
"tbl",
".",
"id",
",",
"params",
"=",
"get_slice_json",
"(",
"defaults",
",",
"adhoc_filters",
"=",
"[",
"{",
"'clause'",
":",
"'WHERE'",
",",
"'expressionType'",
":",
"'SIMPLE'",
",",
"'filterOptionName'",
":",
"'2745eae5'",
",",
"'comparator'",
":",
"[",
"'other'",
"]",
",",
"'operator'",
":",
"'not in'",
",",
"'subject'",
":",
"'state'",
",",
"}",
",",
"]",
",",
"viz_type",
"=",
"'dist_bar'",
",",
"metrics",
"=",
"[",
"{",
"'expressionType'",
":",
"'SIMPLE'",
",",
"'column'",
":",
"{",
"'column_name'",
":",
"'sum_boys'",
",",
"'type'",
":",
"'BIGINT(20)'",
",",
"}",
",",
"'aggregate'",
":",
"'SUM'",
",",
"'label'",
":",
"'Boys'",
",",
"'optionName'",
":",
"'metric_11'",
",",
"}",
",",
"{",
"'expressionType'",
":",
"'SIMPLE'",
",",
"'column'",
":",
"{",
"'column_name'",
":",
"'sum_girls'",
",",
"'type'",
":",
"'BIGINT(20)'",
",",
"}",
",",
"'aggregate'",
":",
"'SUM'",
",",
"'label'",
":",
"'Girls'",
",",
"'optionName'",
":",
"'metric_12'",
",",
"}",
",",
"]",
",",
"groupby",
"=",
"[",
"'state'",
"]",
")",
")",
",",
"Slice",
"(",
"slice_name",
"=",
"'Trends'",
",",
"viz_type",
"=",
"'line'",
",",
"datasource_type",
"=",
"'table'",
",",
"datasource_id",
"=",
"tbl",
".",
"id",
",",
"params",
"=",
"get_slice_json",
"(",
"defaults",
",",
"viz_type",
"=",
"'line'",
",",
"groupby",
"=",
"[",
"'name'",
"]",
",",
"granularity_sqla",
"=",
"'ds'",
",",
"rich_tooltip",
"=",
"True",
",",
"show_legend",
"=",
"True",
")",
")",
",",
"Slice",
"(",
"slice_name",
"=",
"'Average and Sum Trends'",
",",
"viz_type",
"=",
"'dual_line'",
",",
"datasource_type",
"=",
"'table'",
",",
"datasource_id",
"=",
"tbl",
".",
"id",
",",
"params",
"=",
"get_slice_json",
"(",
"defaults",
",",
"viz_type",
"=",
"'dual_line'",
",",
"metric",
"=",
"{",
"'expressionType'",
":",
"'SIMPLE'",
",",
"'column'",
":",
"{",
"'column_name'",
":",
"'num'",
",",
"'type'",
":",
"'BIGINT(20)'",
",",
"}",
",",
"'aggregate'",
":",
"'AVG'",
",",
"'label'",
":",
"'AVG(num)'",
",",
"'optionName'",
":",
"'metric_vgops097wej_g8uff99zhk7'",
",",
"}",
",",
"metric_2",
"=",
"'sum__num'",
",",
"granularity_sqla",
"=",
"'ds'",
")",
")",
",",
"Slice",
"(",
"slice_name",
"=",
"'Title'",
",",
"viz_type",
"=",
"'markup'",
",",
"datasource_type",
"=",
"'table'",
",",
"datasource_id",
"=",
"tbl",
".",
"id",
",",
"params",
"=",
"get_slice_json",
"(",
"defaults",
",",
"viz_type",
"=",
"'markup'",
",",
"markup_type",
"=",
"'html'",
",",
"code",
"=",
"\"\"\"\\\n <div style='text-align:center'>\n <h1>Birth Names Dashboard</h1>\n <p>\n The source dataset came from\n <a href='https://github.com/hadley/babynames' target='_blank'>[here]</a>\n </p>\n <img src='/static/assets/images/babytux.jpg'>\n </div>\n \"\"\"",
")",
")",
",",
"Slice",
"(",
"slice_name",
"=",
"'Name Cloud'",
",",
"viz_type",
"=",
"'word_cloud'",
",",
"datasource_type",
"=",
"'table'",
",",
"datasource_id",
"=",
"tbl",
".",
"id",
",",
"params",
"=",
"get_slice_json",
"(",
"defaults",
",",
"viz_type",
"=",
"'word_cloud'",
",",
"size_from",
"=",
"'10'",
",",
"series",
"=",
"'name'",
",",
"size_to",
"=",
"'70'",
",",
"rotation",
"=",
"'square'",
",",
"limit",
"=",
"'100'",
")",
")",
",",
"Slice",
"(",
"slice_name",
"=",
"'Pivot Table'",
",",
"viz_type",
"=",
"'pivot_table'",
",",
"datasource_type",
"=",
"'table'",
",",
"datasource_id",
"=",
"tbl",
".",
"id",
",",
"params",
"=",
"get_slice_json",
"(",
"defaults",
",",
"viz_type",
"=",
"'pivot_table'",
",",
"metrics",
"=",
"[",
"'sum__num'",
"]",
",",
"groupby",
"=",
"[",
"'name'",
"]",
",",
"columns",
"=",
"[",
"'state'",
"]",
")",
")",
",",
"Slice",
"(",
"slice_name",
"=",
"'Number of Girls'",
",",
"viz_type",
"=",
"'big_number_total'",
",",
"datasource_type",
"=",
"'table'",
",",
"datasource_id",
"=",
"tbl",
".",
"id",
",",
"params",
"=",
"get_slice_json",
"(",
"defaults",
",",
"viz_type",
"=",
"'big_number_total'",
",",
"granularity_sqla",
"=",
"'ds'",
",",
"filters",
"=",
"[",
"{",
"'col'",
":",
"'gender'",
",",
"'op'",
":",
"'in'",
",",
"'val'",
":",
"[",
"'girl'",
"]",
",",
"}",
"]",
",",
"subheader",
"=",
"'total female participants'",
")",
")",
",",
"Slice",
"(",
"slice_name",
"=",
"'Number of California Births'",
",",
"viz_type",
"=",
"'big_number_total'",
",",
"datasource_type",
"=",
"'table'",
",",
"datasource_id",
"=",
"tbl",
".",
"id",
",",
"params",
"=",
"get_slice_json",
"(",
"defaults",
",",
"metric",
"=",
"{",
"'expressionType'",
":",
"'SIMPLE'",
",",
"'column'",
":",
"{",
"'column_name'",
":",
"'num_california'",
",",
"'expression'",
":",
"\"CASE WHEN state = 'CA' THEN num ELSE 0 END\"",
",",
"}",
",",
"'aggregate'",
":",
"'SUM'",
",",
"'label'",
":",
"'SUM(num_california)'",
",",
"}",
",",
"viz_type",
"=",
"'big_number_total'",
",",
"granularity_sqla",
"=",
"'ds'",
")",
")",
",",
"Slice",
"(",
"slice_name",
"=",
"'Top 10 California Names Timeseries'",
",",
"viz_type",
"=",
"'line'",
",",
"datasource_type",
"=",
"'table'",
",",
"datasource_id",
"=",
"tbl",
".",
"id",
",",
"params",
"=",
"get_slice_json",
"(",
"defaults",
",",
"metrics",
"=",
"[",
"{",
"'expressionType'",
":",
"'SIMPLE'",
",",
"'column'",
":",
"{",
"'column_name'",
":",
"'num_california'",
",",
"'expression'",
":",
"\"CASE WHEN state = 'CA' THEN num ELSE 0 END\"",
",",
"}",
",",
"'aggregate'",
":",
"'SUM'",
",",
"'label'",
":",
"'SUM(num_california)'",
",",
"}",
"]",
",",
"viz_type",
"=",
"'line'",
",",
"granularity_sqla",
"=",
"'ds'",
",",
"groupby",
"=",
"[",
"'name'",
"]",
",",
"timeseries_limit_metric",
"=",
"{",
"'expressionType'",
":",
"'SIMPLE'",
",",
"'column'",
":",
"{",
"'column_name'",
":",
"'num_california'",
",",
"'expression'",
":",
"\"CASE WHEN state = 'CA' THEN num ELSE 0 END\"",
",",
"}",
",",
"'aggregate'",
":",
"'SUM'",
",",
"'label'",
":",
"'SUM(num_california)'",
",",
"}",
",",
"limit",
"=",
"'10'",
")",
")",
",",
"Slice",
"(",
"slice_name",
"=",
"'Names Sorted by Num in California'",
",",
"viz_type",
"=",
"'table'",
",",
"datasource_type",
"=",
"'table'",
",",
"datasource_id",
"=",
"tbl",
".",
"id",
",",
"params",
"=",
"get_slice_json",
"(",
"defaults",
",",
"groupby",
"=",
"[",
"'name'",
"]",
",",
"row_limit",
"=",
"50",
",",
"timeseries_limit_metric",
"=",
"{",
"'expressionType'",
":",
"'SIMPLE'",
",",
"'column'",
":",
"{",
"'column_name'",
":",
"'num_california'",
",",
"'expression'",
":",
"\"CASE WHEN state = 'CA' THEN num ELSE 0 END\"",
",",
"}",
",",
"'aggregate'",
":",
"'SUM'",
",",
"'label'",
":",
"'SUM(num_california)'",
",",
"}",
")",
")",
",",
"Slice",
"(",
"slice_name",
"=",
"'Num Births Trend'",
",",
"viz_type",
"=",
"'line'",
",",
"datasource_type",
"=",
"'table'",
",",
"datasource_id",
"=",
"tbl",
".",
"id",
",",
"params",
"=",
"get_slice_json",
"(",
"defaults",
",",
"viz_type",
"=",
"'line'",
")",
")",
",",
"Slice",
"(",
"slice_name",
"=",
"'Daily Totals'",
",",
"viz_type",
"=",
"'table'",
",",
"datasource_type",
"=",
"'table'",
",",
"datasource_id",
"=",
"tbl",
".",
"id",
",",
"created_by",
"=",
"admin",
",",
"params",
"=",
"get_slice_json",
"(",
"defaults",
",",
"groupby",
"=",
"[",
"'ds'",
"]",
",",
"since",
"=",
"'40 years ago'",
",",
"until",
"=",
"'now'",
",",
"viz_type",
"=",
"'table'",
")",
")",
",",
"]",
"for",
"slc",
"in",
"slices",
":",
"merge_slice",
"(",
"slc",
")",
"print",
"(",
"'Creating a dashboard'",
")",
"dash",
"=",
"db",
".",
"session",
".",
"query",
"(",
"Dash",
")",
".",
"filter_by",
"(",
"dashboard_title",
"=",
"'Births'",
")",
".",
"first",
"(",
")",
"if",
"not",
"dash",
":",
"dash",
"=",
"Dash",
"(",
")",
"js",
"=",
"textwrap",
".",
"dedent",
"(",
"\"\"\"\\\n{\n \"CHART-0dd270f0\": {\n \"meta\": {\n \"chartId\": 51,\n \"width\": 2,\n \"height\": 50\n },\n \"type\": \"CHART\",\n \"id\": \"CHART-0dd270f0\",\n \"children\": []\n },\n \"CHART-a3c21bcc\": {\n \"meta\": {\n \"chartId\": 52,\n \"width\": 2,\n \"height\": 50\n },\n \"type\": \"CHART\",\n \"id\": \"CHART-a3c21bcc\",\n \"children\": []\n },\n \"CHART-976960a5\": {\n \"meta\": {\n \"chartId\": 53,\n \"width\": 2,\n \"height\": 25\n },\n \"type\": \"CHART\",\n \"id\": \"CHART-976960a5\",\n \"children\": []\n },\n \"CHART-58575537\": {\n \"meta\": {\n \"chartId\": 54,\n \"width\": 2,\n \"height\": 25\n },\n \"type\": \"CHART\",\n \"id\": \"CHART-58575537\",\n \"children\": []\n },\n \"CHART-e9cd8f0b\": {\n \"meta\": {\n \"chartId\": 55,\n \"width\": 8,\n \"height\": 38\n },\n \"type\": \"CHART\",\n \"id\": \"CHART-e9cd8f0b\",\n \"children\": []\n },\n \"CHART-e440d205\": {\n \"meta\": {\n \"chartId\": 56,\n \"width\": 8,\n \"height\": 50\n },\n \"type\": \"CHART\",\n \"id\": \"CHART-e440d205\",\n \"children\": []\n },\n \"CHART-59444e0b\": {\n \"meta\": {\n \"chartId\": 57,\n \"width\": 3,\n \"height\": 38\n },\n \"type\": \"CHART\",\n \"id\": \"CHART-59444e0b\",\n \"children\": []\n },\n \"CHART-e2cb4997\": {\n \"meta\": {\n \"chartId\": 59,\n \"width\": 4,\n \"height\": 50\n },\n \"type\": \"CHART\",\n \"id\": \"CHART-e2cb4997\",\n \"children\": []\n },\n \"CHART-e8774b49\": {\n \"meta\": {\n \"chartId\": 60,\n \"width\": 12,\n \"height\": 50\n },\n \"type\": \"CHART\",\n \"id\": \"CHART-e8774b49\",\n \"children\": []\n },\n \"CHART-985bfd1e\": {\n \"meta\": {\n \"chartId\": 61,\n \"width\": 4,\n \"height\": 50\n },\n \"type\": \"CHART\",\n \"id\": \"CHART-985bfd1e\",\n \"children\": []\n },\n \"CHART-17f13246\": {\n \"meta\": {\n \"chartId\": 62,\n \"width\": 4,\n \"height\": 50\n },\n \"type\": \"CHART\",\n \"id\": \"CHART-17f13246\",\n \"children\": []\n },\n \"CHART-729324f6\": {\n \"meta\": {\n \"chartId\": 63,\n \"width\": 4,\n \"height\": 50\n },\n \"type\": \"CHART\",\n \"id\": \"CHART-729324f6\",\n \"children\": []\n },\n \"COLUMN-25a865d6\": {\n \"meta\": {\n \"width\": 4,\n \"background\": \"BACKGROUND_TRANSPARENT\"\n },\n \"type\": \"COLUMN\",\n \"id\": \"COLUMN-25a865d6\",\n \"children\": [\n \"ROW-cc97c6ac\",\n \"CHART-e2cb4997\"\n ]\n },\n \"COLUMN-4557b6ba\": {\n \"meta\": {\n \"width\": 8,\n \"background\": \"BACKGROUND_TRANSPARENT\"\n },\n \"type\": \"COLUMN\",\n \"id\": \"COLUMN-4557b6ba\",\n \"children\": [\n \"ROW-d2e78e59\",\n \"CHART-e9cd8f0b\"\n ]\n },\n \"GRID_ID\": {\n \"type\": \"GRID\",\n \"id\": \"GRID_ID\",\n \"children\": [\n \"ROW-8515ace3\",\n \"ROW-1890385f\",\n \"ROW-f0b64094\",\n \"ROW-be9526b8\"\n ]\n },\n \"HEADER_ID\": {\n \"meta\": {\n \"text\": \"Births\"\n },\n \"type\": \"HEADER\",\n \"id\": \"HEADER_ID\"\n },\n \"MARKDOWN-00178c27\": {\n \"meta\": {\n \"width\": 5,\n \"code\": \"<div style=\\\\\"text-align:center\\\\\">\\\\n <h1>Birth Names Dashboard</h1>\\\\n <p>\\\\n The source dataset came from\\\\n <a href=\\\\\"https://github.com/hadley/babynames\\\\\" target=\\\\\"_blank\\\\\">[here]</a>\\\\n </p>\\\\n <img src=\\\\\"/static/assets/images/babytux.jpg\\\\\">\\\\n</div>\\\\n\",\n \"height\": 38\n },\n \"type\": \"MARKDOWN\",\n \"id\": \"MARKDOWN-00178c27\",\n \"children\": []\n },\n \"ROOT_ID\": {\n \"type\": \"ROOT\",\n \"id\": \"ROOT_ID\",\n \"children\": [\n \"GRID_ID\"\n ]\n },\n \"ROW-1890385f\": {\n \"meta\": {\n \"background\": \"BACKGROUND_TRANSPARENT\"\n },\n \"type\": \"ROW\",\n \"id\": \"ROW-1890385f\",\n \"children\": [\n \"CHART-e440d205\",\n \"CHART-0dd270f0\",\n \"CHART-a3c21bcc\"\n ]\n },\n \"ROW-8515ace3\": {\n \"meta\": {\n \"background\": \"BACKGROUND_TRANSPARENT\"\n },\n \"type\": \"ROW\",\n \"id\": \"ROW-8515ace3\",\n \"children\": [\n \"COLUMN-25a865d6\",\n \"COLUMN-4557b6ba\"\n ]\n },\n \"ROW-be9526b8\": {\n \"meta\": {\n \"background\": \"BACKGROUND_TRANSPARENT\"\n },\n \"type\": \"ROW\",\n \"id\": \"ROW-be9526b8\",\n \"children\": [\n \"CHART-985bfd1e\",\n \"CHART-17f13246\",\n \"CHART-729324f6\"\n ]\n },\n \"ROW-cc97c6ac\": {\n \"meta\": {\n \"background\": \"BACKGROUND_TRANSPARENT\"\n },\n \"type\": \"ROW\",\n \"id\": \"ROW-cc97c6ac\",\n \"children\": [\n \"CHART-976960a5\",\n \"CHART-58575537\"\n ]\n },\n \"ROW-d2e78e59\": {\n \"meta\": {\n \"background\": \"BACKGROUND_TRANSPARENT\"\n },\n \"type\": \"ROW\",\n \"id\": \"ROW-d2e78e59\",\n \"children\": [\n \"MARKDOWN-00178c27\",\n \"CHART-59444e0b\"\n ]\n },\n \"ROW-f0b64094\": {\n \"meta\": {\n \"background\": \"BACKGROUND_TRANSPARENT\"\n },\n \"type\": \"ROW\",\n \"id\": \"ROW-f0b64094\",\n \"children\": [\n \"CHART-e8774b49\"\n ]\n },\n \"DASHBOARD_VERSION_KEY\": \"v2\"\n}\n \"\"\"",
")",
"pos",
"=",
"json",
".",
"loads",
"(",
"js",
")",
"# dashboard v2 doesn't allow add markup slice",
"dash",
".",
"slices",
"=",
"[",
"slc",
"for",
"slc",
"in",
"slices",
"if",
"slc",
".",
"viz_type",
"!=",
"'markup'",
"]",
"update_slice_ids",
"(",
"pos",
",",
"dash",
".",
"slices",
")",
"dash",
".",
"dashboard_title",
"=",
"'Births'",
"dash",
".",
"position_json",
"=",
"json",
".",
"dumps",
"(",
"pos",
",",
"indent",
"=",
"4",
")",
"dash",
".",
"slug",
"=",
"'births'",
"db",
".",
"session",
".",
"merge",
"(",
"dash",
")",
"db",
".",
"session",
".",
"commit",
"(",
")"
] |
Loading birth name dataset from a zip file in the repo
|
[
"Loading",
"birth",
"name",
"dataset",
"from",
"a",
"zip",
"file",
"in",
"the",
"repo"
] |
ca2996c78f679260eb79c6008e276733df5fb653
|
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/data/birth_names.py#L38-L622
|
train
|
apache/incubator-superset
|
superset/connectors/druid/views.py
|
Druid.refresh_datasources
|
def refresh_datasources(self, refreshAll=True):
"""endpoint that refreshes druid datasources metadata"""
session = db.session()
DruidCluster = ConnectorRegistry.sources['druid'].cluster_class
for cluster in session.query(DruidCluster).all():
cluster_name = cluster.cluster_name
valid_cluster = True
try:
cluster.refresh_datasources(refreshAll=refreshAll)
except Exception as e:
valid_cluster = False
flash(
"Error while processing cluster '{}'\n{}".format(
cluster_name, utils.error_msg_from_exception(e)),
'danger')
logging.exception(e)
pass
if valid_cluster:
cluster.metadata_last_refreshed = datetime.now()
flash(
_('Refreshed metadata from cluster [{}]').format(
cluster.cluster_name),
'info')
session.commit()
return redirect('/druiddatasourcemodelview/list/')
|
python
|
def refresh_datasources(self, refreshAll=True):
"""endpoint that refreshes druid datasources metadata"""
session = db.session()
DruidCluster = ConnectorRegistry.sources['druid'].cluster_class
for cluster in session.query(DruidCluster).all():
cluster_name = cluster.cluster_name
valid_cluster = True
try:
cluster.refresh_datasources(refreshAll=refreshAll)
except Exception as e:
valid_cluster = False
flash(
"Error while processing cluster '{}'\n{}".format(
cluster_name, utils.error_msg_from_exception(e)),
'danger')
logging.exception(e)
pass
if valid_cluster:
cluster.metadata_last_refreshed = datetime.now()
flash(
_('Refreshed metadata from cluster [{}]').format(
cluster.cluster_name),
'info')
session.commit()
return redirect('/druiddatasourcemodelview/list/')
|
[
"def",
"refresh_datasources",
"(",
"self",
",",
"refreshAll",
"=",
"True",
")",
":",
"session",
"=",
"db",
".",
"session",
"(",
")",
"DruidCluster",
"=",
"ConnectorRegistry",
".",
"sources",
"[",
"'druid'",
"]",
".",
"cluster_class",
"for",
"cluster",
"in",
"session",
".",
"query",
"(",
"DruidCluster",
")",
".",
"all",
"(",
")",
":",
"cluster_name",
"=",
"cluster",
".",
"cluster_name",
"valid_cluster",
"=",
"True",
"try",
":",
"cluster",
".",
"refresh_datasources",
"(",
"refreshAll",
"=",
"refreshAll",
")",
"except",
"Exception",
"as",
"e",
":",
"valid_cluster",
"=",
"False",
"flash",
"(",
"\"Error while processing cluster '{}'\\n{}\"",
".",
"format",
"(",
"cluster_name",
",",
"utils",
".",
"error_msg_from_exception",
"(",
"e",
")",
")",
",",
"'danger'",
")",
"logging",
".",
"exception",
"(",
"e",
")",
"pass",
"if",
"valid_cluster",
":",
"cluster",
".",
"metadata_last_refreshed",
"=",
"datetime",
".",
"now",
"(",
")",
"flash",
"(",
"_",
"(",
"'Refreshed metadata from cluster [{}]'",
")",
".",
"format",
"(",
"cluster",
".",
"cluster_name",
")",
",",
"'info'",
")",
"session",
".",
"commit",
"(",
")",
"return",
"redirect",
"(",
"'/druiddatasourcemodelview/list/'",
")"
] |
endpoint that refreshes druid datasources metadata
|
[
"endpoint",
"that",
"refreshes",
"druid",
"datasources",
"metadata"
] |
ca2996c78f679260eb79c6008e276733df5fb653
|
https://github.com/apache/incubator-superset/blob/ca2996c78f679260eb79c6008e276733df5fb653/superset/connectors/druid/views.py#L339-L363
|
train
|
keon/algorithms
|
algorithms/linkedlist/add_two_numbers.py
|
convert_to_list
|
def convert_to_list(number: int) -> Node:
"""
converts a positive integer into a (reversed) linked list.
for example: give 112
result 2 -> 1 -> 1
"""
if number >= 0:
head = Node(0)
current = head
remainder = number % 10
quotient = number // 10
while quotient != 0:
current.next = Node(remainder)
current = current.next
remainder = quotient % 10
quotient //= 10
current.next = Node(remainder)
return head.next
else:
print("number must be positive!")
|
python
|
def convert_to_list(number: int) -> Node:
"""
converts a positive integer into a (reversed) linked list.
for example: give 112
result 2 -> 1 -> 1
"""
if number >= 0:
head = Node(0)
current = head
remainder = number % 10
quotient = number // 10
while quotient != 0:
current.next = Node(remainder)
current = current.next
remainder = quotient % 10
quotient //= 10
current.next = Node(remainder)
return head.next
else:
print("number must be positive!")
|
[
"def",
"convert_to_list",
"(",
"number",
":",
"int",
")",
"->",
"Node",
":",
"if",
"number",
">=",
"0",
":",
"head",
"=",
"Node",
"(",
"0",
")",
"current",
"=",
"head",
"remainder",
"=",
"number",
"%",
"10",
"quotient",
"=",
"number",
"//",
"10",
"while",
"quotient",
"!=",
"0",
":",
"current",
".",
"next",
"=",
"Node",
"(",
"remainder",
")",
"current",
"=",
"current",
".",
"next",
"remainder",
"=",
"quotient",
"%",
"10",
"quotient",
"//=",
"10",
"current",
".",
"next",
"=",
"Node",
"(",
"remainder",
")",
"return",
"head",
".",
"next",
"else",
":",
"print",
"(",
"\"number must be positive!\"",
")"
] |
converts a positive integer into a (reversed) linked list.
for example: give 112
result 2 -> 1 -> 1
|
[
"converts",
"a",
"positive",
"integer",
"into",
"a",
"(",
"reversed",
")",
"linked",
"list",
".",
"for",
"example",
":",
"give",
"112",
"result",
"2",
"-",
">",
"1",
"-",
">",
"1"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/add_two_numbers.py#L43-L63
|
train
|
keon/algorithms
|
algorithms/linkedlist/add_two_numbers.py
|
convert_to_str
|
def convert_to_str(l: Node) -> str:
"""
converts the non-negative number list into a string.
"""
result = ""
while l:
result += str(l.val)
l = l.next
return result
|
python
|
def convert_to_str(l: Node) -> str:
"""
converts the non-negative number list into a string.
"""
result = ""
while l:
result += str(l.val)
l = l.next
return result
|
[
"def",
"convert_to_str",
"(",
"l",
":",
"Node",
")",
"->",
"str",
":",
"result",
"=",
"\"\"",
"while",
"l",
":",
"result",
"+=",
"str",
"(",
"l",
".",
"val",
")",
"l",
"=",
"l",
".",
"next",
"return",
"result"
] |
converts the non-negative number list into a string.
|
[
"converts",
"the",
"non",
"-",
"negative",
"number",
"list",
"into",
"a",
"string",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/add_two_numbers.py#L66-L74
|
train
|
keon/algorithms
|
algorithms/tree/longest_consecutive.py
|
longest_consecutive
|
def longest_consecutive(root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
max_len = 0
dfs(root, 0, root.val, max_len)
return max_len
|
python
|
def longest_consecutive(root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
max_len = 0
dfs(root, 0, root.val, max_len)
return max_len
|
[
"def",
"longest_consecutive",
"(",
"root",
")",
":",
"if",
"root",
"is",
"None",
":",
"return",
"0",
"max_len",
"=",
"0",
"dfs",
"(",
"root",
",",
"0",
",",
"root",
".",
"val",
",",
"max_len",
")",
"return",
"max_len"
] |
:type root: TreeNode
:rtype: int
|
[
":",
"type",
"root",
":",
"TreeNode",
":",
"rtype",
":",
"int"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/longest_consecutive.py#L28-L37
|
train
|
keon/algorithms
|
algorithms/arrays/three_sum.py
|
three_sum
|
def three_sum(array):
"""
:param array: List[int]
:return: Set[ Tuple[int, int, int] ]
"""
res = set()
array.sort()
for i in range(len(array) - 2):
if i > 0 and array[i] == array[i - 1]:
continue
l, r = i + 1, len(array) - 1
while l < r:
s = array[i] + array[l] + array[r]
if s > 0:
r -= 1
elif s < 0:
l += 1
else:
# found three sum
res.add((array[i], array[l], array[r]))
# remove duplicates
while l < r and array[l] == array[l + 1]:
l += 1
while l < r and array[r] == array[r - 1]:
r -= 1
l += 1
r -= 1
return res
|
python
|
def three_sum(array):
"""
:param array: List[int]
:return: Set[ Tuple[int, int, int] ]
"""
res = set()
array.sort()
for i in range(len(array) - 2):
if i > 0 and array[i] == array[i - 1]:
continue
l, r = i + 1, len(array) - 1
while l < r:
s = array[i] + array[l] + array[r]
if s > 0:
r -= 1
elif s < 0:
l += 1
else:
# found three sum
res.add((array[i], array[l], array[r]))
# remove duplicates
while l < r and array[l] == array[l + 1]:
l += 1
while l < r and array[r] == array[r - 1]:
r -= 1
l += 1
r -= 1
return res
|
[
"def",
"three_sum",
"(",
"array",
")",
":",
"res",
"=",
"set",
"(",
")",
"array",
".",
"sort",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"array",
")",
"-",
"2",
")",
":",
"if",
"i",
">",
"0",
"and",
"array",
"[",
"i",
"]",
"==",
"array",
"[",
"i",
"-",
"1",
"]",
":",
"continue",
"l",
",",
"r",
"=",
"i",
"+",
"1",
",",
"len",
"(",
"array",
")",
"-",
"1",
"while",
"l",
"<",
"r",
":",
"s",
"=",
"array",
"[",
"i",
"]",
"+",
"array",
"[",
"l",
"]",
"+",
"array",
"[",
"r",
"]",
"if",
"s",
">",
"0",
":",
"r",
"-=",
"1",
"elif",
"s",
"<",
"0",
":",
"l",
"+=",
"1",
"else",
":",
"# found three sum",
"res",
".",
"add",
"(",
"(",
"array",
"[",
"i",
"]",
",",
"array",
"[",
"l",
"]",
",",
"array",
"[",
"r",
"]",
")",
")",
"# remove duplicates",
"while",
"l",
"<",
"r",
"and",
"array",
"[",
"l",
"]",
"==",
"array",
"[",
"l",
"+",
"1",
"]",
":",
"l",
"+=",
"1",
"while",
"l",
"<",
"r",
"and",
"array",
"[",
"r",
"]",
"==",
"array",
"[",
"r",
"-",
"1",
"]",
":",
"r",
"-=",
"1",
"l",
"+=",
"1",
"r",
"-=",
"1",
"return",
"res"
] |
:param array: List[int]
:return: Set[ Tuple[int, int, int] ]
|
[
":",
"param",
"array",
":",
"List",
"[",
"int",
"]",
":",
"return",
":",
"Set",
"[",
"Tuple",
"[",
"int",
"int",
"int",
"]",
"]"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/three_sum.py#L18-L48
|
train
|
keon/algorithms
|
algorithms/sort/top_sort.py
|
top_sort_recursive
|
def top_sort_recursive(graph):
""" Time complexity is the same as DFS, which is O(V + E)
Space complexity: O(V)
"""
order, enter, state = [], set(graph), {}
def dfs(node):
state[node] = GRAY
#print(node)
for k in graph.get(node, ()):
sk = state.get(k, None)
if sk == GRAY:
raise ValueError("cycle")
if sk == BLACK:
continue
enter.discard(k)
dfs(k)
order.append(node)
state[node] = BLACK
while enter: dfs(enter.pop())
return order
|
python
|
def top_sort_recursive(graph):
""" Time complexity is the same as DFS, which is O(V + E)
Space complexity: O(V)
"""
order, enter, state = [], set(graph), {}
def dfs(node):
state[node] = GRAY
#print(node)
for k in graph.get(node, ()):
sk = state.get(k, None)
if sk == GRAY:
raise ValueError("cycle")
if sk == BLACK:
continue
enter.discard(k)
dfs(k)
order.append(node)
state[node] = BLACK
while enter: dfs(enter.pop())
return order
|
[
"def",
"top_sort_recursive",
"(",
"graph",
")",
":",
"order",
",",
"enter",
",",
"state",
"=",
"[",
"]",
",",
"set",
"(",
"graph",
")",
",",
"{",
"}",
"def",
"dfs",
"(",
"node",
")",
":",
"state",
"[",
"node",
"]",
"=",
"GRAY",
"#print(node)",
"for",
"k",
"in",
"graph",
".",
"get",
"(",
"node",
",",
"(",
")",
")",
":",
"sk",
"=",
"state",
".",
"get",
"(",
"k",
",",
"None",
")",
"if",
"sk",
"==",
"GRAY",
":",
"raise",
"ValueError",
"(",
"\"cycle\"",
")",
"if",
"sk",
"==",
"BLACK",
":",
"continue",
"enter",
".",
"discard",
"(",
"k",
")",
"dfs",
"(",
"k",
")",
"order",
".",
"append",
"(",
"node",
")",
"state",
"[",
"node",
"]",
"=",
"BLACK",
"while",
"enter",
":",
"dfs",
"(",
"enter",
".",
"pop",
"(",
")",
")",
"return",
"order"
] |
Time complexity is the same as DFS, which is O(V + E)
Space complexity: O(V)
|
[
"Time",
"complexity",
"is",
"the",
"same",
"as",
"DFS",
"which",
"is",
"O",
"(",
"V",
"+",
"E",
")",
"Space",
"complexity",
":",
"O",
"(",
"V",
")"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/top_sort.py#L3-L24
|
train
|
keon/algorithms
|
algorithms/sort/top_sort.py
|
top_sort
|
def top_sort(graph):
""" Time complexity is the same as DFS, which is O(V + E)
Space complexity: O(V)
"""
order, enter, state = [], set(graph), {}
def is_ready(node):
lst = graph.get(node, ())
if len(lst) == 0:
return True
for k in lst:
sk = state.get(k, None)
if sk == GRAY:
raise ValueError("cycle")
if sk != BLACK:
return False
return True
while enter:
node = enter.pop()
stack = []
while True:
state[node] = GRAY
stack.append(node)
for k in graph.get(node, ()):
sk = state.get(k, None)
if sk == GRAY:
raise ValueError("cycle")
if sk == BLACK:
continue
enter.discard(k)
stack.append(k)
while stack and is_ready(stack[-1]):
node = stack.pop()
order.append(node)
state[node] = BLACK
if len(stack) == 0:
break
node = stack.pop()
return order
|
python
|
def top_sort(graph):
""" Time complexity is the same as DFS, which is O(V + E)
Space complexity: O(V)
"""
order, enter, state = [], set(graph), {}
def is_ready(node):
lst = graph.get(node, ())
if len(lst) == 0:
return True
for k in lst:
sk = state.get(k, None)
if sk == GRAY:
raise ValueError("cycle")
if sk != BLACK:
return False
return True
while enter:
node = enter.pop()
stack = []
while True:
state[node] = GRAY
stack.append(node)
for k in graph.get(node, ()):
sk = state.get(k, None)
if sk == GRAY:
raise ValueError("cycle")
if sk == BLACK:
continue
enter.discard(k)
stack.append(k)
while stack and is_ready(stack[-1]):
node = stack.pop()
order.append(node)
state[node] = BLACK
if len(stack) == 0:
break
node = stack.pop()
return order
|
[
"def",
"top_sort",
"(",
"graph",
")",
":",
"order",
",",
"enter",
",",
"state",
"=",
"[",
"]",
",",
"set",
"(",
"graph",
")",
",",
"{",
"}",
"def",
"is_ready",
"(",
"node",
")",
":",
"lst",
"=",
"graph",
".",
"get",
"(",
"node",
",",
"(",
")",
")",
"if",
"len",
"(",
"lst",
")",
"==",
"0",
":",
"return",
"True",
"for",
"k",
"in",
"lst",
":",
"sk",
"=",
"state",
".",
"get",
"(",
"k",
",",
"None",
")",
"if",
"sk",
"==",
"GRAY",
":",
"raise",
"ValueError",
"(",
"\"cycle\"",
")",
"if",
"sk",
"!=",
"BLACK",
":",
"return",
"False",
"return",
"True",
"while",
"enter",
":",
"node",
"=",
"enter",
".",
"pop",
"(",
")",
"stack",
"=",
"[",
"]",
"while",
"True",
":",
"state",
"[",
"node",
"]",
"=",
"GRAY",
"stack",
".",
"append",
"(",
"node",
")",
"for",
"k",
"in",
"graph",
".",
"get",
"(",
"node",
",",
"(",
")",
")",
":",
"sk",
"=",
"state",
".",
"get",
"(",
"k",
",",
"None",
")",
"if",
"sk",
"==",
"GRAY",
":",
"raise",
"ValueError",
"(",
"\"cycle\"",
")",
"if",
"sk",
"==",
"BLACK",
":",
"continue",
"enter",
".",
"discard",
"(",
"k",
")",
"stack",
".",
"append",
"(",
"k",
")",
"while",
"stack",
"and",
"is_ready",
"(",
"stack",
"[",
"-",
"1",
"]",
")",
":",
"node",
"=",
"stack",
".",
"pop",
"(",
")",
"order",
".",
"append",
"(",
"node",
")",
"state",
"[",
"node",
"]",
"=",
"BLACK",
"if",
"len",
"(",
"stack",
")",
"==",
"0",
":",
"break",
"node",
"=",
"stack",
".",
"pop",
"(",
")",
"return",
"order"
] |
Time complexity is the same as DFS, which is O(V + E)
Space complexity: O(V)
|
[
"Time",
"complexity",
"is",
"the",
"same",
"as",
"DFS",
"which",
"is",
"O",
"(",
"V",
"+",
"E",
")",
"Space",
"complexity",
":",
"O",
"(",
"V",
")"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/top_sort.py#L26-L66
|
train
|
keon/algorithms
|
algorithms/dp/max_product_subarray.py
|
max_product
|
def max_product(nums):
"""
:type nums: List[int]
:rtype: int
"""
lmin = lmax = gmax = nums[0]
for i in range(len(nums)):
t1 = nums[i] * lmax
t2 = nums[i] * lmin
lmax = max(max(t1, t2), nums[i])
lmin = min(min(t1, t2), nums[i])
gmax = max(gmax, lmax)
|
python
|
def max_product(nums):
"""
:type nums: List[int]
:rtype: int
"""
lmin = lmax = gmax = nums[0]
for i in range(len(nums)):
t1 = nums[i] * lmax
t2 = nums[i] * lmin
lmax = max(max(t1, t2), nums[i])
lmin = min(min(t1, t2), nums[i])
gmax = max(gmax, lmax)
|
[
"def",
"max_product",
"(",
"nums",
")",
":",
"lmin",
"=",
"lmax",
"=",
"gmax",
"=",
"nums",
"[",
"0",
"]",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"nums",
")",
")",
":",
"t1",
"=",
"nums",
"[",
"i",
"]",
"*",
"lmax",
"t2",
"=",
"nums",
"[",
"i",
"]",
"*",
"lmin",
"lmax",
"=",
"max",
"(",
"max",
"(",
"t1",
",",
"t2",
")",
",",
"nums",
"[",
"i",
"]",
")",
"lmin",
"=",
"min",
"(",
"min",
"(",
"t1",
",",
"t2",
")",
",",
"nums",
"[",
"i",
"]",
")",
"gmax",
"=",
"max",
"(",
"gmax",
",",
"lmax",
")"
] |
:type nums: List[int]
:rtype: int
|
[
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"int"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/max_product_subarray.py#L11-L22
|
train
|
keon/algorithms
|
algorithms/dp/max_product_subarray.py
|
subarray_with_max_product
|
def subarray_with_max_product(arr):
''' arr is list of positive/negative numbers '''
l = len(arr)
product_so_far = max_product_end = 1
max_start_i = 0
so_far_start_i = so_far_end_i = 0
all_negative_flag = True
for i in range(l):
max_product_end *= arr[i]
if arr[i] > 0:
all_negative_flag = False
if max_product_end <= 0:
max_product_end = arr[i]
max_start_i = i
if product_so_far <= max_product_end:
product_so_far = max_product_end
so_far_end_i = i
so_far_start_i = max_start_i
if all_negative_flag:
print("max_product_so_far: %s, %s" %
(reduce(lambda x, y: x * y, arr), arr))
else:
print("max_product_so_far: %s, %s" %
(product_so_far, arr[so_far_start_i:so_far_end_i + 1]))
|
python
|
def subarray_with_max_product(arr):
''' arr is list of positive/negative numbers '''
l = len(arr)
product_so_far = max_product_end = 1
max_start_i = 0
so_far_start_i = so_far_end_i = 0
all_negative_flag = True
for i in range(l):
max_product_end *= arr[i]
if arr[i] > 0:
all_negative_flag = False
if max_product_end <= 0:
max_product_end = arr[i]
max_start_i = i
if product_so_far <= max_product_end:
product_so_far = max_product_end
so_far_end_i = i
so_far_start_i = max_start_i
if all_negative_flag:
print("max_product_so_far: %s, %s" %
(reduce(lambda x, y: x * y, arr), arr))
else:
print("max_product_so_far: %s, %s" %
(product_so_far, arr[so_far_start_i:so_far_end_i + 1]))
|
[
"def",
"subarray_with_max_product",
"(",
"arr",
")",
":",
"l",
"=",
"len",
"(",
"arr",
")",
"product_so_far",
"=",
"max_product_end",
"=",
"1",
"max_start_i",
"=",
"0",
"so_far_start_i",
"=",
"so_far_end_i",
"=",
"0",
"all_negative_flag",
"=",
"True",
"for",
"i",
"in",
"range",
"(",
"l",
")",
":",
"max_product_end",
"*=",
"arr",
"[",
"i",
"]",
"if",
"arr",
"[",
"i",
"]",
">",
"0",
":",
"all_negative_flag",
"=",
"False",
"if",
"max_product_end",
"<=",
"0",
":",
"max_product_end",
"=",
"arr",
"[",
"i",
"]",
"max_start_i",
"=",
"i",
"if",
"product_so_far",
"<=",
"max_product_end",
":",
"product_so_far",
"=",
"max_product_end",
"so_far_end_i",
"=",
"i",
"so_far_start_i",
"=",
"max_start_i",
"if",
"all_negative_flag",
":",
"print",
"(",
"\"max_product_so_far: %s, %s\"",
"%",
"(",
"reduce",
"(",
"lambda",
"x",
",",
"y",
":",
"x",
"*",
"y",
",",
"arr",
")",
",",
"arr",
")",
")",
"else",
":",
"print",
"(",
"\"max_product_so_far: %s, %s\"",
"%",
"(",
"product_so_far",
",",
"arr",
"[",
"so_far_start_i",
":",
"so_far_end_i",
"+",
"1",
"]",
")",
")"
] |
arr is list of positive/negative numbers
|
[
"arr",
"is",
"list",
"of",
"positive",
"/",
"negative",
"numbers"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/max_product_subarray.py#L40-L67
|
train
|
keon/algorithms
|
algorithms/strings/text_justification.py
|
text_justification
|
def text_justification(words, max_width):
'''
:type words: list
:type max_width: int
:rtype: list
'''
ret = [] # return value
row_len = 0 # current length of strs in a row
row_words = [] # current words in a row
index = 0 # the index of current word in words
is_first_word = True # is current word the first in a row
while index < len(words):
while row_len <= max_width and index < len(words):
if len(words[index]) > max_width:
raise ValueError("there exists word whose length is larger than max_width")
tmp = row_len
row_words.append(words[index])
tmp += len(words[index])
if not is_first_word:
tmp += 1 # except for the first word, each word should have at least a ' ' before it.
if tmp > max_width:
row_words.pop()
break
row_len = tmp
index += 1
is_first_word = False
# here we have already got a row of str , then we should supplement enough ' ' to make sure the length is max_width.
row = ""
# if the row is the last
if index == len(words):
for word in row_words:
row += (word + ' ')
row = row[:-1]
row += ' ' * (max_width - len(row))
# not the last row and more than one word
elif len(row_words) != 1:
space_num = max_width - row_len
space_num_of_each_interval = space_num // (len(row_words) - 1)
space_num_rest = space_num - space_num_of_each_interval * (len(row_words) - 1)
for j in range(len(row_words)):
row += row_words[j]
if j != len(row_words) - 1:
row += ' ' * (1 + space_num_of_each_interval)
if space_num_rest > 0:
row += ' '
space_num_rest -= 1
# row with only one word
else:
row += row_words[0]
row += ' ' * (max_width - len(row))
ret.append(row)
# after a row , reset those value
row_len = 0
row_words = []
is_first_word = True
return ret
|
python
|
def text_justification(words, max_width):
'''
:type words: list
:type max_width: int
:rtype: list
'''
ret = [] # return value
row_len = 0 # current length of strs in a row
row_words = [] # current words in a row
index = 0 # the index of current word in words
is_first_word = True # is current word the first in a row
while index < len(words):
while row_len <= max_width and index < len(words):
if len(words[index]) > max_width:
raise ValueError("there exists word whose length is larger than max_width")
tmp = row_len
row_words.append(words[index])
tmp += len(words[index])
if not is_first_word:
tmp += 1 # except for the first word, each word should have at least a ' ' before it.
if tmp > max_width:
row_words.pop()
break
row_len = tmp
index += 1
is_first_word = False
# here we have already got a row of str , then we should supplement enough ' ' to make sure the length is max_width.
row = ""
# if the row is the last
if index == len(words):
for word in row_words:
row += (word + ' ')
row = row[:-1]
row += ' ' * (max_width - len(row))
# not the last row and more than one word
elif len(row_words) != 1:
space_num = max_width - row_len
space_num_of_each_interval = space_num // (len(row_words) - 1)
space_num_rest = space_num - space_num_of_each_interval * (len(row_words) - 1)
for j in range(len(row_words)):
row += row_words[j]
if j != len(row_words) - 1:
row += ' ' * (1 + space_num_of_each_interval)
if space_num_rest > 0:
row += ' '
space_num_rest -= 1
# row with only one word
else:
row += row_words[0]
row += ' ' * (max_width - len(row))
ret.append(row)
# after a row , reset those value
row_len = 0
row_words = []
is_first_word = True
return ret
|
[
"def",
"text_justification",
"(",
"words",
",",
"max_width",
")",
":",
"ret",
"=",
"[",
"]",
"# return value",
"row_len",
"=",
"0",
"# current length of strs in a row",
"row_words",
"=",
"[",
"]",
"# current words in a row",
"index",
"=",
"0",
"# the index of current word in words",
"is_first_word",
"=",
"True",
"# is current word the first in a row",
"while",
"index",
"<",
"len",
"(",
"words",
")",
":",
"while",
"row_len",
"<=",
"max_width",
"and",
"index",
"<",
"len",
"(",
"words",
")",
":",
"if",
"len",
"(",
"words",
"[",
"index",
"]",
")",
">",
"max_width",
":",
"raise",
"ValueError",
"(",
"\"there exists word whose length is larger than max_width\"",
")",
"tmp",
"=",
"row_len",
"row_words",
".",
"append",
"(",
"words",
"[",
"index",
"]",
")",
"tmp",
"+=",
"len",
"(",
"words",
"[",
"index",
"]",
")",
"if",
"not",
"is_first_word",
":",
"tmp",
"+=",
"1",
"# except for the first word, each word should have at least a ' ' before it.",
"if",
"tmp",
">",
"max_width",
":",
"row_words",
".",
"pop",
"(",
")",
"break",
"row_len",
"=",
"tmp",
"index",
"+=",
"1",
"is_first_word",
"=",
"False",
"# here we have already got a row of str , then we should supplement enough ' ' to make sure the length is max_width.",
"row",
"=",
"\"\"",
"# if the row is the last",
"if",
"index",
"==",
"len",
"(",
"words",
")",
":",
"for",
"word",
"in",
"row_words",
":",
"row",
"+=",
"(",
"word",
"+",
"' '",
")",
"row",
"=",
"row",
"[",
":",
"-",
"1",
"]",
"row",
"+=",
"' '",
"*",
"(",
"max_width",
"-",
"len",
"(",
"row",
")",
")",
"# not the last row and more than one word",
"elif",
"len",
"(",
"row_words",
")",
"!=",
"1",
":",
"space_num",
"=",
"max_width",
"-",
"row_len",
"space_num_of_each_interval",
"=",
"space_num",
"//",
"(",
"len",
"(",
"row_words",
")",
"-",
"1",
")",
"space_num_rest",
"=",
"space_num",
"-",
"space_num_of_each_interval",
"*",
"(",
"len",
"(",
"row_words",
")",
"-",
"1",
")",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"row_words",
")",
")",
":",
"row",
"+=",
"row_words",
"[",
"j",
"]",
"if",
"j",
"!=",
"len",
"(",
"row_words",
")",
"-",
"1",
":",
"row",
"+=",
"' '",
"*",
"(",
"1",
"+",
"space_num_of_each_interval",
")",
"if",
"space_num_rest",
">",
"0",
":",
"row",
"+=",
"' '",
"space_num_rest",
"-=",
"1",
"# row with only one word",
"else",
":",
"row",
"+=",
"row_words",
"[",
"0",
"]",
"row",
"+=",
"' '",
"*",
"(",
"max_width",
"-",
"len",
"(",
"row",
")",
")",
"ret",
".",
"append",
"(",
"row",
")",
"# after a row , reset those value",
"row_len",
"=",
"0",
"row_words",
"=",
"[",
"]",
"is_first_word",
"=",
"True",
"return",
"ret"
] |
:type words: list
:type max_width: int
:rtype: list
|
[
":",
"type",
"words",
":",
"list",
":",
"type",
"max_width",
":",
"int",
":",
"rtype",
":",
"list"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/text_justification.py#L34-L89
|
train
|
keon/algorithms
|
algorithms/sort/insertion_sort.py
|
insertion_sort
|
def insertion_sort(arr, simulation=False):
""" Insertion Sort
Complexity: O(n^2)
"""
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
for i in range(len(arr)):
cursor = arr[i]
pos = i
while pos > 0 and arr[pos - 1] > cursor:
# Swap the number down the list
arr[pos] = arr[pos - 1]
pos = pos - 1
# Break and do the final swap
arr[pos] = cursor
if simulation:
iteration = iteration + 1
print("iteration",iteration,":",*arr)
return arr
|
python
|
def insertion_sort(arr, simulation=False):
""" Insertion Sort
Complexity: O(n^2)
"""
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
for i in range(len(arr)):
cursor = arr[i]
pos = i
while pos > 0 and arr[pos - 1] > cursor:
# Swap the number down the list
arr[pos] = arr[pos - 1]
pos = pos - 1
# Break and do the final swap
arr[pos] = cursor
if simulation:
iteration = iteration + 1
print("iteration",iteration,":",*arr)
return arr
|
[
"def",
"insertion_sort",
"(",
"arr",
",",
"simulation",
"=",
"False",
")",
":",
"iteration",
"=",
"0",
"if",
"simulation",
":",
"print",
"(",
"\"iteration\"",
",",
"iteration",
",",
"\":\"",
",",
"*",
"arr",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"arr",
")",
")",
":",
"cursor",
"=",
"arr",
"[",
"i",
"]",
"pos",
"=",
"i",
"while",
"pos",
">",
"0",
"and",
"arr",
"[",
"pos",
"-",
"1",
"]",
">",
"cursor",
":",
"# Swap the number down the list",
"arr",
"[",
"pos",
"]",
"=",
"arr",
"[",
"pos",
"-",
"1",
"]",
"pos",
"=",
"pos",
"-",
"1",
"# Break and do the final swap",
"arr",
"[",
"pos",
"]",
"=",
"cursor",
"if",
"simulation",
":",
"iteration",
"=",
"iteration",
"+",
"1",
"print",
"(",
"\"iteration\"",
",",
"iteration",
",",
"\":\"",
",",
"*",
"arr",
")",
"return",
"arr"
] |
Insertion Sort
Complexity: O(n^2)
|
[
"Insertion",
"Sort",
"Complexity",
":",
"O",
"(",
"n^2",
")"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/insertion_sort.py#L1-L25
|
train
|
keon/algorithms
|
algorithms/sort/cycle_sort.py
|
cycle_sort
|
def cycle_sort(arr):
"""
cycle_sort
This is based on the idea that the permutations to be sorted
can be decomposed into cycles,
and the results can be individually sorted by cycling.
reference: https://en.wikipedia.org/wiki/Cycle_sort
Average time complexity : O(N^2)
Worst case time complexity : O(N^2)
"""
len_arr = len(arr)
# Finding cycle to rotate.
for cur in range(len_arr - 1):
item = arr[cur]
# Finding an indx to put items in.
index = cur
for i in range(cur + 1, len_arr):
if arr[i] < item:
index += 1
# Case of there is not a cycle
if index == cur:
continue
# Putting the item immediately right after the duplicate item or on the right.
while item == arr[index]:
index += 1
arr[index], item = item, arr[index]
# Rotating the remaining cycle.
while index != cur:
# Finding where to put the item.
index = cur
for i in range(cur + 1, len_arr):
if arr[i] < item:
index += 1
# After item is duplicated, put it in place or put it there.
while item == arr[index]:
index += 1
arr[index], item = item, arr[index]
return arr
|
python
|
def cycle_sort(arr):
"""
cycle_sort
This is based on the idea that the permutations to be sorted
can be decomposed into cycles,
and the results can be individually sorted by cycling.
reference: https://en.wikipedia.org/wiki/Cycle_sort
Average time complexity : O(N^2)
Worst case time complexity : O(N^2)
"""
len_arr = len(arr)
# Finding cycle to rotate.
for cur in range(len_arr - 1):
item = arr[cur]
# Finding an indx to put items in.
index = cur
for i in range(cur + 1, len_arr):
if arr[i] < item:
index += 1
# Case of there is not a cycle
if index == cur:
continue
# Putting the item immediately right after the duplicate item or on the right.
while item == arr[index]:
index += 1
arr[index], item = item, arr[index]
# Rotating the remaining cycle.
while index != cur:
# Finding where to put the item.
index = cur
for i in range(cur + 1, len_arr):
if arr[i] < item:
index += 1
# After item is duplicated, put it in place or put it there.
while item == arr[index]:
index += 1
arr[index], item = item, arr[index]
return arr
|
[
"def",
"cycle_sort",
"(",
"arr",
")",
":",
"len_arr",
"=",
"len",
"(",
"arr",
")",
"# Finding cycle to rotate.",
"for",
"cur",
"in",
"range",
"(",
"len_arr",
"-",
"1",
")",
":",
"item",
"=",
"arr",
"[",
"cur",
"]",
"# Finding an indx to put items in.",
"index",
"=",
"cur",
"for",
"i",
"in",
"range",
"(",
"cur",
"+",
"1",
",",
"len_arr",
")",
":",
"if",
"arr",
"[",
"i",
"]",
"<",
"item",
":",
"index",
"+=",
"1",
"# Case of there is not a cycle",
"if",
"index",
"==",
"cur",
":",
"continue",
"# Putting the item immediately right after the duplicate item or on the right.",
"while",
"item",
"==",
"arr",
"[",
"index",
"]",
":",
"index",
"+=",
"1",
"arr",
"[",
"index",
"]",
",",
"item",
"=",
"item",
",",
"arr",
"[",
"index",
"]",
"# Rotating the remaining cycle.",
"while",
"index",
"!=",
"cur",
":",
"# Finding where to put the item.",
"index",
"=",
"cur",
"for",
"i",
"in",
"range",
"(",
"cur",
"+",
"1",
",",
"len_arr",
")",
":",
"if",
"arr",
"[",
"i",
"]",
"<",
"item",
":",
"index",
"+=",
"1",
"# After item is duplicated, put it in place or put it there.",
"while",
"item",
"==",
"arr",
"[",
"index",
"]",
":",
"index",
"+=",
"1",
"arr",
"[",
"index",
"]",
",",
"item",
"=",
"item",
",",
"arr",
"[",
"index",
"]",
"return",
"arr"
] |
cycle_sort
This is based on the idea that the permutations to be sorted
can be decomposed into cycles,
and the results can be individually sorted by cycling.
reference: https://en.wikipedia.org/wiki/Cycle_sort
Average time complexity : O(N^2)
Worst case time complexity : O(N^2)
|
[
"cycle_sort",
"This",
"is",
"based",
"on",
"the",
"idea",
"that",
"the",
"permutations",
"to",
"be",
"sorted",
"can",
"be",
"decomposed",
"into",
"cycles",
"and",
"the",
"results",
"can",
"be",
"individually",
"sorted",
"by",
"cycling",
".",
"reference",
":",
"https",
":",
"//",
"en",
".",
"wikipedia",
".",
"org",
"/",
"wiki",
"/",
"Cycle_sort",
"Average",
"time",
"complexity",
":",
"O",
"(",
"N^2",
")",
"Worst",
"case",
"time",
"complexity",
":",
"O",
"(",
"N^2",
")"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/cycle_sort.py#L1-L46
|
train
|
keon/algorithms
|
algorithms/sort/cocktail_shaker_sort.py
|
cocktail_shaker_sort
|
def cocktail_shaker_sort(arr):
"""
Cocktail_shaker_sort
Sorting a given array
mutation of bubble sort
reference: https://en.wikipedia.org/wiki/Cocktail_shaker_sort
Worst-case performance: O(N^2)
"""
def swap(i, j):
arr[i], arr[j] = arr[j], arr[i]
n = len(arr)
swapped = True
while swapped:
swapped = False
for i in range(1, n):
if arr[i - 1] > arr[i]:
swap(i - 1, i)
swapped = True
if swapped == False:
return arr
swapped = False
for i in range(n-1,0,-1):
if arr[i - 1] > arr[i]:
swap(i - 1, i)
swapped = True
return arr
|
python
|
def cocktail_shaker_sort(arr):
"""
Cocktail_shaker_sort
Sorting a given array
mutation of bubble sort
reference: https://en.wikipedia.org/wiki/Cocktail_shaker_sort
Worst-case performance: O(N^2)
"""
def swap(i, j):
arr[i], arr[j] = arr[j], arr[i]
n = len(arr)
swapped = True
while swapped:
swapped = False
for i in range(1, n):
if arr[i - 1] > arr[i]:
swap(i - 1, i)
swapped = True
if swapped == False:
return arr
swapped = False
for i in range(n-1,0,-1):
if arr[i - 1] > arr[i]:
swap(i - 1, i)
swapped = True
return arr
|
[
"def",
"cocktail_shaker_sort",
"(",
"arr",
")",
":",
"def",
"swap",
"(",
"i",
",",
"j",
")",
":",
"arr",
"[",
"i",
"]",
",",
"arr",
"[",
"j",
"]",
"=",
"arr",
"[",
"j",
"]",
",",
"arr",
"[",
"i",
"]",
"n",
"=",
"len",
"(",
"arr",
")",
"swapped",
"=",
"True",
"while",
"swapped",
":",
"swapped",
"=",
"False",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"n",
")",
":",
"if",
"arr",
"[",
"i",
"-",
"1",
"]",
">",
"arr",
"[",
"i",
"]",
":",
"swap",
"(",
"i",
"-",
"1",
",",
"i",
")",
"swapped",
"=",
"True",
"if",
"swapped",
"==",
"False",
":",
"return",
"arr",
"swapped",
"=",
"False",
"for",
"i",
"in",
"range",
"(",
"n",
"-",
"1",
",",
"0",
",",
"-",
"1",
")",
":",
"if",
"arr",
"[",
"i",
"-",
"1",
"]",
">",
"arr",
"[",
"i",
"]",
":",
"swap",
"(",
"i",
"-",
"1",
",",
"i",
")",
"swapped",
"=",
"True",
"return",
"arr"
] |
Cocktail_shaker_sort
Sorting a given array
mutation of bubble sort
reference: https://en.wikipedia.org/wiki/Cocktail_shaker_sort
Worst-case performance: O(N^2)
|
[
"Cocktail_shaker_sort",
"Sorting",
"a",
"given",
"array",
"mutation",
"of",
"bubble",
"sort"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/cocktail_shaker_sort.py#L1-L30
|
train
|
keon/algorithms
|
algorithms/queues/reconstruct_queue.py
|
reconstruct_queue
|
def reconstruct_queue(people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
queue = []
people.sort(key=lambda x: (-x[0], x[1]))
for h, k in people:
queue.insert(k, [h, k])
return queue
|
python
|
def reconstruct_queue(people):
"""
:type people: List[List[int]]
:rtype: List[List[int]]
"""
queue = []
people.sort(key=lambda x: (-x[0], x[1]))
for h, k in people:
queue.insert(k, [h, k])
return queue
|
[
"def",
"reconstruct_queue",
"(",
"people",
")",
":",
"queue",
"=",
"[",
"]",
"people",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"(",
"-",
"x",
"[",
"0",
"]",
",",
"x",
"[",
"1",
"]",
")",
")",
"for",
"h",
",",
"k",
"in",
"people",
":",
"queue",
".",
"insert",
"(",
"k",
",",
"[",
"h",
",",
"k",
"]",
")",
"return",
"queue"
] |
:type people: List[List[int]]
:rtype: List[List[int]]
|
[
":",
"type",
"people",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"rtype",
":",
"List",
"[",
"List",
"[",
"int",
"]]"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/queues/reconstruct_queue.py#L18-L27
|
train
|
keon/algorithms
|
algorithms/tree/min_height.py
|
min_depth
|
def min_depth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
if root.left is not None or root.right is not None:
return max(self.minDepth(root.left), self.minDepth(root.right))+1
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
|
python
|
def min_depth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
if root.left is not None or root.right is not None:
return max(self.minDepth(root.left), self.minDepth(root.right))+1
return min(self.minDepth(root.left), self.minDepth(root.right)) + 1
|
[
"def",
"min_depth",
"(",
"self",
",",
"root",
")",
":",
"if",
"root",
"is",
"None",
":",
"return",
"0",
"if",
"root",
".",
"left",
"is",
"not",
"None",
"or",
"root",
".",
"right",
"is",
"not",
"None",
":",
"return",
"max",
"(",
"self",
".",
"minDepth",
"(",
"root",
".",
"left",
")",
",",
"self",
".",
"minDepth",
"(",
"root",
".",
"right",
")",
")",
"+",
"1",
"return",
"min",
"(",
"self",
".",
"minDepth",
"(",
"root",
".",
"left",
")",
",",
"self",
".",
"minDepth",
"(",
"root",
".",
"right",
")",
")",
"+",
"1"
] |
:type root: TreeNode
:rtype: int
|
[
":",
"type",
"root",
":",
"TreeNode",
":",
"rtype",
":",
"int"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/min_height.py#L4-L13
|
train
|
keon/algorithms
|
algorithms/strings/one_edit_distance.py
|
is_one_edit
|
def is_one_edit(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) > len(t):
return is_one_edit(t, s)
if len(t) - len(s) > 1 or t == s:
return False
for i in range(len(s)):
if s[i] != t[i]:
return s[i+1:] == t[i+1:] or s[i:] == t[i+1:]
return True
|
python
|
def is_one_edit(s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
if len(s) > len(t):
return is_one_edit(t, s)
if len(t) - len(s) > 1 or t == s:
return False
for i in range(len(s)):
if s[i] != t[i]:
return s[i+1:] == t[i+1:] or s[i:] == t[i+1:]
return True
|
[
"def",
"is_one_edit",
"(",
"s",
",",
"t",
")",
":",
"if",
"len",
"(",
"s",
")",
">",
"len",
"(",
"t",
")",
":",
"return",
"is_one_edit",
"(",
"t",
",",
"s",
")",
"if",
"len",
"(",
"t",
")",
"-",
"len",
"(",
"s",
")",
">",
"1",
"or",
"t",
"==",
"s",
":",
"return",
"False",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"s",
")",
")",
":",
"if",
"s",
"[",
"i",
"]",
"!=",
"t",
"[",
"i",
"]",
":",
"return",
"s",
"[",
"i",
"+",
"1",
":",
"]",
"==",
"t",
"[",
"i",
"+",
"1",
":",
"]",
"or",
"s",
"[",
"i",
":",
"]",
"==",
"t",
"[",
"i",
"+",
"1",
":",
"]",
"return",
"True"
] |
:type s: str
:type t: str
:rtype: bool
|
[
":",
"type",
"s",
":",
"str",
":",
"type",
"t",
":",
"str",
":",
"rtype",
":",
"bool"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/one_edit_distance.py#L6-L19
|
train
|
keon/algorithms
|
algorithms/sort/shell_sort.py
|
shell_sort
|
def shell_sort(arr):
''' Shell Sort
Complexity: O(n^2)
'''
n = len(arr)
# Initialize size of the gap
gap = n//2
while gap > 0:
y_index = gap
while y_index < len(arr):
y = arr[y_index]
x_index = y_index - gap
while x_index >= 0 and y < arr[x_index]:
arr[x_index + gap] = arr[x_index]
x_index = x_index - gap
arr[x_index + gap] = y
y_index = y_index + 1
gap = gap//2
return arr
|
python
|
def shell_sort(arr):
''' Shell Sort
Complexity: O(n^2)
'''
n = len(arr)
# Initialize size of the gap
gap = n//2
while gap > 0:
y_index = gap
while y_index < len(arr):
y = arr[y_index]
x_index = y_index - gap
while x_index >= 0 and y < arr[x_index]:
arr[x_index + gap] = arr[x_index]
x_index = x_index - gap
arr[x_index + gap] = y
y_index = y_index + 1
gap = gap//2
return arr
|
[
"def",
"shell_sort",
"(",
"arr",
")",
":",
"n",
"=",
"len",
"(",
"arr",
")",
"# Initialize size of the gap",
"gap",
"=",
"n",
"//",
"2",
"while",
"gap",
">",
"0",
":",
"y_index",
"=",
"gap",
"while",
"y_index",
"<",
"len",
"(",
"arr",
")",
":",
"y",
"=",
"arr",
"[",
"y_index",
"]",
"x_index",
"=",
"y_index",
"-",
"gap",
"while",
"x_index",
">=",
"0",
"and",
"y",
"<",
"arr",
"[",
"x_index",
"]",
":",
"arr",
"[",
"x_index",
"+",
"gap",
"]",
"=",
"arr",
"[",
"x_index",
"]",
"x_index",
"=",
"x_index",
"-",
"gap",
"arr",
"[",
"x_index",
"+",
"gap",
"]",
"=",
"y",
"y_index",
"=",
"y_index",
"+",
"1",
"gap",
"=",
"gap",
"//",
"2",
"return",
"arr"
] |
Shell Sort
Complexity: O(n^2)
|
[
"Shell",
"Sort",
"Complexity",
":",
"O",
"(",
"n^2",
")"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/shell_sort.py#L1-L21
|
train
|
keon/algorithms
|
algorithms/strings/longest_common_prefix.py
|
common_prefix
|
def common_prefix(s1, s2):
"Return prefix common of 2 strings"
if not s1 or not s2:
return ""
k = 0
while s1[k] == s2[k]:
k = k + 1
if k >= len(s1) or k >= len(s2):
return s1[0:k]
return s1[0:k]
|
python
|
def common_prefix(s1, s2):
"Return prefix common of 2 strings"
if not s1 or not s2:
return ""
k = 0
while s1[k] == s2[k]:
k = k + 1
if k >= len(s1) or k >= len(s2):
return s1[0:k]
return s1[0:k]
|
[
"def",
"common_prefix",
"(",
"s1",
",",
"s2",
")",
":",
"if",
"not",
"s1",
"or",
"not",
"s2",
":",
"return",
"\"\"",
"k",
"=",
"0",
"while",
"s1",
"[",
"k",
"]",
"==",
"s2",
"[",
"k",
"]",
":",
"k",
"=",
"k",
"+",
"1",
"if",
"k",
">=",
"len",
"(",
"s1",
")",
"or",
"k",
">=",
"len",
"(",
"s2",
")",
":",
"return",
"s1",
"[",
"0",
":",
"k",
"]",
"return",
"s1",
"[",
"0",
":",
"k",
"]"
] |
Return prefix common of 2 strings
|
[
"Return",
"prefix",
"common",
"of",
"2",
"strings"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/longest_common_prefix.py#L21-L30
|
train
|
keon/algorithms
|
algorithms/maths/euler_totient.py
|
euler_totient
|
def euler_totient(n):
"""Euler's totient function or Phi function.
Time Complexity: O(sqrt(n))."""
result = n;
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
while n % i == 0:
n //= i
result -= result // i
if n > 1:
result -= result // n;
return result;
|
python
|
def euler_totient(n):
"""Euler's totient function or Phi function.
Time Complexity: O(sqrt(n))."""
result = n;
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
while n % i == 0:
n //= i
result -= result // i
if n > 1:
result -= result // n;
return result;
|
[
"def",
"euler_totient",
"(",
"n",
")",
":",
"result",
"=",
"n",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"int",
"(",
"n",
"**",
"0.5",
")",
"+",
"1",
")",
":",
"if",
"n",
"%",
"i",
"==",
"0",
":",
"while",
"n",
"%",
"i",
"==",
"0",
":",
"n",
"//=",
"i",
"result",
"-=",
"result",
"//",
"i",
"if",
"n",
">",
"1",
":",
"result",
"-=",
"result",
"//",
"n",
"return",
"result"
] |
Euler's totient function or Phi function.
Time Complexity: O(sqrt(n)).
|
[
"Euler",
"s",
"totient",
"function",
"or",
"Phi",
"function",
".",
"Time",
"Complexity",
":",
"O",
"(",
"sqrt",
"(",
"n",
"))",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/euler_totient.py#L7-L18
|
train
|
keon/algorithms
|
algorithms/linkedlist/is_palindrome.py
|
is_palindrome_dict
|
def is_palindrome_dict(head):
"""
This function builds up a dictionary where the keys are the values of the list,
and the values are the positions at which these values occur in the list.
We then iterate over the dict and if there is more than one key with an odd
number of occurrences, bail out and return False.
Otherwise, we want to ensure that the positions of occurrence sum to the
value of the length of the list - 1, working from the outside of the list inward.
For example:
Input: 1 -> 1 -> 2 -> 3 -> 2 -> 1 -> 1
d = {1: [0,1,5,6], 2: [2,4], 3: [3]}
'3' is the middle outlier, 2+4=6, 0+6=6 and 5+1=6 so we have a palindrome.
"""
if not head or not head.next:
return True
d = {}
pos = 0
while head:
if head.val in d.keys():
d[head.val].append(pos)
else:
d[head.val] = [pos]
head = head.next
pos += 1
checksum = pos - 1
middle = 0
for v in d.values():
if len(v) % 2 != 0:
middle += 1
else:
step = 0
for i in range(0, len(v)):
if v[i] + v[len(v) - 1 - step] != checksum:
return False
step += 1
if middle > 1:
return False
return True
|
python
|
def is_palindrome_dict(head):
"""
This function builds up a dictionary where the keys are the values of the list,
and the values are the positions at which these values occur in the list.
We then iterate over the dict and if there is more than one key with an odd
number of occurrences, bail out and return False.
Otherwise, we want to ensure that the positions of occurrence sum to the
value of the length of the list - 1, working from the outside of the list inward.
For example:
Input: 1 -> 1 -> 2 -> 3 -> 2 -> 1 -> 1
d = {1: [0,1,5,6], 2: [2,4], 3: [3]}
'3' is the middle outlier, 2+4=6, 0+6=6 and 5+1=6 so we have a palindrome.
"""
if not head or not head.next:
return True
d = {}
pos = 0
while head:
if head.val in d.keys():
d[head.val].append(pos)
else:
d[head.val] = [pos]
head = head.next
pos += 1
checksum = pos - 1
middle = 0
for v in d.values():
if len(v) % 2 != 0:
middle += 1
else:
step = 0
for i in range(0, len(v)):
if v[i] + v[len(v) - 1 - step] != checksum:
return False
step += 1
if middle > 1:
return False
return True
|
[
"def",
"is_palindrome_dict",
"(",
"head",
")",
":",
"if",
"not",
"head",
"or",
"not",
"head",
".",
"next",
":",
"return",
"True",
"d",
"=",
"{",
"}",
"pos",
"=",
"0",
"while",
"head",
":",
"if",
"head",
".",
"val",
"in",
"d",
".",
"keys",
"(",
")",
":",
"d",
"[",
"head",
".",
"val",
"]",
".",
"append",
"(",
"pos",
")",
"else",
":",
"d",
"[",
"head",
".",
"val",
"]",
"=",
"[",
"pos",
"]",
"head",
"=",
"head",
".",
"next",
"pos",
"+=",
"1",
"checksum",
"=",
"pos",
"-",
"1",
"middle",
"=",
"0",
"for",
"v",
"in",
"d",
".",
"values",
"(",
")",
":",
"if",
"len",
"(",
"v",
")",
"%",
"2",
"!=",
"0",
":",
"middle",
"+=",
"1",
"else",
":",
"step",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"v",
")",
")",
":",
"if",
"v",
"[",
"i",
"]",
"+",
"v",
"[",
"len",
"(",
"v",
")",
"-",
"1",
"-",
"step",
"]",
"!=",
"checksum",
":",
"return",
"False",
"step",
"+=",
"1",
"if",
"middle",
">",
"1",
":",
"return",
"False",
"return",
"True"
] |
This function builds up a dictionary where the keys are the values of the list,
and the values are the positions at which these values occur in the list.
We then iterate over the dict and if there is more than one key with an odd
number of occurrences, bail out and return False.
Otherwise, we want to ensure that the positions of occurrence sum to the
value of the length of the list - 1, working from the outside of the list inward.
For example:
Input: 1 -> 1 -> 2 -> 3 -> 2 -> 1 -> 1
d = {1: [0,1,5,6], 2: [2,4], 3: [3]}
'3' is the middle outlier, 2+4=6, 0+6=6 and 5+1=6 so we have a palindrome.
|
[
"This",
"function",
"builds",
"up",
"a",
"dictionary",
"where",
"the",
"keys",
"are",
"the",
"values",
"of",
"the",
"list",
"and",
"the",
"values",
"are",
"the",
"positions",
"at",
"which",
"these",
"values",
"occur",
"in",
"the",
"list",
".",
"We",
"then",
"iterate",
"over",
"the",
"dict",
"and",
"if",
"there",
"is",
"more",
"than",
"one",
"key",
"with",
"an",
"odd",
"number",
"of",
"occurrences",
"bail",
"out",
"and",
"return",
"False",
".",
"Otherwise",
"we",
"want",
"to",
"ensure",
"that",
"the",
"positions",
"of",
"occurrence",
"sum",
"to",
"the",
"value",
"of",
"the",
"length",
"of",
"the",
"list",
"-",
"1",
"working",
"from",
"the",
"outside",
"of",
"the",
"list",
"inward",
".",
"For",
"example",
":",
"Input",
":",
"1",
"-",
">",
"1",
"-",
">",
"2",
"-",
">",
"3",
"-",
">",
"2",
"-",
">",
"1",
"-",
">",
"1",
"d",
"=",
"{",
"1",
":",
"[",
"0",
"1",
"5",
"6",
"]",
"2",
":",
"[",
"2",
"4",
"]",
"3",
":",
"[",
"3",
"]",
"}",
"3",
"is",
"the",
"middle",
"outlier",
"2",
"+",
"4",
"=",
"6",
"0",
"+",
"6",
"=",
"6",
"and",
"5",
"+",
"1",
"=",
"6",
"so",
"we",
"have",
"a",
"palindrome",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/is_palindrome.py#L52-L89
|
train
|
keon/algorithms
|
algorithms/dp/fib.py
|
fib_list
|
def fib_list(n):
"""[summary]
This algorithm computes the n-th fibbonacci number
very quick. approximate O(n)
The algorithm use dynamic programming.
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be a positive integer'
list_results = [0, 1]
for i in range(2, n+1):
list_results.append(list_results[i-1] + list_results[i-2])
return list_results[n]
|
python
|
def fib_list(n):
"""[summary]
This algorithm computes the n-th fibbonacci number
very quick. approximate O(n)
The algorithm use dynamic programming.
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be a positive integer'
list_results = [0, 1]
for i in range(2, n+1):
list_results.append(list_results[i-1] + list_results[i-2])
return list_results[n]
|
[
"def",
"fib_list",
"(",
"n",
")",
":",
"# precondition",
"assert",
"n",
">=",
"0",
",",
"'n must be a positive integer'",
"list_results",
"=",
"[",
"0",
",",
"1",
"]",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"n",
"+",
"1",
")",
":",
"list_results",
".",
"append",
"(",
"list_results",
"[",
"i",
"-",
"1",
"]",
"+",
"list_results",
"[",
"i",
"-",
"2",
"]",
")",
"return",
"list_results",
"[",
"n",
"]"
] |
[summary]
This algorithm computes the n-th fibbonacci number
very quick. approximate O(n)
The algorithm use dynamic programming.
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
|
[
"[",
"summary",
"]",
"This",
"algorithm",
"computes",
"the",
"n",
"-",
"th",
"fibbonacci",
"number",
"very",
"quick",
".",
"approximate",
"O",
"(",
"n",
")",
"The",
"algorithm",
"use",
"dynamic",
"programming",
".",
"Arguments",
":",
"n",
"{",
"[",
"int",
"]",
"}",
"--",
"[",
"description",
"]",
"Returns",
":",
"[",
"int",
"]",
"--",
"[",
"description",
"]"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/fib.py#L24-L43
|
train
|
keon/algorithms
|
algorithms/dp/fib.py
|
fib_iter
|
def fib_iter(n):
"""[summary]
Works iterative approximate O(n)
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be positive integer'
fib_1 = 0
fib_2 = 1
sum = 0
if n <= 1:
return n
for _ in range(n-1):
sum = fib_1 + fib_2
fib_1 = fib_2
fib_2 = sum
return sum
|
python
|
def fib_iter(n):
"""[summary]
Works iterative approximate O(n)
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
"""
# precondition
assert n >= 0, 'n must be positive integer'
fib_1 = 0
fib_2 = 1
sum = 0
if n <= 1:
return n
for _ in range(n-1):
sum = fib_1 + fib_2
fib_1 = fib_2
fib_2 = sum
return sum
|
[
"def",
"fib_iter",
"(",
"n",
")",
":",
"# precondition",
"assert",
"n",
">=",
"0",
",",
"'n must be positive integer'",
"fib_1",
"=",
"0",
"fib_2",
"=",
"1",
"sum",
"=",
"0",
"if",
"n",
"<=",
"1",
":",
"return",
"n",
"for",
"_",
"in",
"range",
"(",
"n",
"-",
"1",
")",
":",
"sum",
"=",
"fib_1",
"+",
"fib_2",
"fib_1",
"=",
"fib_2",
"fib_2",
"=",
"sum",
"return",
"sum"
] |
[summary]
Works iterative approximate O(n)
Arguments:
n {[int]} -- [description]
Returns:
[int] -- [description]
|
[
"[",
"summary",
"]",
"Works",
"iterative",
"approximate",
"O",
"(",
"n",
")"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/fib.py#L47-L70
|
train
|
keon/algorithms
|
algorithms/bit/subsets.py
|
subsets
|
def subsets(nums):
"""
:param nums: List[int]
:return: Set[tuple]
"""
n = len(nums)
total = 1 << n
res = set()
for i in range(total):
subset = tuple(num for j, num in enumerate(nums) if i & 1 << j)
res.add(subset)
return res
|
python
|
def subsets(nums):
"""
:param nums: List[int]
:return: Set[tuple]
"""
n = len(nums)
total = 1 << n
res = set()
for i in range(total):
subset = tuple(num for j, num in enumerate(nums) if i & 1 << j)
res.add(subset)
return res
|
[
"def",
"subsets",
"(",
"nums",
")",
":",
"n",
"=",
"len",
"(",
"nums",
")",
"total",
"=",
"1",
"<<",
"n",
"res",
"=",
"set",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"total",
")",
":",
"subset",
"=",
"tuple",
"(",
"num",
"for",
"j",
",",
"num",
"in",
"enumerate",
"(",
"nums",
")",
"if",
"i",
"&",
"1",
"<<",
"j",
")",
"res",
".",
"add",
"(",
"subset",
")",
"return",
"res"
] |
:param nums: List[int]
:return: Set[tuple]
|
[
":",
"param",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"return",
":",
"Set",
"[",
"tuple",
"]"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/bit/subsets.py#L21-L34
|
train
|
keon/algorithms
|
algorithms/strings/min_distance.py
|
lcs
|
def lcs(s1, s2, i, j):
"""
The length of longest common subsequence among the two given strings s1 and s2
"""
if i == 0 or j == 0:
return 0
elif s1[i - 1] == s2[j - 1]:
return 1 + lcs(s1, s2, i - 1, j - 1)
else:
return max(lcs(s1, s2, i - 1, j), lcs(s1, s2, i, j - 1))
|
python
|
def lcs(s1, s2, i, j):
"""
The length of longest common subsequence among the two given strings s1 and s2
"""
if i == 0 or j == 0:
return 0
elif s1[i - 1] == s2[j - 1]:
return 1 + lcs(s1, s2, i - 1, j - 1)
else:
return max(lcs(s1, s2, i - 1, j), lcs(s1, s2, i, j - 1))
|
[
"def",
"lcs",
"(",
"s1",
",",
"s2",
",",
"i",
",",
"j",
")",
":",
"if",
"i",
"==",
"0",
"or",
"j",
"==",
"0",
":",
"return",
"0",
"elif",
"s1",
"[",
"i",
"-",
"1",
"]",
"==",
"s2",
"[",
"j",
"-",
"1",
"]",
":",
"return",
"1",
"+",
"lcs",
"(",
"s1",
",",
"s2",
",",
"i",
"-",
"1",
",",
"j",
"-",
"1",
")",
"else",
":",
"return",
"max",
"(",
"lcs",
"(",
"s1",
",",
"s2",
",",
"i",
"-",
"1",
",",
"j",
")",
",",
"lcs",
"(",
"s1",
",",
"s2",
",",
"i",
",",
"j",
"-",
"1",
")",
")"
] |
The length of longest common subsequence among the two given strings s1 and s2
|
[
"The",
"length",
"of",
"longest",
"common",
"subsequence",
"among",
"the",
"two",
"given",
"strings",
"s1",
"and",
"s2"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/min_distance.py#L17-L26
|
train
|
keon/algorithms
|
algorithms/tree/lowest_common_ancestor.py
|
lca
|
def lca(root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root is None or root is p or root is q:
return root
left = lca(root.left, p, q)
right = lca(root.right, p, q)
if left is not None and right is not None:
return root
return left if left else right
|
python
|
def lca(root, p, q):
"""
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
"""
if root is None or root is p or root is q:
return root
left = lca(root.left, p, q)
right = lca(root.right, p, q)
if left is not None and right is not None:
return root
return left if left else right
|
[
"def",
"lca",
"(",
"root",
",",
"p",
",",
"q",
")",
":",
"if",
"root",
"is",
"None",
"or",
"root",
"is",
"p",
"or",
"root",
"is",
"q",
":",
"return",
"root",
"left",
"=",
"lca",
"(",
"root",
".",
"left",
",",
"p",
",",
"q",
")",
"right",
"=",
"lca",
"(",
"root",
".",
"right",
",",
"p",
",",
"q",
")",
"if",
"left",
"is",
"not",
"None",
"and",
"right",
"is",
"not",
"None",
":",
"return",
"root",
"return",
"left",
"if",
"left",
"else",
"right"
] |
:type root: TreeNode
:type p: TreeNode
:type q: TreeNode
:rtype: TreeNode
|
[
":",
"type",
"root",
":",
"TreeNode",
":",
"type",
"p",
":",
"TreeNode",
":",
"type",
"q",
":",
"TreeNode",
":",
"rtype",
":",
"TreeNode"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/lowest_common_ancestor.py#L24-L37
|
train
|
keon/algorithms
|
algorithms/tree/bst/lowest_common_ancestor.py
|
lowest_common_ancestor
|
def lowest_common_ancestor(root, p, q):
"""
:type root: Node
:type p: Node
:type q: Node
:rtype: Node
"""
while root:
if p.val > root.val < q.val:
root = root.right
elif p.val < root.val > q.val:
root = root.left
else:
return root
|
python
|
def lowest_common_ancestor(root, p, q):
"""
:type root: Node
:type p: Node
:type q: Node
:rtype: Node
"""
while root:
if p.val > root.val < q.val:
root = root.right
elif p.val < root.val > q.val:
root = root.left
else:
return root
|
[
"def",
"lowest_common_ancestor",
"(",
"root",
",",
"p",
",",
"q",
")",
":",
"while",
"root",
":",
"if",
"p",
".",
"val",
">",
"root",
".",
"val",
"<",
"q",
".",
"val",
":",
"root",
"=",
"root",
".",
"right",
"elif",
"p",
".",
"val",
"<",
"root",
".",
"val",
">",
"q",
".",
"val",
":",
"root",
"=",
"root",
".",
"left",
"else",
":",
"return",
"root"
] |
:type root: Node
:type p: Node
:type q: Node
:rtype: Node
|
[
":",
"type",
"root",
":",
"Node",
":",
"type",
"p",
":",
"Node",
":",
"type",
"q",
":",
"Node",
":",
"rtype",
":",
"Node"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/bst/lowest_common_ancestor.py#L24-L37
|
train
|
keon/algorithms
|
algorithms/dp/climbing_stairs.py
|
climb_stairs
|
def climb_stairs(n):
"""
:type n: int
:rtype: int
"""
arr = [1, 1]
for _ in range(1, n):
arr.append(arr[-1] + arr[-2])
return arr[-1]
|
python
|
def climb_stairs(n):
"""
:type n: int
:rtype: int
"""
arr = [1, 1]
for _ in range(1, n):
arr.append(arr[-1] + arr[-2])
return arr[-1]
|
[
"def",
"climb_stairs",
"(",
"n",
")",
":",
"arr",
"=",
"[",
"1",
",",
"1",
"]",
"for",
"_",
"in",
"range",
"(",
"1",
",",
"n",
")",
":",
"arr",
".",
"append",
"(",
"arr",
"[",
"-",
"1",
"]",
"+",
"arr",
"[",
"-",
"2",
"]",
")",
"return",
"arr",
"[",
"-",
"1",
"]"
] |
:type n: int
:rtype: int
|
[
":",
"type",
"n",
":",
"int",
":",
"rtype",
":",
"int"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/climbing_stairs.py#L14-L22
|
train
|
keon/algorithms
|
algorithms/maths/nth_digit.py
|
find_nth_digit
|
def find_nth_digit(n):
"""find the nth digit of given number.
1. find the length of the number where the nth digit is from.
2. find the actual number where the nth digit is from
3. find the nth digit and return
"""
length = 1
count = 9
start = 1
while n > length * count:
n -= length * count
length += 1
count *= 10
start *= 10
start += (n-1) / length
s = str(start)
return int(s[(n-1) % length])
|
python
|
def find_nth_digit(n):
"""find the nth digit of given number.
1. find the length of the number where the nth digit is from.
2. find the actual number where the nth digit is from
3. find the nth digit and return
"""
length = 1
count = 9
start = 1
while n > length * count:
n -= length * count
length += 1
count *= 10
start *= 10
start += (n-1) / length
s = str(start)
return int(s[(n-1) % length])
|
[
"def",
"find_nth_digit",
"(",
"n",
")",
":",
"length",
"=",
"1",
"count",
"=",
"9",
"start",
"=",
"1",
"while",
"n",
">",
"length",
"*",
"count",
":",
"n",
"-=",
"length",
"*",
"count",
"length",
"+=",
"1",
"count",
"*=",
"10",
"start",
"*=",
"10",
"start",
"+=",
"(",
"n",
"-",
"1",
")",
"/",
"length",
"s",
"=",
"str",
"(",
"start",
")",
"return",
"int",
"(",
"s",
"[",
"(",
"n",
"-",
"1",
")",
"%",
"length",
"]",
")"
] |
find the nth digit of given number.
1. find the length of the number where the nth digit is from.
2. find the actual number where the nth digit is from
3. find the nth digit and return
|
[
"find",
"the",
"nth",
"digit",
"of",
"given",
"number",
".",
"1",
".",
"find",
"the",
"length",
"of",
"the",
"number",
"where",
"the",
"nth",
"digit",
"is",
"from",
".",
"2",
".",
"find",
"the",
"actual",
"number",
"where",
"the",
"nth",
"digit",
"is",
"from",
"3",
".",
"find",
"the",
"nth",
"digit",
"and",
"return"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/nth_digit.py#L1-L17
|
train
|
keon/algorithms
|
algorithms/maths/hailstone.py
|
hailstone
|
def hailstone(n):
"""Return the 'hailstone sequence' from n to 1
n: The starting point of the hailstone sequence
"""
sequence = [n]
while n > 1:
if n%2 != 0:
n = 3*n + 1
else:
n = int(n/2)
sequence.append(n)
return sequence
|
python
|
def hailstone(n):
"""Return the 'hailstone sequence' from n to 1
n: The starting point of the hailstone sequence
"""
sequence = [n]
while n > 1:
if n%2 != 0:
n = 3*n + 1
else:
n = int(n/2)
sequence.append(n)
return sequence
|
[
"def",
"hailstone",
"(",
"n",
")",
":",
"sequence",
"=",
"[",
"n",
"]",
"while",
"n",
">",
"1",
":",
"if",
"n",
"%",
"2",
"!=",
"0",
":",
"n",
"=",
"3",
"*",
"n",
"+",
"1",
"else",
":",
"n",
"=",
"int",
"(",
"n",
"/",
"2",
")",
"sequence",
".",
"append",
"(",
"n",
")",
"return",
"sequence"
] |
Return the 'hailstone sequence' from n to 1
n: The starting point of the hailstone sequence
|
[
"Return",
"the",
"hailstone",
"sequence",
"from",
"n",
"to",
"1",
"n",
":",
"The",
"starting",
"point",
"of",
"the",
"hailstone",
"sequence"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/hailstone.py#L1-L13
|
train
|
keon/algorithms
|
algorithms/dp/word_break.py
|
word_break
|
def word_break(s, word_dict):
"""
:type s: str
:type word_dict: Set[str]
:rtype: bool
"""
dp = [False] * (len(s)+1)
dp[0] = True
for i in range(1, len(s)+1):
for j in range(0, i):
if dp[j] and s[j:i] in word_dict:
dp[i] = True
break
return dp[-1]
|
python
|
def word_break(s, word_dict):
"""
:type s: str
:type word_dict: Set[str]
:rtype: bool
"""
dp = [False] * (len(s)+1)
dp[0] = True
for i in range(1, len(s)+1):
for j in range(0, i):
if dp[j] and s[j:i] in word_dict:
dp[i] = True
break
return dp[-1]
|
[
"def",
"word_break",
"(",
"s",
",",
"word_dict",
")",
":",
"dp",
"=",
"[",
"False",
"]",
"*",
"(",
"len",
"(",
"s",
")",
"+",
"1",
")",
"dp",
"[",
"0",
"]",
"=",
"True",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"s",
")",
"+",
"1",
")",
":",
"for",
"j",
"in",
"range",
"(",
"0",
",",
"i",
")",
":",
"if",
"dp",
"[",
"j",
"]",
"and",
"s",
"[",
"j",
":",
"i",
"]",
"in",
"word_dict",
":",
"dp",
"[",
"i",
"]",
"=",
"True",
"break",
"return",
"dp",
"[",
"-",
"1",
"]"
] |
:type s: str
:type word_dict: Set[str]
:rtype: bool
|
[
":",
"type",
"s",
":",
"str",
":",
"type",
"word_dict",
":",
"Set",
"[",
"str",
"]",
":",
"rtype",
":",
"bool"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/word_break.py#L24-L37
|
train
|
keon/algorithms
|
algorithms/maths/prime_check.py
|
prime_check
|
def prime_check(n):
"""Return True if n is a prime number
Else return False.
"""
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
j = 5
while j * j <= n:
if n % j == 0 or n % (j + 2) == 0:
return False
j += 6
return True
|
python
|
def prime_check(n):
"""Return True if n is a prime number
Else return False.
"""
if n <= 1:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
j = 5
while j * j <= n:
if n % j == 0 or n % (j + 2) == 0:
return False
j += 6
return True
|
[
"def",
"prime_check",
"(",
"n",
")",
":",
"if",
"n",
"<=",
"1",
":",
"return",
"False",
"if",
"n",
"==",
"2",
"or",
"n",
"==",
"3",
":",
"return",
"True",
"if",
"n",
"%",
"2",
"==",
"0",
"or",
"n",
"%",
"3",
"==",
"0",
":",
"return",
"False",
"j",
"=",
"5",
"while",
"j",
"*",
"j",
"<=",
"n",
":",
"if",
"n",
"%",
"j",
"==",
"0",
"or",
"n",
"%",
"(",
"j",
"+",
"2",
")",
"==",
"0",
":",
"return",
"False",
"j",
"+=",
"6",
"return",
"True"
] |
Return True if n is a prime number
Else return False.
|
[
"Return",
"True",
"if",
"n",
"is",
"a",
"prime",
"number",
"Else",
"return",
"False",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/prime_check.py#L1-L17
|
train
|
keon/algorithms
|
algorithms/arrays/longest_non_repeat.py
|
longest_non_repeat_v1
|
def longest_non_repeat_v1(string):
"""
Find the length of the longest substring
without repeating characters.
"""
if string is None:
return 0
dict = {}
max_length = 0
j = 0
for i in range(len(string)):
if string[i] in dict:
j = max(dict[string[i]], j)
dict[string[i]] = i + 1
max_length = max(max_length, i - j + 1)
return max_length
|
python
|
def longest_non_repeat_v1(string):
"""
Find the length of the longest substring
without repeating characters.
"""
if string is None:
return 0
dict = {}
max_length = 0
j = 0
for i in range(len(string)):
if string[i] in dict:
j = max(dict[string[i]], j)
dict[string[i]] = i + 1
max_length = max(max_length, i - j + 1)
return max_length
|
[
"def",
"longest_non_repeat_v1",
"(",
"string",
")",
":",
"if",
"string",
"is",
"None",
":",
"return",
"0",
"dict",
"=",
"{",
"}",
"max_length",
"=",
"0",
"j",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"string",
")",
")",
":",
"if",
"string",
"[",
"i",
"]",
"in",
"dict",
":",
"j",
"=",
"max",
"(",
"dict",
"[",
"string",
"[",
"i",
"]",
"]",
",",
"j",
")",
"dict",
"[",
"string",
"[",
"i",
"]",
"]",
"=",
"i",
"+",
"1",
"max_length",
"=",
"max",
"(",
"max_length",
",",
"i",
"-",
"j",
"+",
"1",
")",
"return",
"max_length"
] |
Find the length of the longest substring
without repeating characters.
|
[
"Find",
"the",
"length",
"of",
"the",
"longest",
"substring",
"without",
"repeating",
"characters",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/longest_non_repeat.py#L14-L29
|
train
|
keon/algorithms
|
algorithms/arrays/longest_non_repeat.py
|
longest_non_repeat_v2
|
def longest_non_repeat_v2(string):
"""
Find the length of the longest substring
without repeating characters.
Uses alternative algorithm.
"""
if string is None:
return 0
start, max_len = 0, 0
used_char = {}
for index, char in enumerate(string):
if char in used_char and start <= used_char[char]:
start = used_char[char] + 1
else:
max_len = max(max_len, index - start + 1)
used_char[char] = index
return max_len
|
python
|
def longest_non_repeat_v2(string):
"""
Find the length of the longest substring
without repeating characters.
Uses alternative algorithm.
"""
if string is None:
return 0
start, max_len = 0, 0
used_char = {}
for index, char in enumerate(string):
if char in used_char and start <= used_char[char]:
start = used_char[char] + 1
else:
max_len = max(max_len, index - start + 1)
used_char[char] = index
return max_len
|
[
"def",
"longest_non_repeat_v2",
"(",
"string",
")",
":",
"if",
"string",
"is",
"None",
":",
"return",
"0",
"start",
",",
"max_len",
"=",
"0",
",",
"0",
"used_char",
"=",
"{",
"}",
"for",
"index",
",",
"char",
"in",
"enumerate",
"(",
"string",
")",
":",
"if",
"char",
"in",
"used_char",
"and",
"start",
"<=",
"used_char",
"[",
"char",
"]",
":",
"start",
"=",
"used_char",
"[",
"char",
"]",
"+",
"1",
"else",
":",
"max_len",
"=",
"max",
"(",
"max_len",
",",
"index",
"-",
"start",
"+",
"1",
")",
"used_char",
"[",
"char",
"]",
"=",
"index",
"return",
"max_len"
] |
Find the length of the longest substring
without repeating characters.
Uses alternative algorithm.
|
[
"Find",
"the",
"length",
"of",
"the",
"longest",
"substring",
"without",
"repeating",
"characters",
".",
"Uses",
"alternative",
"algorithm",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/longest_non_repeat.py#L31-L47
|
train
|
keon/algorithms
|
algorithms/arrays/longest_non_repeat.py
|
get_longest_non_repeat_v1
|
def get_longest_non_repeat_v1(string):
"""
Find the length of the longest substring
without repeating characters.
Return max_len and the substring as a tuple
"""
if string is None:
return 0, ''
sub_string = ''
dict = {}
max_length = 0
j = 0
for i in range(len(string)):
if string[i] in dict:
j = max(dict[string[i]], j)
dict[string[i]] = i + 1
if i - j + 1 > max_length:
max_length = i - j + 1
sub_string = string[j: i + 1]
return max_length, sub_string
|
python
|
def get_longest_non_repeat_v1(string):
"""
Find the length of the longest substring
without repeating characters.
Return max_len and the substring as a tuple
"""
if string is None:
return 0, ''
sub_string = ''
dict = {}
max_length = 0
j = 0
for i in range(len(string)):
if string[i] in dict:
j = max(dict[string[i]], j)
dict[string[i]] = i + 1
if i - j + 1 > max_length:
max_length = i - j + 1
sub_string = string[j: i + 1]
return max_length, sub_string
|
[
"def",
"get_longest_non_repeat_v1",
"(",
"string",
")",
":",
"if",
"string",
"is",
"None",
":",
"return",
"0",
",",
"''",
"sub_string",
"=",
"''",
"dict",
"=",
"{",
"}",
"max_length",
"=",
"0",
"j",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"string",
")",
")",
":",
"if",
"string",
"[",
"i",
"]",
"in",
"dict",
":",
"j",
"=",
"max",
"(",
"dict",
"[",
"string",
"[",
"i",
"]",
"]",
",",
"j",
")",
"dict",
"[",
"string",
"[",
"i",
"]",
"]",
"=",
"i",
"+",
"1",
"if",
"i",
"-",
"j",
"+",
"1",
">",
"max_length",
":",
"max_length",
"=",
"i",
"-",
"j",
"+",
"1",
"sub_string",
"=",
"string",
"[",
"j",
":",
"i",
"+",
"1",
"]",
"return",
"max_length",
",",
"sub_string"
] |
Find the length of the longest substring
without repeating characters.
Return max_len and the substring as a tuple
|
[
"Find",
"the",
"length",
"of",
"the",
"longest",
"substring",
"without",
"repeating",
"characters",
".",
"Return",
"max_len",
"and",
"the",
"substring",
"as",
"a",
"tuple"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/longest_non_repeat.py#L50-L69
|
train
|
keon/algorithms
|
algorithms/arrays/longest_non_repeat.py
|
get_longest_non_repeat_v2
|
def get_longest_non_repeat_v2(string):
"""
Find the length of the longest substring
without repeating characters.
Uses alternative algorithm.
Return max_len and the substring as a tuple
"""
if string is None:
return 0, ''
sub_string = ''
start, max_len = 0, 0
used_char = {}
for index, char in enumerate(string):
if char in used_char and start <= used_char[char]:
start = used_char[char] + 1
else:
if index - start + 1 > max_len:
max_len = index - start + 1
sub_string = string[start: index + 1]
used_char[char] = index
return max_len, sub_string
|
python
|
def get_longest_non_repeat_v2(string):
"""
Find the length of the longest substring
without repeating characters.
Uses alternative algorithm.
Return max_len and the substring as a tuple
"""
if string is None:
return 0, ''
sub_string = ''
start, max_len = 0, 0
used_char = {}
for index, char in enumerate(string):
if char in used_char and start <= used_char[char]:
start = used_char[char] + 1
else:
if index - start + 1 > max_len:
max_len = index - start + 1
sub_string = string[start: index + 1]
used_char[char] = index
return max_len, sub_string
|
[
"def",
"get_longest_non_repeat_v2",
"(",
"string",
")",
":",
"if",
"string",
"is",
"None",
":",
"return",
"0",
",",
"''",
"sub_string",
"=",
"''",
"start",
",",
"max_len",
"=",
"0",
",",
"0",
"used_char",
"=",
"{",
"}",
"for",
"index",
",",
"char",
"in",
"enumerate",
"(",
"string",
")",
":",
"if",
"char",
"in",
"used_char",
"and",
"start",
"<=",
"used_char",
"[",
"char",
"]",
":",
"start",
"=",
"used_char",
"[",
"char",
"]",
"+",
"1",
"else",
":",
"if",
"index",
"-",
"start",
"+",
"1",
">",
"max_len",
":",
"max_len",
"=",
"index",
"-",
"start",
"+",
"1",
"sub_string",
"=",
"string",
"[",
"start",
":",
"index",
"+",
"1",
"]",
"used_char",
"[",
"char",
"]",
"=",
"index",
"return",
"max_len",
",",
"sub_string"
] |
Find the length of the longest substring
without repeating characters.
Uses alternative algorithm.
Return max_len and the substring as a tuple
|
[
"Find",
"the",
"length",
"of",
"the",
"longest",
"substring",
"without",
"repeating",
"characters",
".",
"Uses",
"alternative",
"algorithm",
".",
"Return",
"max_len",
"and",
"the",
"substring",
"as",
"a",
"tuple"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/longest_non_repeat.py#L71-L91
|
train
|
keon/algorithms
|
algorithms/queues/priority_queue.py
|
PriorityQueue.push
|
def push(self, item, priority=None):
"""Push the item in the priority queue.
if priority is not given, priority is set to the value of item.
"""
priority = item if priority is None else priority
node = PriorityQueueNode(item, priority)
for index, current in enumerate(self.priority_queue_list):
if current.priority < node.priority:
self.priority_queue_list.insert(index, node)
return
# when traversed complete queue
self.priority_queue_list.append(node)
|
python
|
def push(self, item, priority=None):
"""Push the item in the priority queue.
if priority is not given, priority is set to the value of item.
"""
priority = item if priority is None else priority
node = PriorityQueueNode(item, priority)
for index, current in enumerate(self.priority_queue_list):
if current.priority < node.priority:
self.priority_queue_list.insert(index, node)
return
# when traversed complete queue
self.priority_queue_list.append(node)
|
[
"def",
"push",
"(",
"self",
",",
"item",
",",
"priority",
"=",
"None",
")",
":",
"priority",
"=",
"item",
"if",
"priority",
"is",
"None",
"else",
"priority",
"node",
"=",
"PriorityQueueNode",
"(",
"item",
",",
"priority",
")",
"for",
"index",
",",
"current",
"in",
"enumerate",
"(",
"self",
".",
"priority_queue_list",
")",
":",
"if",
"current",
".",
"priority",
"<",
"node",
".",
"priority",
":",
"self",
".",
"priority_queue_list",
".",
"insert",
"(",
"index",
",",
"node",
")",
"return",
"# when traversed complete queue",
"self",
".",
"priority_queue_list",
".",
"append",
"(",
"node",
")"
] |
Push the item in the priority queue.
if priority is not given, priority is set to the value of item.
|
[
"Push",
"the",
"item",
"in",
"the",
"priority",
"queue",
".",
"if",
"priority",
"is",
"not",
"given",
"priority",
"is",
"set",
"to",
"the",
"value",
"of",
"item",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/queues/priority_queue.py#L38-L49
|
train
|
keon/algorithms
|
algorithms/maths/factorial.py
|
factorial
|
def factorial(n, mod=None):
"""Calculates factorial iteratively.
If mod is not None, then return (n! % mod)
Time Complexity - O(n)"""
if not (isinstance(n, int) and n >= 0):
raise ValueError("'n' must be a non-negative integer.")
if mod is not None and not (isinstance(mod, int) and mod > 0):
raise ValueError("'mod' must be a positive integer")
result = 1
if n == 0:
return 1
for i in range(2, n+1):
result *= i
if mod:
result %= mod
return result
|
python
|
def factorial(n, mod=None):
"""Calculates factorial iteratively.
If mod is not None, then return (n! % mod)
Time Complexity - O(n)"""
if not (isinstance(n, int) and n >= 0):
raise ValueError("'n' must be a non-negative integer.")
if mod is not None and not (isinstance(mod, int) and mod > 0):
raise ValueError("'mod' must be a positive integer")
result = 1
if n == 0:
return 1
for i in range(2, n+1):
result *= i
if mod:
result %= mod
return result
|
[
"def",
"factorial",
"(",
"n",
",",
"mod",
"=",
"None",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"n",
",",
"int",
")",
"and",
"n",
">=",
"0",
")",
":",
"raise",
"ValueError",
"(",
"\"'n' must be a non-negative integer.\"",
")",
"if",
"mod",
"is",
"not",
"None",
"and",
"not",
"(",
"isinstance",
"(",
"mod",
",",
"int",
")",
"and",
"mod",
">",
"0",
")",
":",
"raise",
"ValueError",
"(",
"\"'mod' must be a positive integer\"",
")",
"result",
"=",
"1",
"if",
"n",
"==",
"0",
":",
"return",
"1",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"n",
"+",
"1",
")",
":",
"result",
"*=",
"i",
"if",
"mod",
":",
"result",
"%=",
"mod",
"return",
"result"
] |
Calculates factorial iteratively.
If mod is not None, then return (n! % mod)
Time Complexity - O(n)
|
[
"Calculates",
"factorial",
"iteratively",
".",
"If",
"mod",
"is",
"not",
"None",
"then",
"return",
"(",
"n!",
"%",
"mod",
")",
"Time",
"Complexity",
"-",
"O",
"(",
"n",
")"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/factorial.py#L1-L16
|
train
|
keon/algorithms
|
algorithms/maths/factorial.py
|
factorial_recur
|
def factorial_recur(n, mod=None):
"""Calculates factorial recursively.
If mod is not None, then return (n! % mod)
Time Complexity - O(n)"""
if not (isinstance(n, int) and n >= 0):
raise ValueError("'n' must be a non-negative integer.")
if mod is not None and not (isinstance(mod, int) and mod > 0):
raise ValueError("'mod' must be a positive integer")
if n == 0:
return 1
result = n * factorial(n - 1, mod)
if mod:
result %= mod
return result
|
python
|
def factorial_recur(n, mod=None):
"""Calculates factorial recursively.
If mod is not None, then return (n! % mod)
Time Complexity - O(n)"""
if not (isinstance(n, int) and n >= 0):
raise ValueError("'n' must be a non-negative integer.")
if mod is not None and not (isinstance(mod, int) and mod > 0):
raise ValueError("'mod' must be a positive integer")
if n == 0:
return 1
result = n * factorial(n - 1, mod)
if mod:
result %= mod
return result
|
[
"def",
"factorial_recur",
"(",
"n",
",",
"mod",
"=",
"None",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"n",
",",
"int",
")",
"and",
"n",
">=",
"0",
")",
":",
"raise",
"ValueError",
"(",
"\"'n' must be a non-negative integer.\"",
")",
"if",
"mod",
"is",
"not",
"None",
"and",
"not",
"(",
"isinstance",
"(",
"mod",
",",
"int",
")",
"and",
"mod",
">",
"0",
")",
":",
"raise",
"ValueError",
"(",
"\"'mod' must be a positive integer\"",
")",
"if",
"n",
"==",
"0",
":",
"return",
"1",
"result",
"=",
"n",
"*",
"factorial",
"(",
"n",
"-",
"1",
",",
"mod",
")",
"if",
"mod",
":",
"result",
"%=",
"mod",
"return",
"result"
] |
Calculates factorial recursively.
If mod is not None, then return (n! % mod)
Time Complexity - O(n)
|
[
"Calculates",
"factorial",
"recursively",
".",
"If",
"mod",
"is",
"not",
"None",
"then",
"return",
"(",
"n!",
"%",
"mod",
")",
"Time",
"Complexity",
"-",
"O",
"(",
"n",
")"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/factorial.py#L19-L32
|
train
|
keon/algorithms
|
algorithms/sort/selection_sort.py
|
selection_sort
|
def selection_sort(arr, simulation=False):
""" Selection Sort
Complexity: O(n^2)
"""
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
for i in range(len(arr)):
minimum = i
for j in range(i + 1, len(arr)):
# "Select" the correct value
if arr[j] < arr[minimum]:
minimum = j
arr[minimum], arr[i] = arr[i], arr[minimum]
if simulation:
iteration = iteration + 1
print("iteration",iteration,":",*arr)
return arr
|
python
|
def selection_sort(arr, simulation=False):
""" Selection Sort
Complexity: O(n^2)
"""
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
for i in range(len(arr)):
minimum = i
for j in range(i + 1, len(arr)):
# "Select" the correct value
if arr[j] < arr[minimum]:
minimum = j
arr[minimum], arr[i] = arr[i], arr[minimum]
if simulation:
iteration = iteration + 1
print("iteration",iteration,":",*arr)
return arr
|
[
"def",
"selection_sort",
"(",
"arr",
",",
"simulation",
"=",
"False",
")",
":",
"iteration",
"=",
"0",
"if",
"simulation",
":",
"print",
"(",
"\"iteration\"",
",",
"iteration",
",",
"\":\"",
",",
"*",
"arr",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"arr",
")",
")",
":",
"minimum",
"=",
"i",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
",",
"len",
"(",
"arr",
")",
")",
":",
"# \"Select\" the correct value",
"if",
"arr",
"[",
"j",
"]",
"<",
"arr",
"[",
"minimum",
"]",
":",
"minimum",
"=",
"j",
"arr",
"[",
"minimum",
"]",
",",
"arr",
"[",
"i",
"]",
"=",
"arr",
"[",
"i",
"]",
",",
"arr",
"[",
"minimum",
"]",
"if",
"simulation",
":",
"iteration",
"=",
"iteration",
"+",
"1",
"print",
"(",
"\"iteration\"",
",",
"iteration",
",",
"\":\"",
",",
"*",
"arr",
")",
"return",
"arr"
] |
Selection Sort
Complexity: O(n^2)
|
[
"Selection",
"Sort",
"Complexity",
":",
"O",
"(",
"n^2",
")"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/selection_sort.py#L1-L23
|
train
|
keon/algorithms
|
algorithms/linkedlist/remove_duplicates.py
|
remove_dups
|
def remove_dups(head):
"""
Time Complexity: O(N)
Space Complexity: O(N)
"""
hashset = set()
prev = Node()
while head:
if head.val in hashset:
prev.next = head.next
else:
hashset.add(head.val)
prev = head
head = head.next
|
python
|
def remove_dups(head):
"""
Time Complexity: O(N)
Space Complexity: O(N)
"""
hashset = set()
prev = Node()
while head:
if head.val in hashset:
prev.next = head.next
else:
hashset.add(head.val)
prev = head
head = head.next
|
[
"def",
"remove_dups",
"(",
"head",
")",
":",
"hashset",
"=",
"set",
"(",
")",
"prev",
"=",
"Node",
"(",
")",
"while",
"head",
":",
"if",
"head",
".",
"val",
"in",
"hashset",
":",
"prev",
".",
"next",
"=",
"head",
".",
"next",
"else",
":",
"hashset",
".",
"add",
"(",
"head",
".",
"val",
")",
"prev",
"=",
"head",
"head",
"=",
"head",
".",
"next"
] |
Time Complexity: O(N)
Space Complexity: O(N)
|
[
"Time",
"Complexity",
":",
"O",
"(",
"N",
")",
"Space",
"Complexity",
":",
"O",
"(",
"N",
")"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/remove_duplicates.py#L6-L19
|
train
|
keon/algorithms
|
algorithms/linkedlist/remove_duplicates.py
|
remove_dups_wothout_set
|
def remove_dups_wothout_set(head):
"""
Time Complexity: O(N^2)
Space Complexity: O(1)
"""
current = head
while current:
runner = current
while runner.next:
if runner.next.val == current.val:
runner.next = runner.next.next
else:
runner = runner.next
current = current.next
|
python
|
def remove_dups_wothout_set(head):
"""
Time Complexity: O(N^2)
Space Complexity: O(1)
"""
current = head
while current:
runner = current
while runner.next:
if runner.next.val == current.val:
runner.next = runner.next.next
else:
runner = runner.next
current = current.next
|
[
"def",
"remove_dups_wothout_set",
"(",
"head",
")",
":",
"current",
"=",
"head",
"while",
"current",
":",
"runner",
"=",
"current",
"while",
"runner",
".",
"next",
":",
"if",
"runner",
".",
"next",
".",
"val",
"==",
"current",
".",
"val",
":",
"runner",
".",
"next",
"=",
"runner",
".",
"next",
".",
"next",
"else",
":",
"runner",
"=",
"runner",
".",
"next",
"current",
"=",
"current",
".",
"next"
] |
Time Complexity: O(N^2)
Space Complexity: O(1)
|
[
"Time",
"Complexity",
":",
"O",
"(",
"N^2",
")",
"Space",
"Complexity",
":",
"O",
"(",
"1",
")"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/remove_duplicates.py#L21-L34
|
train
|
keon/algorithms
|
algorithms/tree/red_black_tree/red_black_tree.py
|
RBTree.transplant
|
def transplant(self, node_u, node_v):
"""
replace u with v
:param node_u: replaced node
:param node_v:
:return: None
"""
if node_u.parent is None:
self.root = node_v
elif node_u is node_u.parent.left:
node_u.parent.left = node_v
elif node_u is node_u.parent.right:
node_u.parent.right = node_v
# check is node_v is None
if node_v:
node_v.parent = node_u.parent
|
python
|
def transplant(self, node_u, node_v):
"""
replace u with v
:param node_u: replaced node
:param node_v:
:return: None
"""
if node_u.parent is None:
self.root = node_v
elif node_u is node_u.parent.left:
node_u.parent.left = node_v
elif node_u is node_u.parent.right:
node_u.parent.right = node_v
# check is node_v is None
if node_v:
node_v.parent = node_u.parent
|
[
"def",
"transplant",
"(",
"self",
",",
"node_u",
",",
"node_v",
")",
":",
"if",
"node_u",
".",
"parent",
"is",
"None",
":",
"self",
".",
"root",
"=",
"node_v",
"elif",
"node_u",
"is",
"node_u",
".",
"parent",
".",
"left",
":",
"node_u",
".",
"parent",
".",
"left",
"=",
"node_v",
"elif",
"node_u",
"is",
"node_u",
".",
"parent",
".",
"right",
":",
"node_u",
".",
"parent",
".",
"right",
"=",
"node_v",
"# check is node_v is None ",
"if",
"node_v",
":",
"node_v",
".",
"parent",
"=",
"node_u",
".",
"parent"
] |
replace u with v
:param node_u: replaced node
:param node_v:
:return: None
|
[
"replace",
"u",
"with",
"v",
":",
"param",
"node_u",
":",
"replaced",
"node",
":",
"param",
"node_v",
":",
":",
"return",
":",
"None"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/red_black_tree/red_black_tree.py#L143-L158
|
train
|
keon/algorithms
|
algorithms/tree/red_black_tree/red_black_tree.py
|
RBTree.maximum
|
def maximum(self, node):
"""
find the max node when node regard as a root node
:param node:
:return: max node
"""
temp_node = node
while temp_node.right is not None:
temp_node = temp_node.right
return temp_node
|
python
|
def maximum(self, node):
"""
find the max node when node regard as a root node
:param node:
:return: max node
"""
temp_node = node
while temp_node.right is not None:
temp_node = temp_node.right
return temp_node
|
[
"def",
"maximum",
"(",
"self",
",",
"node",
")",
":",
"temp_node",
"=",
"node",
"while",
"temp_node",
".",
"right",
"is",
"not",
"None",
":",
"temp_node",
"=",
"temp_node",
".",
"right",
"return",
"temp_node"
] |
find the max node when node regard as a root node
:param node:
:return: max node
|
[
"find",
"the",
"max",
"node",
"when",
"node",
"regard",
"as",
"a",
"root",
"node",
":",
"param",
"node",
":",
":",
"return",
":",
"max",
"node"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/red_black_tree/red_black_tree.py#L160-L169
|
train
|
keon/algorithms
|
algorithms/tree/red_black_tree/red_black_tree.py
|
RBTree.minimum
|
def minimum(self, node):
"""
find the minimum node when node regard as a root node
:param node:
:return: minimum node
"""
temp_node = node
while temp_node.left:
temp_node = temp_node.left
return temp_node
|
python
|
def minimum(self, node):
"""
find the minimum node when node regard as a root node
:param node:
:return: minimum node
"""
temp_node = node
while temp_node.left:
temp_node = temp_node.left
return temp_node
|
[
"def",
"minimum",
"(",
"self",
",",
"node",
")",
":",
"temp_node",
"=",
"node",
"while",
"temp_node",
".",
"left",
":",
"temp_node",
"=",
"temp_node",
".",
"left",
"return",
"temp_node"
] |
find the minimum node when node regard as a root node
:param node:
:return: minimum node
|
[
"find",
"the",
"minimum",
"node",
"when",
"node",
"regard",
"as",
"a",
"root",
"node",
":",
"param",
"node",
":",
":",
"return",
":",
"minimum",
"node"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/red_black_tree/red_black_tree.py#L171-L180
|
train
|
keon/algorithms
|
algorithms/maths/modular_exponential.py
|
modular_exponential
|
def modular_exponential(base, exponent, mod):
"""Computes (base ^ exponent) % mod.
Time complexity - O(log n)
Use similar to Python in-built function pow."""
if exponent < 0:
raise ValueError("Exponent must be positive.")
base %= mod
result = 1
while exponent > 0:
# If the last bit is 1, add 2^k.
if exponent & 1:
result = (result * base) % mod
exponent = exponent >> 1
# Utilize modular multiplication properties to combine the computed mod C values.
base = (base * base) % mod
return result
|
python
|
def modular_exponential(base, exponent, mod):
"""Computes (base ^ exponent) % mod.
Time complexity - O(log n)
Use similar to Python in-built function pow."""
if exponent < 0:
raise ValueError("Exponent must be positive.")
base %= mod
result = 1
while exponent > 0:
# If the last bit is 1, add 2^k.
if exponent & 1:
result = (result * base) % mod
exponent = exponent >> 1
# Utilize modular multiplication properties to combine the computed mod C values.
base = (base * base) % mod
return result
|
[
"def",
"modular_exponential",
"(",
"base",
",",
"exponent",
",",
"mod",
")",
":",
"if",
"exponent",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Exponent must be positive.\"",
")",
"base",
"%=",
"mod",
"result",
"=",
"1",
"while",
"exponent",
">",
"0",
":",
"# If the last bit is 1, add 2^k.",
"if",
"exponent",
"&",
"1",
":",
"result",
"=",
"(",
"result",
"*",
"base",
")",
"%",
"mod",
"exponent",
"=",
"exponent",
">>",
"1",
"# Utilize modular multiplication properties to combine the computed mod C values.",
"base",
"=",
"(",
"base",
"*",
"base",
")",
"%",
"mod",
"return",
"result"
] |
Computes (base ^ exponent) % mod.
Time complexity - O(log n)
Use similar to Python in-built function pow.
|
[
"Computes",
"(",
"base",
"^",
"exponent",
")",
"%",
"mod",
".",
"Time",
"complexity",
"-",
"O",
"(",
"log",
"n",
")",
"Use",
"similar",
"to",
"Python",
"in",
"-",
"built",
"function",
"pow",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/modular_exponential.py#L1-L18
|
train
|
keon/algorithms
|
algorithms/sort/meeting_rooms.py
|
can_attend_meetings
|
def can_attend_meetings(intervals):
"""
:type intervals: List[Interval]
:rtype: bool
"""
intervals = sorted(intervals, key=lambda x: x.start)
for i in range(1, len(intervals)):
if intervals[i].start < intervals[i - 1].end:
return False
return True
|
python
|
def can_attend_meetings(intervals):
"""
:type intervals: List[Interval]
:rtype: bool
"""
intervals = sorted(intervals, key=lambda x: x.start)
for i in range(1, len(intervals)):
if intervals[i].start < intervals[i - 1].end:
return False
return True
|
[
"def",
"can_attend_meetings",
"(",
"intervals",
")",
":",
"intervals",
"=",
"sorted",
"(",
"intervals",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"start",
")",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"intervals",
")",
")",
":",
"if",
"intervals",
"[",
"i",
"]",
".",
"start",
"<",
"intervals",
"[",
"i",
"-",
"1",
"]",
".",
"end",
":",
"return",
"False",
"return",
"True"
] |
:type intervals: List[Interval]
:rtype: bool
|
[
":",
"type",
"intervals",
":",
"List",
"[",
"Interval",
"]",
":",
"rtype",
":",
"bool"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/meeting_rooms.py#L12-L21
|
train
|
keon/algorithms
|
algorithms/tree/bst/delete_node.py
|
Solution.delete_node
|
def delete_node(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
if not root: return None
if root.val == key:
if root.left:
# Find the right most leaf of the left sub-tree
left_right_most = root.left
while left_right_most.right:
left_right_most = left_right_most.right
# Attach right child to the right of that leaf
left_right_most.right = root.right
# Return left child instead of root, a.k.a delete root
return root.left
else:
return root.right
# If left or right child got deleted, the returned root is the child of the deleted node.
elif root.val > key:
root.left = self.deleteNode(root.left, key)
else:
root.right = self.deleteNode(root.right, key)
return root
|
python
|
def delete_node(self, root, key):
"""
:type root: TreeNode
:type key: int
:rtype: TreeNode
"""
if not root: return None
if root.val == key:
if root.left:
# Find the right most leaf of the left sub-tree
left_right_most = root.left
while left_right_most.right:
left_right_most = left_right_most.right
# Attach right child to the right of that leaf
left_right_most.right = root.right
# Return left child instead of root, a.k.a delete root
return root.left
else:
return root.right
# If left or right child got deleted, the returned root is the child of the deleted node.
elif root.val > key:
root.left = self.deleteNode(root.left, key)
else:
root.right = self.deleteNode(root.right, key)
return root
|
[
"def",
"delete_node",
"(",
"self",
",",
"root",
",",
"key",
")",
":",
"if",
"not",
"root",
":",
"return",
"None",
"if",
"root",
".",
"val",
"==",
"key",
":",
"if",
"root",
".",
"left",
":",
"# Find the right most leaf of the left sub-tree",
"left_right_most",
"=",
"root",
".",
"left",
"while",
"left_right_most",
".",
"right",
":",
"left_right_most",
"=",
"left_right_most",
".",
"right",
"# Attach right child to the right of that leaf",
"left_right_most",
".",
"right",
"=",
"root",
".",
"right",
"# Return left child instead of root, a.k.a delete root",
"return",
"root",
".",
"left",
"else",
":",
"return",
"root",
".",
"right",
"# If left or right child got deleted, the returned root is the child of the deleted node.",
"elif",
"root",
".",
"val",
">",
"key",
":",
"root",
".",
"left",
"=",
"self",
".",
"deleteNode",
"(",
"root",
".",
"left",
",",
"key",
")",
"else",
":",
"root",
".",
"right",
"=",
"self",
".",
"deleteNode",
"(",
"root",
".",
"right",
",",
"key",
")",
"return",
"root"
] |
:type root: TreeNode
:type key: int
:rtype: TreeNode
|
[
":",
"type",
"root",
":",
"TreeNode",
":",
"type",
"key",
":",
"int",
":",
"rtype",
":",
"TreeNode"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/bst/delete_node.py#L41-L66
|
train
|
keon/algorithms
|
algorithms/stack/simplify_path.py
|
simplify_path
|
def simplify_path(path):
"""
:type path: str
:rtype: str
"""
skip = {'..', '.', ''}
stack = []
paths = path.split('/')
for tok in paths:
if tok == '..':
if stack:
stack.pop()
elif tok not in skip:
stack.append(tok)
return '/' + '/'.join(stack)
|
python
|
def simplify_path(path):
"""
:type path: str
:rtype: str
"""
skip = {'..', '.', ''}
stack = []
paths = path.split('/')
for tok in paths:
if tok == '..':
if stack:
stack.pop()
elif tok not in skip:
stack.append(tok)
return '/' + '/'.join(stack)
|
[
"def",
"simplify_path",
"(",
"path",
")",
":",
"skip",
"=",
"{",
"'..'",
",",
"'.'",
",",
"''",
"}",
"stack",
"=",
"[",
"]",
"paths",
"=",
"path",
".",
"split",
"(",
"'/'",
")",
"for",
"tok",
"in",
"paths",
":",
"if",
"tok",
"==",
"'..'",
":",
"if",
"stack",
":",
"stack",
".",
"pop",
"(",
")",
"elif",
"tok",
"not",
"in",
"skip",
":",
"stack",
".",
"append",
"(",
"tok",
")",
"return",
"'/'",
"+",
"'/'",
".",
"join",
"(",
"stack",
")"
] |
:type path: str
:rtype: str
|
[
":",
"type",
"path",
":",
"str",
":",
"rtype",
":",
"str"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/stack/simplify_path.py#L13-L27
|
train
|
keon/algorithms
|
algorithms/backtrack/subsets.py
|
subsets
|
def subsets(nums):
"""
O(2**n)
"""
def backtrack(res, nums, stack, pos):
if pos == len(nums):
res.append(list(stack))
else:
# take nums[pos]
stack.append(nums[pos])
backtrack(res, nums, stack, pos+1)
stack.pop()
# dont take nums[pos]
backtrack(res, nums, stack, pos+1)
res = []
backtrack(res, nums, [], 0)
return res
|
python
|
def subsets(nums):
"""
O(2**n)
"""
def backtrack(res, nums, stack, pos):
if pos == len(nums):
res.append(list(stack))
else:
# take nums[pos]
stack.append(nums[pos])
backtrack(res, nums, stack, pos+1)
stack.pop()
# dont take nums[pos]
backtrack(res, nums, stack, pos+1)
res = []
backtrack(res, nums, [], 0)
return res
|
[
"def",
"subsets",
"(",
"nums",
")",
":",
"def",
"backtrack",
"(",
"res",
",",
"nums",
",",
"stack",
",",
"pos",
")",
":",
"if",
"pos",
"==",
"len",
"(",
"nums",
")",
":",
"res",
".",
"append",
"(",
"list",
"(",
"stack",
")",
")",
"else",
":",
"# take nums[pos]",
"stack",
".",
"append",
"(",
"nums",
"[",
"pos",
"]",
")",
"backtrack",
"(",
"res",
",",
"nums",
",",
"stack",
",",
"pos",
"+",
"1",
")",
"stack",
".",
"pop",
"(",
")",
"# dont take nums[pos]",
"backtrack",
"(",
"res",
",",
"nums",
",",
"stack",
",",
"pos",
"+",
"1",
")",
"res",
"=",
"[",
"]",
"backtrack",
"(",
"res",
",",
"nums",
",",
"[",
"]",
",",
"0",
")",
"return",
"res"
] |
O(2**n)
|
[
"O",
"(",
"2",
"**",
"n",
")"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/backtrack/subsets.py#L22-L39
|
train
|
keon/algorithms
|
algorithms/search/jump_search.py
|
jump_search
|
def jump_search(arr,target):
"""Jump Search
Worst-case Complexity: O(√n) (root(n))
All items in list must be sorted like binary search
Find block that contains target value and search it linearly in that block
It returns a first target value in array
reference: https://en.wikipedia.org/wiki/Jump_search
"""
n = len(arr)
block_size = int(math.sqrt(n))
block_prev = 0
block= block_size
# return -1 means that array doesn't contain taget value
# find block that contains target value
if arr[n - 1] < target:
return -1
while block <= n and arr[block - 1] < target:
block_prev = block
block += block_size
# find target value in block
while arr[block_prev] < target :
block_prev += 1
if block_prev == min(block, n) :
return -1
# if there is target value in array, return it
if arr[block_prev] == target :
return block_prev
else :
return -1
|
python
|
def jump_search(arr,target):
"""Jump Search
Worst-case Complexity: O(√n) (root(n))
All items in list must be sorted like binary search
Find block that contains target value and search it linearly in that block
It returns a first target value in array
reference: https://en.wikipedia.org/wiki/Jump_search
"""
n = len(arr)
block_size = int(math.sqrt(n))
block_prev = 0
block= block_size
# return -1 means that array doesn't contain taget value
# find block that contains target value
if arr[n - 1] < target:
return -1
while block <= n and arr[block - 1] < target:
block_prev = block
block += block_size
# find target value in block
while arr[block_prev] < target :
block_prev += 1
if block_prev == min(block, n) :
return -1
# if there is target value in array, return it
if arr[block_prev] == target :
return block_prev
else :
return -1
|
[
"def",
"jump_search",
"(",
"arr",
",",
"target",
")",
":",
"n",
"=",
"len",
"(",
"arr",
")",
"block_size",
"=",
"int",
"(",
"math",
".",
"sqrt",
"(",
"n",
")",
")",
"block_prev",
"=",
"0",
"block",
"=",
"block_size",
"# return -1 means that array doesn't contain taget value",
"# find block that contains target value",
"if",
"arr",
"[",
"n",
"-",
"1",
"]",
"<",
"target",
":",
"return",
"-",
"1",
"while",
"block",
"<=",
"n",
"and",
"arr",
"[",
"block",
"-",
"1",
"]",
"<",
"target",
":",
"block_prev",
"=",
"block",
"block",
"+=",
"block_size",
"# find target value in block",
"while",
"arr",
"[",
"block_prev",
"]",
"<",
"target",
":",
"block_prev",
"+=",
"1",
"if",
"block_prev",
"==",
"min",
"(",
"block",
",",
"n",
")",
":",
"return",
"-",
"1",
"# if there is target value in array, return it",
"if",
"arr",
"[",
"block_prev",
"]",
"==",
"target",
":",
"return",
"block_prev",
"else",
":",
"return",
"-",
"1"
] |
Jump Search
Worst-case Complexity: O(√n) (root(n))
All items in list must be sorted like binary search
Find block that contains target value and search it linearly in that block
It returns a first target value in array
reference: https://en.wikipedia.org/wiki/Jump_search
|
[
"Jump",
"Search",
"Worst",
"-",
"case",
"Complexity",
":",
"O",
"(",
"√n",
")",
"(",
"root",
"(",
"n",
"))",
"All",
"items",
"in",
"list",
"must",
"be",
"sorted",
"like",
"binary",
"search"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/search/jump_search.py#L3-L40
|
train
|
keon/algorithms
|
algorithms/arrays/flatten.py
|
flatten_iter
|
def flatten_iter(iterable):
"""
Takes as input multi dimensional iterable and
returns generator which produces one dimensional output.
"""
for element in iterable:
if isinstance(element, Iterable):
yield from flatten_iter(element)
else:
yield element
|
python
|
def flatten_iter(iterable):
"""
Takes as input multi dimensional iterable and
returns generator which produces one dimensional output.
"""
for element in iterable:
if isinstance(element, Iterable):
yield from flatten_iter(element)
else:
yield element
|
[
"def",
"flatten_iter",
"(",
"iterable",
")",
":",
"for",
"element",
"in",
"iterable",
":",
"if",
"isinstance",
"(",
"element",
",",
"Iterable",
")",
":",
"yield",
"from",
"flatten_iter",
"(",
"element",
")",
"else",
":",
"yield",
"element"
] |
Takes as input multi dimensional iterable and
returns generator which produces one dimensional output.
|
[
"Takes",
"as",
"input",
"multi",
"dimensional",
"iterable",
"and",
"returns",
"generator",
"which",
"produces",
"one",
"dimensional",
"output",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/flatten.py#L22-L31
|
train
|
keon/algorithms
|
algorithms/bfs/word_ladder.py
|
ladder_length
|
def ladder_length(begin_word, end_word, word_list):
"""
Bidirectional BFS!!!
:type begin_word: str
:type end_word: str
:type word_list: Set[str]
:rtype: int
"""
if len(begin_word) != len(end_word):
return -1 # not possible
if begin_word == end_word:
return 0
# when only differ by 1 character
if sum(c1 != c2 for c1, c2 in zip(begin_word, end_word)) == 1:
return 1
begin_set = set()
end_set = set()
begin_set.add(begin_word)
end_set.add(end_word)
result = 2
while begin_set and end_set:
if len(begin_set) > len(end_set):
begin_set, end_set = end_set, begin_set
next_begin_set = set()
for word in begin_set:
for ladder_word in word_range(word):
if ladder_word in end_set:
return result
if ladder_word in word_list:
next_begin_set.add(ladder_word)
word_list.remove(ladder_word)
begin_set = next_begin_set
result += 1
# print(begin_set)
# print(result)
return -1
|
python
|
def ladder_length(begin_word, end_word, word_list):
"""
Bidirectional BFS!!!
:type begin_word: str
:type end_word: str
:type word_list: Set[str]
:rtype: int
"""
if len(begin_word) != len(end_word):
return -1 # not possible
if begin_word == end_word:
return 0
# when only differ by 1 character
if sum(c1 != c2 for c1, c2 in zip(begin_word, end_word)) == 1:
return 1
begin_set = set()
end_set = set()
begin_set.add(begin_word)
end_set.add(end_word)
result = 2
while begin_set and end_set:
if len(begin_set) > len(end_set):
begin_set, end_set = end_set, begin_set
next_begin_set = set()
for word in begin_set:
for ladder_word in word_range(word):
if ladder_word in end_set:
return result
if ladder_word in word_list:
next_begin_set.add(ladder_word)
word_list.remove(ladder_word)
begin_set = next_begin_set
result += 1
# print(begin_set)
# print(result)
return -1
|
[
"def",
"ladder_length",
"(",
"begin_word",
",",
"end_word",
",",
"word_list",
")",
":",
"if",
"len",
"(",
"begin_word",
")",
"!=",
"len",
"(",
"end_word",
")",
":",
"return",
"-",
"1",
"# not possible",
"if",
"begin_word",
"==",
"end_word",
":",
"return",
"0",
"# when only differ by 1 character",
"if",
"sum",
"(",
"c1",
"!=",
"c2",
"for",
"c1",
",",
"c2",
"in",
"zip",
"(",
"begin_word",
",",
"end_word",
")",
")",
"==",
"1",
":",
"return",
"1",
"begin_set",
"=",
"set",
"(",
")",
"end_set",
"=",
"set",
"(",
")",
"begin_set",
".",
"add",
"(",
"begin_word",
")",
"end_set",
".",
"add",
"(",
"end_word",
")",
"result",
"=",
"2",
"while",
"begin_set",
"and",
"end_set",
":",
"if",
"len",
"(",
"begin_set",
")",
">",
"len",
"(",
"end_set",
")",
":",
"begin_set",
",",
"end_set",
"=",
"end_set",
",",
"begin_set",
"next_begin_set",
"=",
"set",
"(",
")",
"for",
"word",
"in",
"begin_set",
":",
"for",
"ladder_word",
"in",
"word_range",
"(",
"word",
")",
":",
"if",
"ladder_word",
"in",
"end_set",
":",
"return",
"result",
"if",
"ladder_word",
"in",
"word_list",
":",
"next_begin_set",
".",
"add",
"(",
"ladder_word",
")",
"word_list",
".",
"remove",
"(",
"ladder_word",
")",
"begin_set",
"=",
"next_begin_set",
"result",
"+=",
"1",
"# print(begin_set)",
"# print(result)",
"return",
"-",
"1"
] |
Bidirectional BFS!!!
:type begin_word: str
:type end_word: str
:type word_list: Set[str]
:rtype: int
|
[
"Bidirectional",
"BFS!!!",
":",
"type",
"begin_word",
":",
"str",
":",
"type",
"end_word",
":",
"str",
":",
"type",
"word_list",
":",
"Set",
"[",
"str",
"]",
":",
"rtype",
":",
"int"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/bfs/word_ladder.py#L24-L64
|
train
|
keon/algorithms
|
algorithms/iterables/convolved.py
|
convolved
|
def convolved(iterable, kernel_size=1, stride=1, padding=0, default_value=None):
"""Iterable to get every convolution window per loop iteration.
For example:
`convolved([1, 2, 3, 4], kernel_size=2)`
will produce the following result:
`[[1, 2], [2, 3], [3, 4]]`.
`convolved([1, 2, 3], kernel_size=2, stride=1, padding=2, default_value=42)`
will produce the following result:
`[[42, 42], [42, 1], [1, 2], [2, 3], [3, 42], [42, 42]]`
Arguments:
iterable: An object to iterate on. It should support slice indexing if `padding == 0`.
kernel_size: The number of items yielded at every iteration.
stride: The step size between each iteration.
padding: Padding must be an integer or a string with value `SAME` or `VALID`. If it is an integer, it represents
how many values we add with `default_value` on the borders. If it is a string, `SAME` means that the
convolution will add some padding according to the kernel_size, and `VALID` is the same as
specifying `padding=0`.
default_value: Default fill value for padding and values outside iteration range.
For more information, refer to:
- https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py
- https://github.com/guillaume-chevalier/python-conv-lib
- MIT License, Copyright (c) 2018 Guillaume Chevalier
"""
# Input validation and error messages
if not hasattr(iterable, '__iter__'):
raise ValueError(
"Can't iterate on object.".format(
iterable))
if stride < 1:
raise ValueError(
"Stride must be of at least one. Got `stride={}`.".format(
stride))
if not (padding in ['SAME', 'VALID'] or type(padding) in [int]):
raise ValueError(
"Padding must be an integer or a string with value `SAME` or `VALID`.")
if not isinstance(padding, str):
if padding < 0:
raise ValueError(
"Padding must be of at least zero. Got `padding={}`.".format(
padding))
else:
if padding == 'SAME':
padding = kernel_size // 2
elif padding == 'VALID':
padding = 0
if not type(iterable) == list:
iterable = list(iterable)
# Add padding to iterable
if padding > 0:
pad = [default_value] * padding
iterable = pad + list(iterable) + pad
# Fill missing value to the right
remainder = (kernel_size - len(iterable)) % stride
extra_pad = [default_value] * remainder
iterable = iterable + extra_pad
i = 0
while True:
if i > len(iterable) - kernel_size:
break
yield iterable[i:i + kernel_size]
i += stride
|
python
|
def convolved(iterable, kernel_size=1, stride=1, padding=0, default_value=None):
"""Iterable to get every convolution window per loop iteration.
For example:
`convolved([1, 2, 3, 4], kernel_size=2)`
will produce the following result:
`[[1, 2], [2, 3], [3, 4]]`.
`convolved([1, 2, 3], kernel_size=2, stride=1, padding=2, default_value=42)`
will produce the following result:
`[[42, 42], [42, 1], [1, 2], [2, 3], [3, 42], [42, 42]]`
Arguments:
iterable: An object to iterate on. It should support slice indexing if `padding == 0`.
kernel_size: The number of items yielded at every iteration.
stride: The step size between each iteration.
padding: Padding must be an integer or a string with value `SAME` or `VALID`. If it is an integer, it represents
how many values we add with `default_value` on the borders. If it is a string, `SAME` means that the
convolution will add some padding according to the kernel_size, and `VALID` is the same as
specifying `padding=0`.
default_value: Default fill value for padding and values outside iteration range.
For more information, refer to:
- https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py
- https://github.com/guillaume-chevalier/python-conv-lib
- MIT License, Copyright (c) 2018 Guillaume Chevalier
"""
# Input validation and error messages
if not hasattr(iterable, '__iter__'):
raise ValueError(
"Can't iterate on object.".format(
iterable))
if stride < 1:
raise ValueError(
"Stride must be of at least one. Got `stride={}`.".format(
stride))
if not (padding in ['SAME', 'VALID'] or type(padding) in [int]):
raise ValueError(
"Padding must be an integer or a string with value `SAME` or `VALID`.")
if not isinstance(padding, str):
if padding < 0:
raise ValueError(
"Padding must be of at least zero. Got `padding={}`.".format(
padding))
else:
if padding == 'SAME':
padding = kernel_size // 2
elif padding == 'VALID':
padding = 0
if not type(iterable) == list:
iterable = list(iterable)
# Add padding to iterable
if padding > 0:
pad = [default_value] * padding
iterable = pad + list(iterable) + pad
# Fill missing value to the right
remainder = (kernel_size - len(iterable)) % stride
extra_pad = [default_value] * remainder
iterable = iterable + extra_pad
i = 0
while True:
if i > len(iterable) - kernel_size:
break
yield iterable[i:i + kernel_size]
i += stride
|
[
"def",
"convolved",
"(",
"iterable",
",",
"kernel_size",
"=",
"1",
",",
"stride",
"=",
"1",
",",
"padding",
"=",
"0",
",",
"default_value",
"=",
"None",
")",
":",
"# Input validation and error messages",
"if",
"not",
"hasattr",
"(",
"iterable",
",",
"'__iter__'",
")",
":",
"raise",
"ValueError",
"(",
"\"Can't iterate on object.\"",
".",
"format",
"(",
"iterable",
")",
")",
"if",
"stride",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"Stride must be of at least one. Got `stride={}`.\"",
".",
"format",
"(",
"stride",
")",
")",
"if",
"not",
"(",
"padding",
"in",
"[",
"'SAME'",
",",
"'VALID'",
"]",
"or",
"type",
"(",
"padding",
")",
"in",
"[",
"int",
"]",
")",
":",
"raise",
"ValueError",
"(",
"\"Padding must be an integer or a string with value `SAME` or `VALID`.\"",
")",
"if",
"not",
"isinstance",
"(",
"padding",
",",
"str",
")",
":",
"if",
"padding",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"Padding must be of at least zero. Got `padding={}`.\"",
".",
"format",
"(",
"padding",
")",
")",
"else",
":",
"if",
"padding",
"==",
"'SAME'",
":",
"padding",
"=",
"kernel_size",
"//",
"2",
"elif",
"padding",
"==",
"'VALID'",
":",
"padding",
"=",
"0",
"if",
"not",
"type",
"(",
"iterable",
")",
"==",
"list",
":",
"iterable",
"=",
"list",
"(",
"iterable",
")",
"# Add padding to iterable",
"if",
"padding",
">",
"0",
":",
"pad",
"=",
"[",
"default_value",
"]",
"*",
"padding",
"iterable",
"=",
"pad",
"+",
"list",
"(",
"iterable",
")",
"+",
"pad",
"# Fill missing value to the right",
"remainder",
"=",
"(",
"kernel_size",
"-",
"len",
"(",
"iterable",
")",
")",
"%",
"stride",
"extra_pad",
"=",
"[",
"default_value",
"]",
"*",
"remainder",
"iterable",
"=",
"iterable",
"+",
"extra_pad",
"i",
"=",
"0",
"while",
"True",
":",
"if",
"i",
">",
"len",
"(",
"iterable",
")",
"-",
"kernel_size",
":",
"break",
"yield",
"iterable",
"[",
"i",
":",
"i",
"+",
"kernel_size",
"]",
"i",
"+=",
"stride"
] |
Iterable to get every convolution window per loop iteration.
For example:
`convolved([1, 2, 3, 4], kernel_size=2)`
will produce the following result:
`[[1, 2], [2, 3], [3, 4]]`.
`convolved([1, 2, 3], kernel_size=2, stride=1, padding=2, default_value=42)`
will produce the following result:
`[[42, 42], [42, 1], [1, 2], [2, 3], [3, 42], [42, 42]]`
Arguments:
iterable: An object to iterate on. It should support slice indexing if `padding == 0`.
kernel_size: The number of items yielded at every iteration.
stride: The step size between each iteration.
padding: Padding must be an integer or a string with value `SAME` or `VALID`. If it is an integer, it represents
how many values we add with `default_value` on the borders. If it is a string, `SAME` means that the
convolution will add some padding according to the kernel_size, and `VALID` is the same as
specifying `padding=0`.
default_value: Default fill value for padding and values outside iteration range.
For more information, refer to:
- https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py
- https://github.com/guillaume-chevalier/python-conv-lib
- MIT License, Copyright (c) 2018 Guillaume Chevalier
|
[
"Iterable",
"to",
"get",
"every",
"convolution",
"window",
"per",
"loop",
"iteration",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/iterables/convolved.py#L28-L94
|
train
|
keon/algorithms
|
algorithms/iterables/convolved.py
|
convolved_1d
|
def convolved_1d(iterable, kernel_size=1, stride=1, padding=0, default_value=None):
"""1D Iterable to get every convolution window per loop iteration.
For more information, refer to:
- https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py
- https://github.com/guillaume-chevalier/python-conv-lib
- MIT License, Copyright (c) 2018 Guillaume Chevalier
"""
return convolved(iterable, kernel_size, stride, padding, default_value)
|
python
|
def convolved_1d(iterable, kernel_size=1, stride=1, padding=0, default_value=None):
"""1D Iterable to get every convolution window per loop iteration.
For more information, refer to:
- https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py
- https://github.com/guillaume-chevalier/python-conv-lib
- MIT License, Copyright (c) 2018 Guillaume Chevalier
"""
return convolved(iterable, kernel_size, stride, padding, default_value)
|
[
"def",
"convolved_1d",
"(",
"iterable",
",",
"kernel_size",
"=",
"1",
",",
"stride",
"=",
"1",
",",
"padding",
"=",
"0",
",",
"default_value",
"=",
"None",
")",
":",
"return",
"convolved",
"(",
"iterable",
",",
"kernel_size",
",",
"stride",
",",
"padding",
",",
"default_value",
")"
] |
1D Iterable to get every convolution window per loop iteration.
For more information, refer to:
- https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py
- https://github.com/guillaume-chevalier/python-conv-lib
- MIT License, Copyright (c) 2018 Guillaume Chevalier
|
[
"1D",
"Iterable",
"to",
"get",
"every",
"convolution",
"window",
"per",
"loop",
"iteration",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/iterables/convolved.py#L96-L104
|
train
|
keon/algorithms
|
algorithms/iterables/convolved.py
|
convolved_2d
|
def convolved_2d(iterable, kernel_size=1, stride=1, padding=0, default_value=None):
"""2D Iterable to get every convolution window per loop iteration.
For more information, refer to:
- https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py
- https://github.com/guillaume-chevalier/python-conv-lib
- MIT License, Copyright (c) 2018 Guillaume Chevalier
"""
kernel_size = dimensionize(kernel_size, nd=2)
stride = dimensionize(stride, nd=2)
padding = dimensionize(padding, nd=2)
for row_packet in convolved(iterable, kernel_size[0], stride[0], padding[0], default_value):
transposed_inner = []
for col in tuple(row_packet):
transposed_inner.append(list(
convolved(col, kernel_size[1], stride[1], padding[1], default_value)
))
if len(transposed_inner) > 0:
for col_i in range(len(transposed_inner[0])):
yield tuple(row_j[col_i] for row_j in transposed_inner)
|
python
|
def convolved_2d(iterable, kernel_size=1, stride=1, padding=0, default_value=None):
"""2D Iterable to get every convolution window per loop iteration.
For more information, refer to:
- https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py
- https://github.com/guillaume-chevalier/python-conv-lib
- MIT License, Copyright (c) 2018 Guillaume Chevalier
"""
kernel_size = dimensionize(kernel_size, nd=2)
stride = dimensionize(stride, nd=2)
padding = dimensionize(padding, nd=2)
for row_packet in convolved(iterable, kernel_size[0], stride[0], padding[0], default_value):
transposed_inner = []
for col in tuple(row_packet):
transposed_inner.append(list(
convolved(col, kernel_size[1], stride[1], padding[1], default_value)
))
if len(transposed_inner) > 0:
for col_i in range(len(transposed_inner[0])):
yield tuple(row_j[col_i] for row_j in transposed_inner)
|
[
"def",
"convolved_2d",
"(",
"iterable",
",",
"kernel_size",
"=",
"1",
",",
"stride",
"=",
"1",
",",
"padding",
"=",
"0",
",",
"default_value",
"=",
"None",
")",
":",
"kernel_size",
"=",
"dimensionize",
"(",
"kernel_size",
",",
"nd",
"=",
"2",
")",
"stride",
"=",
"dimensionize",
"(",
"stride",
",",
"nd",
"=",
"2",
")",
"padding",
"=",
"dimensionize",
"(",
"padding",
",",
"nd",
"=",
"2",
")",
"for",
"row_packet",
"in",
"convolved",
"(",
"iterable",
",",
"kernel_size",
"[",
"0",
"]",
",",
"stride",
"[",
"0",
"]",
",",
"padding",
"[",
"0",
"]",
",",
"default_value",
")",
":",
"transposed_inner",
"=",
"[",
"]",
"for",
"col",
"in",
"tuple",
"(",
"row_packet",
")",
":",
"transposed_inner",
".",
"append",
"(",
"list",
"(",
"convolved",
"(",
"col",
",",
"kernel_size",
"[",
"1",
"]",
",",
"stride",
"[",
"1",
"]",
",",
"padding",
"[",
"1",
"]",
",",
"default_value",
")",
")",
")",
"if",
"len",
"(",
"transposed_inner",
")",
">",
"0",
":",
"for",
"col_i",
"in",
"range",
"(",
"len",
"(",
"transposed_inner",
"[",
"0",
"]",
")",
")",
":",
"yield",
"tuple",
"(",
"row_j",
"[",
"col_i",
"]",
"for",
"row_j",
"in",
"transposed_inner",
")"
] |
2D Iterable to get every convolution window per loop iteration.
For more information, refer to:
- https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py
- https://github.com/guillaume-chevalier/python-conv-lib
- MIT License, Copyright (c) 2018 Guillaume Chevalier
|
[
"2D",
"Iterable",
"to",
"get",
"every",
"convolution",
"window",
"per",
"loop",
"iteration",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/iterables/convolved.py#L107-L128
|
train
|
keon/algorithms
|
algorithms/iterables/convolved.py
|
dimensionize
|
def dimensionize(maybe_a_list, nd=2):
"""Convert integers to a list of integers to fit the number of dimensions if
the argument is not already a list.
For example:
`dimensionize(3, nd=2)`
will produce the following result:
`(3, 3)`.
`dimensionize([3, 1], nd=2)`
will produce the following result:
`[3, 1]`.
For more information, refer to:
- https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py
- https://github.com/guillaume-chevalier/python-conv-lib
- MIT License, Copyright (c) 2018 Guillaume Chevalier
"""
if not hasattr(maybe_a_list, '__iter__'):
# Argument is probably an integer so we map it to a list of size `nd`.
now_a_list = [maybe_a_list] * nd
return now_a_list
else:
# Argument is probably an `nd`-sized list.
return maybe_a_list
|
python
|
def dimensionize(maybe_a_list, nd=2):
"""Convert integers to a list of integers to fit the number of dimensions if
the argument is not already a list.
For example:
`dimensionize(3, nd=2)`
will produce the following result:
`(3, 3)`.
`dimensionize([3, 1], nd=2)`
will produce the following result:
`[3, 1]`.
For more information, refer to:
- https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py
- https://github.com/guillaume-chevalier/python-conv-lib
- MIT License, Copyright (c) 2018 Guillaume Chevalier
"""
if not hasattr(maybe_a_list, '__iter__'):
# Argument is probably an integer so we map it to a list of size `nd`.
now_a_list = [maybe_a_list] * nd
return now_a_list
else:
# Argument is probably an `nd`-sized list.
return maybe_a_list
|
[
"def",
"dimensionize",
"(",
"maybe_a_list",
",",
"nd",
"=",
"2",
")",
":",
"if",
"not",
"hasattr",
"(",
"maybe_a_list",
",",
"'__iter__'",
")",
":",
"# Argument is probably an integer so we map it to a list of size `nd`.",
"now_a_list",
"=",
"[",
"maybe_a_list",
"]",
"*",
"nd",
"return",
"now_a_list",
"else",
":",
"# Argument is probably an `nd`-sized list.",
"return",
"maybe_a_list"
] |
Convert integers to a list of integers to fit the number of dimensions if
the argument is not already a list.
For example:
`dimensionize(3, nd=2)`
will produce the following result:
`(3, 3)`.
`dimensionize([3, 1], nd=2)`
will produce the following result:
`[3, 1]`.
For more information, refer to:
- https://github.com/guillaume-chevalier/python-conv-lib/blob/master/conv/conv.py
- https://github.com/guillaume-chevalier/python-conv-lib
- MIT License, Copyright (c) 2018 Guillaume Chevalier
|
[
"Convert",
"integers",
"to",
"a",
"list",
"of",
"integers",
"to",
"fit",
"the",
"number",
"of",
"dimensions",
"if",
"the",
"argument",
"is",
"not",
"already",
"a",
"list",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/iterables/convolved.py#L131-L154
|
train
|
keon/algorithms
|
algorithms/heap/sliding_window_max.py
|
max_sliding_window
|
def max_sliding_window(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if not nums:
return nums
queue = collections.deque()
res = []
for num in nums:
if len(queue) < k:
queue.append(num)
else:
res.append(max(queue))
queue.popleft()
queue.append(num)
res.append(max(queue))
return res
|
python
|
def max_sliding_window(nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
if not nums:
return nums
queue = collections.deque()
res = []
for num in nums:
if len(queue) < k:
queue.append(num)
else:
res.append(max(queue))
queue.popleft()
queue.append(num)
res.append(max(queue))
return res
|
[
"def",
"max_sliding_window",
"(",
"nums",
",",
"k",
")",
":",
"if",
"not",
"nums",
":",
"return",
"nums",
"queue",
"=",
"collections",
".",
"deque",
"(",
")",
"res",
"=",
"[",
"]",
"for",
"num",
"in",
"nums",
":",
"if",
"len",
"(",
"queue",
")",
"<",
"k",
":",
"queue",
".",
"append",
"(",
"num",
")",
"else",
":",
"res",
".",
"append",
"(",
"max",
"(",
"queue",
")",
")",
"queue",
".",
"popleft",
"(",
")",
"queue",
".",
"append",
"(",
"num",
")",
"res",
".",
"append",
"(",
"max",
"(",
"queue",
")",
")",
"return",
"res"
] |
:type nums: List[int]
:type k: int
:rtype: List[int]
|
[
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"type",
"k",
":",
"int",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/heap/sliding_window_max.py#L23-L41
|
train
|
keon/algorithms
|
algorithms/arrays/merge_intervals.py
|
merge_intervals
|
def merge_intervals(intervals):
""" Merge intervals in the form of a list. """
if intervals is None:
return None
intervals.sort(key=lambda i: i[0])
out = [intervals.pop(0)]
for i in intervals:
if out[-1][-1] >= i[0]:
out[-1][-1] = max(out[-1][-1], i[-1])
else:
out.append(i)
return out
|
python
|
def merge_intervals(intervals):
""" Merge intervals in the form of a list. """
if intervals is None:
return None
intervals.sort(key=lambda i: i[0])
out = [intervals.pop(0)]
for i in intervals:
if out[-1][-1] >= i[0]:
out[-1][-1] = max(out[-1][-1], i[-1])
else:
out.append(i)
return out
|
[
"def",
"merge_intervals",
"(",
"intervals",
")",
":",
"if",
"intervals",
"is",
"None",
":",
"return",
"None",
"intervals",
".",
"sort",
"(",
"key",
"=",
"lambda",
"i",
":",
"i",
"[",
"0",
"]",
")",
"out",
"=",
"[",
"intervals",
".",
"pop",
"(",
"0",
")",
"]",
"for",
"i",
"in",
"intervals",
":",
"if",
"out",
"[",
"-",
"1",
"]",
"[",
"-",
"1",
"]",
">=",
"i",
"[",
"0",
"]",
":",
"out",
"[",
"-",
"1",
"]",
"[",
"-",
"1",
"]",
"=",
"max",
"(",
"out",
"[",
"-",
"1",
"]",
"[",
"-",
"1",
"]",
",",
"i",
"[",
"-",
"1",
"]",
")",
"else",
":",
"out",
".",
"append",
"(",
"i",
")",
"return",
"out"
] |
Merge intervals in the form of a list.
|
[
"Merge",
"intervals",
"in",
"the",
"form",
"of",
"a",
"list",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/merge_intervals.py#L66-L77
|
train
|
keon/algorithms
|
algorithms/arrays/merge_intervals.py
|
Interval.merge
|
def merge(intervals):
""" Merge two intervals into one. """
out = []
for i in sorted(intervals, key=lambda i: i.start):
if out and i.start <= out[-1].end:
out[-1].end = max(out[-1].end, i.end)
else:
out += i,
return out
|
python
|
def merge(intervals):
""" Merge two intervals into one. """
out = []
for i in sorted(intervals, key=lambda i: i.start):
if out and i.start <= out[-1].end:
out[-1].end = max(out[-1].end, i.end)
else:
out += i,
return out
|
[
"def",
"merge",
"(",
"intervals",
")",
":",
"out",
"=",
"[",
"]",
"for",
"i",
"in",
"sorted",
"(",
"intervals",
",",
"key",
"=",
"lambda",
"i",
":",
"i",
".",
"start",
")",
":",
"if",
"out",
"and",
"i",
".",
"start",
"<=",
"out",
"[",
"-",
"1",
"]",
".",
"end",
":",
"out",
"[",
"-",
"1",
"]",
".",
"end",
"=",
"max",
"(",
"out",
"[",
"-",
"1",
"]",
".",
"end",
",",
"i",
".",
"end",
")",
"else",
":",
"out",
"+=",
"i",
",",
"return",
"out"
] |
Merge two intervals into one.
|
[
"Merge",
"two",
"intervals",
"into",
"one",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/merge_intervals.py#L47-L55
|
train
|
keon/algorithms
|
algorithms/arrays/merge_intervals.py
|
Interval.print_intervals
|
def print_intervals(intervals):
""" Print out the intervals. """
res = []
for i in intervals:
res.append(repr(i))
print("".join(res))
|
python
|
def print_intervals(intervals):
""" Print out the intervals. """
res = []
for i in intervals:
res.append(repr(i))
print("".join(res))
|
[
"def",
"print_intervals",
"(",
"intervals",
")",
":",
"res",
"=",
"[",
"]",
"for",
"i",
"in",
"intervals",
":",
"res",
".",
"append",
"(",
"repr",
"(",
"i",
")",
")",
"print",
"(",
"\"\"",
".",
"join",
"(",
"res",
")",
")"
] |
Print out the intervals.
|
[
"Print",
"out",
"the",
"intervals",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/merge_intervals.py#L58-L63
|
train
|
keon/algorithms
|
algorithms/arrays/rotate.py
|
rotate_v1
|
def rotate_v1(array, k):
"""
Rotate the entire array 'k' times
T(n)- O(nk)
:type array: List[int]
:type k: int
:rtype: void Do not return anything, modify array in-place instead.
"""
array = array[:]
n = len(array)
for i in range(k): # unused variable is not a problem
temp = array[n - 1]
for j in range(n-1, 0, -1):
array[j] = array[j - 1]
array[0] = temp
return array
|
python
|
def rotate_v1(array, k):
"""
Rotate the entire array 'k' times
T(n)- O(nk)
:type array: List[int]
:type k: int
:rtype: void Do not return anything, modify array in-place instead.
"""
array = array[:]
n = len(array)
for i in range(k): # unused variable is not a problem
temp = array[n - 1]
for j in range(n-1, 0, -1):
array[j] = array[j - 1]
array[0] = temp
return array
|
[
"def",
"rotate_v1",
"(",
"array",
",",
"k",
")",
":",
"array",
"=",
"array",
"[",
":",
"]",
"n",
"=",
"len",
"(",
"array",
")",
"for",
"i",
"in",
"range",
"(",
"k",
")",
":",
"# unused variable is not a problem",
"temp",
"=",
"array",
"[",
"n",
"-",
"1",
"]",
"for",
"j",
"in",
"range",
"(",
"n",
"-",
"1",
",",
"0",
",",
"-",
"1",
")",
":",
"array",
"[",
"j",
"]",
"=",
"array",
"[",
"j",
"-",
"1",
"]",
"array",
"[",
"0",
"]",
"=",
"temp",
"return",
"array"
] |
Rotate the entire array 'k' times
T(n)- O(nk)
:type array: List[int]
:type k: int
:rtype: void Do not return anything, modify array in-place instead.
|
[
"Rotate",
"the",
"entire",
"array",
"k",
"times",
"T",
"(",
"n",
")",
"-",
"O",
"(",
"nk",
")"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/rotate.py#L13-L29
|
train
|
keon/algorithms
|
algorithms/arrays/rotate.py
|
rotate_v2
|
def rotate_v2(array, k):
"""
Reverse segments of the array, followed by the entire array
T(n)- O(n)
:type array: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
array = array[:]
def reverse(arr, a, b):
while a < b:
arr[a], arr[b] = arr[b], arr[a]
a += 1
b -= 1
n = len(array)
k = k % n
reverse(array, 0, n - k - 1)
reverse(array, n - k, n - 1)
reverse(array, 0, n - 1)
return array
|
python
|
def rotate_v2(array, k):
"""
Reverse segments of the array, followed by the entire array
T(n)- O(n)
:type array: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
array = array[:]
def reverse(arr, a, b):
while a < b:
arr[a], arr[b] = arr[b], arr[a]
a += 1
b -= 1
n = len(array)
k = k % n
reverse(array, 0, n - k - 1)
reverse(array, n - k, n - 1)
reverse(array, 0, n - 1)
return array
|
[
"def",
"rotate_v2",
"(",
"array",
",",
"k",
")",
":",
"array",
"=",
"array",
"[",
":",
"]",
"def",
"reverse",
"(",
"arr",
",",
"a",
",",
"b",
")",
":",
"while",
"a",
"<",
"b",
":",
"arr",
"[",
"a",
"]",
",",
"arr",
"[",
"b",
"]",
"=",
"arr",
"[",
"b",
"]",
",",
"arr",
"[",
"a",
"]",
"a",
"+=",
"1",
"b",
"-=",
"1",
"n",
"=",
"len",
"(",
"array",
")",
"k",
"=",
"k",
"%",
"n",
"reverse",
"(",
"array",
",",
"0",
",",
"n",
"-",
"k",
"-",
"1",
")",
"reverse",
"(",
"array",
",",
"n",
"-",
"k",
",",
"n",
"-",
"1",
")",
"reverse",
"(",
"array",
",",
"0",
",",
"n",
"-",
"1",
")",
"return",
"array"
] |
Reverse segments of the array, followed by the entire array
T(n)- O(n)
:type array: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
|
[
"Reverse",
"segments",
"of",
"the",
"array",
"followed",
"by",
"the",
"entire",
"array",
"T",
"(",
"n",
")",
"-",
"O",
"(",
"n",
")",
":",
"type",
"array",
":",
"List",
"[",
"int",
"]",
":",
"type",
"k",
":",
"int",
":",
"rtype",
":",
"void",
"Do",
"not",
"return",
"anything",
"modify",
"nums",
"in",
"-",
"place",
"instead",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/rotate.py#L32-L53
|
train
|
keon/algorithms
|
algorithms/dfs/pacific_atlantic.py
|
pacific_atlantic
|
def pacific_atlantic(matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
n = len(matrix)
if not n: return []
m = len(matrix[0])
if not m: return []
res = []
atlantic = [[False for _ in range (n)] for _ in range(m)]
pacific = [[False for _ in range (n)] for _ in range(m)]
for i in range(n):
dfs(pacific, matrix, float("-inf"), i, 0)
dfs(atlantic, matrix, float("-inf"), i, m-1)
for i in range(m):
dfs(pacific, matrix, float("-inf"), 0, i)
dfs(atlantic, matrix, float("-inf"), n-1, i)
for i in range(n):
for j in range(m):
if pacific[i][j] and atlantic[i][j]:
res.append([i, j])
return res
|
python
|
def pacific_atlantic(matrix):
"""
:type matrix: List[List[int]]
:rtype: List[List[int]]
"""
n = len(matrix)
if not n: return []
m = len(matrix[0])
if not m: return []
res = []
atlantic = [[False for _ in range (n)] for _ in range(m)]
pacific = [[False for _ in range (n)] for _ in range(m)]
for i in range(n):
dfs(pacific, matrix, float("-inf"), i, 0)
dfs(atlantic, matrix, float("-inf"), i, m-1)
for i in range(m):
dfs(pacific, matrix, float("-inf"), 0, i)
dfs(atlantic, matrix, float("-inf"), n-1, i)
for i in range(n):
for j in range(m):
if pacific[i][j] and atlantic[i][j]:
res.append([i, j])
return res
|
[
"def",
"pacific_atlantic",
"(",
"matrix",
")",
":",
"n",
"=",
"len",
"(",
"matrix",
")",
"if",
"not",
"n",
":",
"return",
"[",
"]",
"m",
"=",
"len",
"(",
"matrix",
"[",
"0",
"]",
")",
"if",
"not",
"m",
":",
"return",
"[",
"]",
"res",
"=",
"[",
"]",
"atlantic",
"=",
"[",
"[",
"False",
"for",
"_",
"in",
"range",
"(",
"n",
")",
"]",
"for",
"_",
"in",
"range",
"(",
"m",
")",
"]",
"pacific",
"=",
"[",
"[",
"False",
"for",
"_",
"in",
"range",
"(",
"n",
")",
"]",
"for",
"_",
"in",
"range",
"(",
"m",
")",
"]",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"dfs",
"(",
"pacific",
",",
"matrix",
",",
"float",
"(",
"\"-inf\"",
")",
",",
"i",
",",
"0",
")",
"dfs",
"(",
"atlantic",
",",
"matrix",
",",
"float",
"(",
"\"-inf\"",
")",
",",
"i",
",",
"m",
"-",
"1",
")",
"for",
"i",
"in",
"range",
"(",
"m",
")",
":",
"dfs",
"(",
"pacific",
",",
"matrix",
",",
"float",
"(",
"\"-inf\"",
")",
",",
"0",
",",
"i",
")",
"dfs",
"(",
"atlantic",
",",
"matrix",
",",
"float",
"(",
"\"-inf\"",
")",
",",
"n",
"-",
"1",
",",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"n",
")",
":",
"for",
"j",
"in",
"range",
"(",
"m",
")",
":",
"if",
"pacific",
"[",
"i",
"]",
"[",
"j",
"]",
"and",
"atlantic",
"[",
"i",
"]",
"[",
"j",
"]",
":",
"res",
".",
"append",
"(",
"[",
"i",
",",
"j",
"]",
")",
"return",
"res"
] |
:type matrix: List[List[int]]
:rtype: List[List[int]]
|
[
":",
"type",
"matrix",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"rtype",
":",
"List",
"[",
"List",
"[",
"int",
"]]"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dfs/pacific_atlantic.py#L32-L54
|
train
|
keon/algorithms
|
algorithms/sort/quick_sort.py
|
quick_sort
|
def quick_sort(arr, simulation=False):
""" Quick sort
Complexity: best O(n log(n)) avg O(n log(n)), worst O(N^2)
"""
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
arr, _ = quick_sort_recur(arr, 0, len(arr) - 1, iteration, simulation)
return arr
|
python
|
def quick_sort(arr, simulation=False):
""" Quick sort
Complexity: best O(n log(n)) avg O(n log(n)), worst O(N^2)
"""
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
arr, _ = quick_sort_recur(arr, 0, len(arr) - 1, iteration, simulation)
return arr
|
[
"def",
"quick_sort",
"(",
"arr",
",",
"simulation",
"=",
"False",
")",
":",
"iteration",
"=",
"0",
"if",
"simulation",
":",
"print",
"(",
"\"iteration\"",
",",
"iteration",
",",
"\":\"",
",",
"*",
"arr",
")",
"arr",
",",
"_",
"=",
"quick_sort_recur",
"(",
"arr",
",",
"0",
",",
"len",
"(",
"arr",
")",
"-",
"1",
",",
"iteration",
",",
"simulation",
")",
"return",
"arr"
] |
Quick sort
Complexity: best O(n log(n)) avg O(n log(n)), worst O(N^2)
|
[
"Quick",
"sort",
"Complexity",
":",
"best",
"O",
"(",
"n",
"log",
"(",
"n",
"))",
"avg",
"O",
"(",
"n",
"log",
"(",
"n",
"))",
"worst",
"O",
"(",
"N^2",
")"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/quick_sort.py#L1-L10
|
train
|
keon/algorithms
|
algorithms/strings/is_palindrome.py
|
is_palindrome
|
def is_palindrome(s):
"""
:type s: str
:rtype: bool
"""
i = 0
j = len(s)-1
while i < j:
while i < j and not s[i].isalnum():
i += 1
while i < j and not s[j].isalnum():
j -= 1
if s[i].lower() != s[j].lower():
return False
i, j = i+1, j-1
return True
|
python
|
def is_palindrome(s):
"""
:type s: str
:rtype: bool
"""
i = 0
j = len(s)-1
while i < j:
while i < j and not s[i].isalnum():
i += 1
while i < j and not s[j].isalnum():
j -= 1
if s[i].lower() != s[j].lower():
return False
i, j = i+1, j-1
return True
|
[
"def",
"is_palindrome",
"(",
"s",
")",
":",
"i",
"=",
"0",
"j",
"=",
"len",
"(",
"s",
")",
"-",
"1",
"while",
"i",
"<",
"j",
":",
"while",
"i",
"<",
"j",
"and",
"not",
"s",
"[",
"i",
"]",
".",
"isalnum",
"(",
")",
":",
"i",
"+=",
"1",
"while",
"i",
"<",
"j",
"and",
"not",
"s",
"[",
"j",
"]",
".",
"isalnum",
"(",
")",
":",
"j",
"-=",
"1",
"if",
"s",
"[",
"i",
"]",
".",
"lower",
"(",
")",
"!=",
"s",
"[",
"j",
"]",
".",
"lower",
"(",
")",
":",
"return",
"False",
"i",
",",
"j",
"=",
"i",
"+",
"1",
",",
"j",
"-",
"1",
"return",
"True"
] |
:type s: str
:rtype: bool
|
[
":",
"type",
"s",
":",
"str",
":",
"rtype",
":",
"bool"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/strings/is_palindrome.py#L16-L31
|
train
|
keon/algorithms
|
algorithms/arrays/plus_one.py
|
plus_one_v1
|
def plus_one_v1(digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits[-1] = digits[-1] + 1
res = []
ten = 0
i = len(digits)-1
while i >= 0 or ten == 1:
summ = 0
if i >= 0:
summ += digits[i]
if ten:
summ += 1
res.append(summ % 10)
ten = summ // 10
i -= 1
return res[::-1]
|
python
|
def plus_one_v1(digits):
"""
:type digits: List[int]
:rtype: List[int]
"""
digits[-1] = digits[-1] + 1
res = []
ten = 0
i = len(digits)-1
while i >= 0 or ten == 1:
summ = 0
if i >= 0:
summ += digits[i]
if ten:
summ += 1
res.append(summ % 10)
ten = summ // 10
i -= 1
return res[::-1]
|
[
"def",
"plus_one_v1",
"(",
"digits",
")",
":",
"digits",
"[",
"-",
"1",
"]",
"=",
"digits",
"[",
"-",
"1",
"]",
"+",
"1",
"res",
"=",
"[",
"]",
"ten",
"=",
"0",
"i",
"=",
"len",
"(",
"digits",
")",
"-",
"1",
"while",
"i",
">=",
"0",
"or",
"ten",
"==",
"1",
":",
"summ",
"=",
"0",
"if",
"i",
">=",
"0",
":",
"summ",
"+=",
"digits",
"[",
"i",
"]",
"if",
"ten",
":",
"summ",
"+=",
"1",
"res",
".",
"append",
"(",
"summ",
"%",
"10",
")",
"ten",
"=",
"summ",
"//",
"10",
"i",
"-=",
"1",
"return",
"res",
"[",
":",
":",
"-",
"1",
"]"
] |
:type digits: List[int]
:rtype: List[int]
|
[
":",
"type",
"digits",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/plus_one.py#L10-L28
|
train
|
keon/algorithms
|
algorithms/linkedlist/rotate_list.py
|
rotate_right
|
def rotate_right(head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or not head.next:
return head
current = head
length = 1
# count length of the list
while current.next:
current = current.next
length += 1
# make it circular
current.next = head
k = k % length
# rotate until length-k
for i in range(length-k):
current = current.next
head = current.next
current.next = None
return head
|
python
|
def rotate_right(head, k):
"""
:type head: ListNode
:type k: int
:rtype: ListNode
"""
if not head or not head.next:
return head
current = head
length = 1
# count length of the list
while current.next:
current = current.next
length += 1
# make it circular
current.next = head
k = k % length
# rotate until length-k
for i in range(length-k):
current = current.next
head = current.next
current.next = None
return head
|
[
"def",
"rotate_right",
"(",
"head",
",",
"k",
")",
":",
"if",
"not",
"head",
"or",
"not",
"head",
".",
"next",
":",
"return",
"head",
"current",
"=",
"head",
"length",
"=",
"1",
"# count length of the list",
"while",
"current",
".",
"next",
":",
"current",
"=",
"current",
".",
"next",
"length",
"+=",
"1",
"# make it circular",
"current",
".",
"next",
"=",
"head",
"k",
"=",
"k",
"%",
"length",
"# rotate until length-k",
"for",
"i",
"in",
"range",
"(",
"length",
"-",
"k",
")",
":",
"current",
"=",
"current",
".",
"next",
"head",
"=",
"current",
".",
"next",
"current",
".",
"next",
"=",
"None",
"return",
"head"
] |
:type head: ListNode
:type k: int
:rtype: ListNode
|
[
":",
"type",
"head",
":",
"ListNode",
":",
"type",
"k",
":",
"int",
":",
"rtype",
":",
"ListNode"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/rotate_list.py#L17-L39
|
train
|
keon/algorithms
|
algorithms/dp/num_decodings.py
|
num_decodings
|
def num_decodings(s):
"""
:type s: str
:rtype: int
"""
if not s or s[0] == "0":
return 0
wo_last, wo_last_two = 1, 1
for i in range(1, len(s)):
x = wo_last if s[i] != "0" else 0
y = wo_last_two if int(s[i-1:i+1]) < 27 and s[i-1] != "0" else 0
wo_last_two = wo_last
wo_last = x+y
return wo_last
|
python
|
def num_decodings(s):
"""
:type s: str
:rtype: int
"""
if not s or s[0] == "0":
return 0
wo_last, wo_last_two = 1, 1
for i in range(1, len(s)):
x = wo_last if s[i] != "0" else 0
y = wo_last_two if int(s[i-1:i+1]) < 27 and s[i-1] != "0" else 0
wo_last_two = wo_last
wo_last = x+y
return wo_last
|
[
"def",
"num_decodings",
"(",
"s",
")",
":",
"if",
"not",
"s",
"or",
"s",
"[",
"0",
"]",
"==",
"\"0\"",
":",
"return",
"0",
"wo_last",
",",
"wo_last_two",
"=",
"1",
",",
"1",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"s",
")",
")",
":",
"x",
"=",
"wo_last",
"if",
"s",
"[",
"i",
"]",
"!=",
"\"0\"",
"else",
"0",
"y",
"=",
"wo_last_two",
"if",
"int",
"(",
"s",
"[",
"i",
"-",
"1",
":",
"i",
"+",
"1",
"]",
")",
"<",
"27",
"and",
"s",
"[",
"i",
"-",
"1",
"]",
"!=",
"\"0\"",
"else",
"0",
"wo_last_two",
"=",
"wo_last",
"wo_last",
"=",
"x",
"+",
"y",
"return",
"wo_last"
] |
:type s: str
:rtype: int
|
[
":",
"type",
"s",
":",
"str",
":",
"rtype",
":",
"int"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/dp/num_decodings.py#L20-L33
|
train
|
keon/algorithms
|
algorithms/search/search_range.py
|
search_range
|
def search_range(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
low = 0
high = len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
if target < nums[mid]:
high = mid - 1
elif target > nums[mid]:
low = mid + 1
else:
break
for j in range(len(nums) - 1, -1, -1):
if nums[j] == target:
return [mid, j]
return [-1, -1]
|
python
|
def search_range(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
low = 0
high = len(nums) - 1
while low <= high:
mid = low + (high - low) // 2
if target < nums[mid]:
high = mid - 1
elif target > nums[mid]:
low = mid + 1
else:
break
for j in range(len(nums) - 1, -1, -1):
if nums[j] == target:
return [mid, j]
return [-1, -1]
|
[
"def",
"search_range",
"(",
"nums",
",",
"target",
")",
":",
"low",
"=",
"0",
"high",
"=",
"len",
"(",
"nums",
")",
"-",
"1",
"while",
"low",
"<=",
"high",
":",
"mid",
"=",
"low",
"+",
"(",
"high",
"-",
"low",
")",
"//",
"2",
"if",
"target",
"<",
"nums",
"[",
"mid",
"]",
":",
"high",
"=",
"mid",
"-",
"1",
"elif",
"target",
">",
"nums",
"[",
"mid",
"]",
":",
"low",
"=",
"mid",
"+",
"1",
"else",
":",
"break",
"for",
"j",
"in",
"range",
"(",
"len",
"(",
"nums",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"if",
"nums",
"[",
"j",
"]",
"==",
"target",
":",
"return",
"[",
"mid",
",",
"j",
"]",
"return",
"[",
"-",
"1",
",",
"-",
"1",
"]"
] |
:type nums: List[int]
:type target: int
:rtype: List[int]
|
[
":",
"type",
"nums",
":",
"List",
"[",
"int",
"]",
":",
"type",
"target",
":",
"int",
":",
"rtype",
":",
"List",
"[",
"int",
"]"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/search/search_range.py#L12-L33
|
train
|
keon/algorithms
|
algorithms/linkedlist/first_cyclic_node.py
|
first_cyclic_node
|
def first_cyclic_node(head):
"""
:type head: Node
:rtype: Node
"""
runner = walker = head
while runner and runner.next:
runner = runner.next.next
walker = walker.next
if runner is walker:
break
if runner is None or runner.next is None:
return None
walker = head
while runner is not walker:
runner, walker = runner.next, walker.next
return runner
|
python
|
def first_cyclic_node(head):
"""
:type head: Node
:rtype: Node
"""
runner = walker = head
while runner and runner.next:
runner = runner.next.next
walker = walker.next
if runner is walker:
break
if runner is None or runner.next is None:
return None
walker = head
while runner is not walker:
runner, walker = runner.next, walker.next
return runner
|
[
"def",
"first_cyclic_node",
"(",
"head",
")",
":",
"runner",
"=",
"walker",
"=",
"head",
"while",
"runner",
"and",
"runner",
".",
"next",
":",
"runner",
"=",
"runner",
".",
"next",
".",
"next",
"walker",
"=",
"walker",
".",
"next",
"if",
"runner",
"is",
"walker",
":",
"break",
"if",
"runner",
"is",
"None",
"or",
"runner",
".",
"next",
"is",
"None",
":",
"return",
"None",
"walker",
"=",
"head",
"while",
"runner",
"is",
"not",
"walker",
":",
"runner",
",",
"walker",
"=",
"runner",
".",
"next",
",",
"walker",
".",
"next",
"return",
"runner"
] |
:type head: Node
:rtype: Node
|
[
":",
"type",
"head",
":",
"Node",
":",
"rtype",
":",
"Node"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/first_cyclic_node.py#L19-L37
|
train
|
keon/algorithms
|
algorithms/sort/heap_sort.py
|
max_heap_sort
|
def max_heap_sort(arr, simulation=False):
""" Heap Sort that uses a max heap to sort an array in ascending order
Complexity: O(n log(n))
"""
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
for i in range(len(arr) - 1, 0, -1):
iteration = max_heapify(arr, i, simulation, iteration)
if simulation:
iteration = iteration + 1
print("iteration",iteration,":",*arr)
return arr
|
python
|
def max_heap_sort(arr, simulation=False):
""" Heap Sort that uses a max heap to sort an array in ascending order
Complexity: O(n log(n))
"""
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
for i in range(len(arr) - 1, 0, -1):
iteration = max_heapify(arr, i, simulation, iteration)
if simulation:
iteration = iteration + 1
print("iteration",iteration,":",*arr)
return arr
|
[
"def",
"max_heap_sort",
"(",
"arr",
",",
"simulation",
"=",
"False",
")",
":",
"iteration",
"=",
"0",
"if",
"simulation",
":",
"print",
"(",
"\"iteration\"",
",",
"iteration",
",",
"\":\"",
",",
"*",
"arr",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"arr",
")",
"-",
"1",
",",
"0",
",",
"-",
"1",
")",
":",
"iteration",
"=",
"max_heapify",
"(",
"arr",
",",
"i",
",",
"simulation",
",",
"iteration",
")",
"if",
"simulation",
":",
"iteration",
"=",
"iteration",
"+",
"1",
"print",
"(",
"\"iteration\"",
",",
"iteration",
",",
"\":\"",
",",
"*",
"arr",
")",
"return",
"arr"
] |
Heap Sort that uses a max heap to sort an array in ascending order
Complexity: O(n log(n))
|
[
"Heap",
"Sort",
"that",
"uses",
"a",
"max",
"heap",
"to",
"sort",
"an",
"array",
"in",
"ascending",
"order",
"Complexity",
":",
"O",
"(",
"n",
"log",
"(",
"n",
"))"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/heap_sort.py#L1-L15
|
train
|
keon/algorithms
|
algorithms/sort/heap_sort.py
|
max_heapify
|
def max_heapify(arr, end, simulation, iteration):
""" Max heapify helper for max_heap_sort
"""
last_parent = (end - 1) // 2
# Iterate from last parent to first
for parent in range(last_parent, -1, -1):
current_parent = parent
# Iterate from current_parent to last_parent
while current_parent <= last_parent:
# Find greatest child of current_parent
child = 2 * current_parent + 1
if child + 1 <= end and arr[child] < arr[child + 1]:
child = child + 1
# Swap if child is greater than parent
if arr[child] > arr[current_parent]:
arr[current_parent], arr[child] = arr[child], arr[current_parent]
current_parent = child
if simulation:
iteration = iteration + 1
print("iteration",iteration,":",*arr)
# If no swap occured, no need to keep iterating
else:
break
arr[0], arr[end] = arr[end], arr[0]
return iteration
|
python
|
def max_heapify(arr, end, simulation, iteration):
""" Max heapify helper for max_heap_sort
"""
last_parent = (end - 1) // 2
# Iterate from last parent to first
for parent in range(last_parent, -1, -1):
current_parent = parent
# Iterate from current_parent to last_parent
while current_parent <= last_parent:
# Find greatest child of current_parent
child = 2 * current_parent + 1
if child + 1 <= end and arr[child] < arr[child + 1]:
child = child + 1
# Swap if child is greater than parent
if arr[child] > arr[current_parent]:
arr[current_parent], arr[child] = arr[child], arr[current_parent]
current_parent = child
if simulation:
iteration = iteration + 1
print("iteration",iteration,":",*arr)
# If no swap occured, no need to keep iterating
else:
break
arr[0], arr[end] = arr[end], arr[0]
return iteration
|
[
"def",
"max_heapify",
"(",
"arr",
",",
"end",
",",
"simulation",
",",
"iteration",
")",
":",
"last_parent",
"=",
"(",
"end",
"-",
"1",
")",
"//",
"2",
"# Iterate from last parent to first",
"for",
"parent",
"in",
"range",
"(",
"last_parent",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"current_parent",
"=",
"parent",
"# Iterate from current_parent to last_parent",
"while",
"current_parent",
"<=",
"last_parent",
":",
"# Find greatest child of current_parent",
"child",
"=",
"2",
"*",
"current_parent",
"+",
"1",
"if",
"child",
"+",
"1",
"<=",
"end",
"and",
"arr",
"[",
"child",
"]",
"<",
"arr",
"[",
"child",
"+",
"1",
"]",
":",
"child",
"=",
"child",
"+",
"1",
"# Swap if child is greater than parent",
"if",
"arr",
"[",
"child",
"]",
">",
"arr",
"[",
"current_parent",
"]",
":",
"arr",
"[",
"current_parent",
"]",
",",
"arr",
"[",
"child",
"]",
"=",
"arr",
"[",
"child",
"]",
",",
"arr",
"[",
"current_parent",
"]",
"current_parent",
"=",
"child",
"if",
"simulation",
":",
"iteration",
"=",
"iteration",
"+",
"1",
"print",
"(",
"\"iteration\"",
",",
"iteration",
",",
"\":\"",
",",
"*",
"arr",
")",
"# If no swap occured, no need to keep iterating",
"else",
":",
"break",
"arr",
"[",
"0",
"]",
",",
"arr",
"[",
"end",
"]",
"=",
"arr",
"[",
"end",
"]",
",",
"arr",
"[",
"0",
"]",
"return",
"iteration"
] |
Max heapify helper for max_heap_sort
|
[
"Max",
"heapify",
"helper",
"for",
"max_heap_sort"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/heap_sort.py#L18-L45
|
train
|
keon/algorithms
|
algorithms/sort/heap_sort.py
|
min_heap_sort
|
def min_heap_sort(arr, simulation=False):
""" Heap Sort that uses a min heap to sort an array in ascending order
Complexity: O(n log(n))
"""
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
for i in range(0, len(arr) - 1):
iteration = min_heapify(arr, i, simulation, iteration)
return arr
|
python
|
def min_heap_sort(arr, simulation=False):
""" Heap Sort that uses a min heap to sort an array in ascending order
Complexity: O(n log(n))
"""
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
for i in range(0, len(arr) - 1):
iteration = min_heapify(arr, i, simulation, iteration)
return arr
|
[
"def",
"min_heap_sort",
"(",
"arr",
",",
"simulation",
"=",
"False",
")",
":",
"iteration",
"=",
"0",
"if",
"simulation",
":",
"print",
"(",
"\"iteration\"",
",",
"iteration",
",",
"\":\"",
",",
"*",
"arr",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"arr",
")",
"-",
"1",
")",
":",
"iteration",
"=",
"min_heapify",
"(",
"arr",
",",
"i",
",",
"simulation",
",",
"iteration",
")",
"return",
"arr"
] |
Heap Sort that uses a min heap to sort an array in ascending order
Complexity: O(n log(n))
|
[
"Heap",
"Sort",
"that",
"uses",
"a",
"min",
"heap",
"to",
"sort",
"an",
"array",
"in",
"ascending",
"order",
"Complexity",
":",
"O",
"(",
"n",
"log",
"(",
"n",
"))"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/heap_sort.py#L47-L58
|
train
|
keon/algorithms
|
algorithms/sort/heap_sort.py
|
min_heapify
|
def min_heapify(arr, start, simulation, iteration):
""" Min heapify helper for min_heap_sort
"""
# Offset last_parent by the start (last_parent calculated as if start index was 0)
# All array accesses need to be offset by start
end = len(arr) - 1
last_parent = (end - start - 1) // 2
# Iterate from last parent to first
for parent in range(last_parent, -1, -1):
current_parent = parent
# Iterate from current_parent to last_parent
while current_parent <= last_parent:
# Find lesser child of current_parent
child = 2 * current_parent + 1
if child + 1 <= end - start and arr[child + start] > arr[
child + 1 + start]:
child = child + 1
# Swap if child is less than parent
if arr[child + start] < arr[current_parent + start]:
arr[current_parent + start], arr[child + start] = \
arr[child + start], arr[current_parent + start]
current_parent = child
if simulation:
iteration = iteration + 1
print("iteration",iteration,":",*arr)
# If no swap occured, no need to keep iterating
else:
break
return iteration
|
python
|
def min_heapify(arr, start, simulation, iteration):
""" Min heapify helper for min_heap_sort
"""
# Offset last_parent by the start (last_parent calculated as if start index was 0)
# All array accesses need to be offset by start
end = len(arr) - 1
last_parent = (end - start - 1) // 2
# Iterate from last parent to first
for parent in range(last_parent, -1, -1):
current_parent = parent
# Iterate from current_parent to last_parent
while current_parent <= last_parent:
# Find lesser child of current_parent
child = 2 * current_parent + 1
if child + 1 <= end - start and arr[child + start] > arr[
child + 1 + start]:
child = child + 1
# Swap if child is less than parent
if arr[child + start] < arr[current_parent + start]:
arr[current_parent + start], arr[child + start] = \
arr[child + start], arr[current_parent + start]
current_parent = child
if simulation:
iteration = iteration + 1
print("iteration",iteration,":",*arr)
# If no swap occured, no need to keep iterating
else:
break
return iteration
|
[
"def",
"min_heapify",
"(",
"arr",
",",
"start",
",",
"simulation",
",",
"iteration",
")",
":",
"# Offset last_parent by the start (last_parent calculated as if start index was 0)",
"# All array accesses need to be offset by start",
"end",
"=",
"len",
"(",
"arr",
")",
"-",
"1",
"last_parent",
"=",
"(",
"end",
"-",
"start",
"-",
"1",
")",
"//",
"2",
"# Iterate from last parent to first",
"for",
"parent",
"in",
"range",
"(",
"last_parent",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"current_parent",
"=",
"parent",
"# Iterate from current_parent to last_parent",
"while",
"current_parent",
"<=",
"last_parent",
":",
"# Find lesser child of current_parent",
"child",
"=",
"2",
"*",
"current_parent",
"+",
"1",
"if",
"child",
"+",
"1",
"<=",
"end",
"-",
"start",
"and",
"arr",
"[",
"child",
"+",
"start",
"]",
">",
"arr",
"[",
"child",
"+",
"1",
"+",
"start",
"]",
":",
"child",
"=",
"child",
"+",
"1",
"# Swap if child is less than parent",
"if",
"arr",
"[",
"child",
"+",
"start",
"]",
"<",
"arr",
"[",
"current_parent",
"+",
"start",
"]",
":",
"arr",
"[",
"current_parent",
"+",
"start",
"]",
",",
"arr",
"[",
"child",
"+",
"start",
"]",
"=",
"arr",
"[",
"child",
"+",
"start",
"]",
",",
"arr",
"[",
"current_parent",
"+",
"start",
"]",
"current_parent",
"=",
"child",
"if",
"simulation",
":",
"iteration",
"=",
"iteration",
"+",
"1",
"print",
"(",
"\"iteration\"",
",",
"iteration",
",",
"\":\"",
",",
"*",
"arr",
")",
"# If no swap occured, no need to keep iterating",
"else",
":",
"break",
"return",
"iteration"
] |
Min heapify helper for min_heap_sort
|
[
"Min",
"heapify",
"helper",
"for",
"min_heap_sort"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/heap_sort.py#L61-L92
|
train
|
keon/algorithms
|
algorithms/maths/rsa.py
|
generate_key
|
def generate_key(k, seed=None):
"""
the RSA key generating algorithm
k is the number of bits in n
"""
def modinv(a, m):
"""calculate the inverse of a mod m
that is, find b such that (a * b) % m == 1"""
b = 1
while not (a * b) % m == 1:
b += 1
return b
def gen_prime(k, seed=None):
"""generate a prime with k bits"""
def is_prime(num):
if num == 2:
return True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
random.seed(seed)
while True:
key = random.randrange(int(2 ** (k - 1)), int(2 ** k))
if is_prime(key):
return key
# size in bits of p and q need to add up to the size of n
p_size = k / 2
q_size = k - p_size
e = gen_prime(k, seed) # in many cases, e is also chosen to be a small constant
while True:
p = gen_prime(p_size, seed)
if p % e != 1:
break
while True:
q = gen_prime(q_size, seed)
if q % e != 1:
break
n = p * q
l = (p - 1) * (q - 1) # calculate totient function
d = modinv(e, l)
return int(n), int(e), int(d)
|
python
|
def generate_key(k, seed=None):
"""
the RSA key generating algorithm
k is the number of bits in n
"""
def modinv(a, m):
"""calculate the inverse of a mod m
that is, find b such that (a * b) % m == 1"""
b = 1
while not (a * b) % m == 1:
b += 1
return b
def gen_prime(k, seed=None):
"""generate a prime with k bits"""
def is_prime(num):
if num == 2:
return True
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
random.seed(seed)
while True:
key = random.randrange(int(2 ** (k - 1)), int(2 ** k))
if is_prime(key):
return key
# size in bits of p and q need to add up to the size of n
p_size = k / 2
q_size = k - p_size
e = gen_prime(k, seed) # in many cases, e is also chosen to be a small constant
while True:
p = gen_prime(p_size, seed)
if p % e != 1:
break
while True:
q = gen_prime(q_size, seed)
if q % e != 1:
break
n = p * q
l = (p - 1) * (q - 1) # calculate totient function
d = modinv(e, l)
return int(n), int(e), int(d)
|
[
"def",
"generate_key",
"(",
"k",
",",
"seed",
"=",
"None",
")",
":",
"def",
"modinv",
"(",
"a",
",",
"m",
")",
":",
"\"\"\"calculate the inverse of a mod m\n that is, find b such that (a * b) % m == 1\"\"\"",
"b",
"=",
"1",
"while",
"not",
"(",
"a",
"*",
"b",
")",
"%",
"m",
"==",
"1",
":",
"b",
"+=",
"1",
"return",
"b",
"def",
"gen_prime",
"(",
"k",
",",
"seed",
"=",
"None",
")",
":",
"\"\"\"generate a prime with k bits\"\"\"",
"def",
"is_prime",
"(",
"num",
")",
":",
"if",
"num",
"==",
"2",
":",
"return",
"True",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"int",
"(",
"num",
"**",
"0.5",
")",
"+",
"1",
")",
":",
"if",
"num",
"%",
"i",
"==",
"0",
":",
"return",
"False",
"return",
"True",
"random",
".",
"seed",
"(",
"seed",
")",
"while",
"True",
":",
"key",
"=",
"random",
".",
"randrange",
"(",
"int",
"(",
"2",
"**",
"(",
"k",
"-",
"1",
")",
")",
",",
"int",
"(",
"2",
"**",
"k",
")",
")",
"if",
"is_prime",
"(",
"key",
")",
":",
"return",
"key",
"# size in bits of p and q need to add up to the size of n",
"p_size",
"=",
"k",
"/",
"2",
"q_size",
"=",
"k",
"-",
"p_size",
"e",
"=",
"gen_prime",
"(",
"k",
",",
"seed",
")",
"# in many cases, e is also chosen to be a small constant",
"while",
"True",
":",
"p",
"=",
"gen_prime",
"(",
"p_size",
",",
"seed",
")",
"if",
"p",
"%",
"e",
"!=",
"1",
":",
"break",
"while",
"True",
":",
"q",
"=",
"gen_prime",
"(",
"q_size",
",",
"seed",
")",
"if",
"q",
"%",
"e",
"!=",
"1",
":",
"break",
"n",
"=",
"p",
"*",
"q",
"l",
"=",
"(",
"p",
"-",
"1",
")",
"*",
"(",
"q",
"-",
"1",
")",
"# calculate totient function",
"d",
"=",
"modinv",
"(",
"e",
",",
"l",
")",
"return",
"int",
"(",
"n",
")",
",",
"int",
"(",
"e",
")",
",",
"int",
"(",
"d",
")"
] |
the RSA key generating algorithm
k is the number of bits in n
|
[
"the",
"RSA",
"key",
"generating",
"algorithm",
"k",
"is",
"the",
"number",
"of",
"bits",
"in",
"n"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/rsa.py#L27-L78
|
train
|
keon/algorithms
|
algorithms/maths/sqrt_precision_factor.py
|
square_root
|
def square_root(n, epsilon=0.001):
"""Return square root of n, with maximum absolute error epsilon"""
guess = n / 2
while abs(guess * guess - n) > epsilon:
guess = (guess + (n / guess)) / 2
return guess
|
python
|
def square_root(n, epsilon=0.001):
"""Return square root of n, with maximum absolute error epsilon"""
guess = n / 2
while abs(guess * guess - n) > epsilon:
guess = (guess + (n / guess)) / 2
return guess
|
[
"def",
"square_root",
"(",
"n",
",",
"epsilon",
"=",
"0.001",
")",
":",
"guess",
"=",
"n",
"/",
"2",
"while",
"abs",
"(",
"guess",
"*",
"guess",
"-",
"n",
")",
">",
"epsilon",
":",
"guess",
"=",
"(",
"guess",
"+",
"(",
"n",
"/",
"guess",
")",
")",
"/",
"2",
"return",
"guess"
] |
Return square root of n, with maximum absolute error epsilon
|
[
"Return",
"square",
"root",
"of",
"n",
"with",
"maximum",
"absolute",
"error",
"epsilon"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/sqrt_precision_factor.py#L12-L19
|
train
|
keon/algorithms
|
algorithms/sort/counting_sort.py
|
counting_sort
|
def counting_sort(arr):
"""
Counting_sort
Sorting a array which has no element greater than k
Creating a new temp_arr,where temp_arr[i] contain the number of
element less than or equal to i in the arr
Then placing the number i into a correct position in the result_arr
return the result_arr
Complexity: 0(n)
"""
m = min(arr)
# in case there are negative elements, change the array to all positive element
different = 0
if m < 0:
# save the change, so that we can convert the array back to all positive number
different = -m
for i in range(len(arr)):
arr[i] += -m
k = max(arr)
temp_arr = [0] * (k + 1)
for i in range(0, len(arr)):
temp_arr[arr[i]] = temp_arr[arr[i]] + 1
# temp_array[i] contain the times the number i appear in arr
for i in range(1, k + 1):
temp_arr[i] = temp_arr[i] + temp_arr[i - 1]
# temp_array[i] contain the number of element less than or equal i in arr
result_arr = arr.copy()
# creating a result_arr an put the element in a correct positon
for i in range(len(arr) - 1, -1, -1):
result_arr[temp_arr[arr[i]] - 1] = arr[i] - different
temp_arr[arr[i]] = temp_arr[arr[i]] - 1
return result_arr
|
python
|
def counting_sort(arr):
"""
Counting_sort
Sorting a array which has no element greater than k
Creating a new temp_arr,where temp_arr[i] contain the number of
element less than or equal to i in the arr
Then placing the number i into a correct position in the result_arr
return the result_arr
Complexity: 0(n)
"""
m = min(arr)
# in case there are negative elements, change the array to all positive element
different = 0
if m < 0:
# save the change, so that we can convert the array back to all positive number
different = -m
for i in range(len(arr)):
arr[i] += -m
k = max(arr)
temp_arr = [0] * (k + 1)
for i in range(0, len(arr)):
temp_arr[arr[i]] = temp_arr[arr[i]] + 1
# temp_array[i] contain the times the number i appear in arr
for i in range(1, k + 1):
temp_arr[i] = temp_arr[i] + temp_arr[i - 1]
# temp_array[i] contain the number of element less than or equal i in arr
result_arr = arr.copy()
# creating a result_arr an put the element in a correct positon
for i in range(len(arr) - 1, -1, -1):
result_arr[temp_arr[arr[i]] - 1] = arr[i] - different
temp_arr[arr[i]] = temp_arr[arr[i]] - 1
return result_arr
|
[
"def",
"counting_sort",
"(",
"arr",
")",
":",
"m",
"=",
"min",
"(",
"arr",
")",
"# in case there are negative elements, change the array to all positive element",
"different",
"=",
"0",
"if",
"m",
"<",
"0",
":",
"# save the change, so that we can convert the array back to all positive number",
"different",
"=",
"-",
"m",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"arr",
")",
")",
":",
"arr",
"[",
"i",
"]",
"+=",
"-",
"m",
"k",
"=",
"max",
"(",
"arr",
")",
"temp_arr",
"=",
"[",
"0",
"]",
"*",
"(",
"k",
"+",
"1",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"arr",
")",
")",
":",
"temp_arr",
"[",
"arr",
"[",
"i",
"]",
"]",
"=",
"temp_arr",
"[",
"arr",
"[",
"i",
"]",
"]",
"+",
"1",
"# temp_array[i] contain the times the number i appear in arr",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"k",
"+",
"1",
")",
":",
"temp_arr",
"[",
"i",
"]",
"=",
"temp_arr",
"[",
"i",
"]",
"+",
"temp_arr",
"[",
"i",
"-",
"1",
"]",
"# temp_array[i] contain the number of element less than or equal i in arr",
"result_arr",
"=",
"arr",
".",
"copy",
"(",
")",
"# creating a result_arr an put the element in a correct positon",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"arr",
")",
"-",
"1",
",",
"-",
"1",
",",
"-",
"1",
")",
":",
"result_arr",
"[",
"temp_arr",
"[",
"arr",
"[",
"i",
"]",
"]",
"-",
"1",
"]",
"=",
"arr",
"[",
"i",
"]",
"-",
"different",
"temp_arr",
"[",
"arr",
"[",
"i",
"]",
"]",
"=",
"temp_arr",
"[",
"arr",
"[",
"i",
"]",
"]",
"-",
"1",
"return",
"result_arr"
] |
Counting_sort
Sorting a array which has no element greater than k
Creating a new temp_arr,where temp_arr[i] contain the number of
element less than or equal to i in the arr
Then placing the number i into a correct position in the result_arr
return the result_arr
Complexity: 0(n)
|
[
"Counting_sort",
"Sorting",
"a",
"array",
"which",
"has",
"no",
"element",
"greater",
"than",
"k",
"Creating",
"a",
"new",
"temp_arr",
"where",
"temp_arr",
"[",
"i",
"]",
"contain",
"the",
"number",
"of",
"element",
"less",
"than",
"or",
"equal",
"to",
"i",
"in",
"the",
"arr",
"Then",
"placing",
"the",
"number",
"i",
"into",
"a",
"correct",
"position",
"in",
"the",
"result_arr",
"return",
"the",
"result_arr",
"Complexity",
":",
"0",
"(",
"n",
")"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/counting_sort.py#L1-L36
|
train
|
keon/algorithms
|
algorithms/set/set_covering.py
|
powerset
|
def powerset(iterable):
"""Calculate the powerset of any iterable.
For a range of integers up to the length of the given list,
make all possible combinations and chain them together as one object.
From https://docs.python.org/3/library/itertools.html#itertools-recipes
"""
"list(powerset([1,2,3])) --> [(), (1,), (2,), (3,), (1,2), (1,3), (2,3), (1,2,3)]"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
|
python
|
def powerset(iterable):
"""Calculate the powerset of any iterable.
For a range of integers up to the length of the given list,
make all possible combinations and chain them together as one object.
From https://docs.python.org/3/library/itertools.html#itertools-recipes
"""
"list(powerset([1,2,3])) --> [(), (1,), (2,), (3,), (1,2), (1,3), (2,3), (1,2,3)]"
s = list(iterable)
return chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
|
[
"def",
"powerset",
"(",
"iterable",
")",
":",
"\"list(powerset([1,2,3])) --> [(), (1,), (2,), (3,), (1,2), (1,3), (2,3), (1,2,3)]\"",
"s",
"=",
"list",
"(",
"iterable",
")",
"return",
"chain",
".",
"from_iterable",
"(",
"combinations",
"(",
"s",
",",
"r",
")",
"for",
"r",
"in",
"range",
"(",
"len",
"(",
"s",
")",
"+",
"1",
")",
")"
] |
Calculate the powerset of any iterable.
For a range of integers up to the length of the given list,
make all possible combinations and chain them together as one object.
From https://docs.python.org/3/library/itertools.html#itertools-recipes
|
[
"Calculate",
"the",
"powerset",
"of",
"any",
"iterable",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/set/set_covering.py#L25-L34
|
train
|
keon/algorithms
|
algorithms/set/set_covering.py
|
optimal_set_cover
|
def optimal_set_cover(universe, subsets, costs):
""" Optimal algorithm - DONT USE ON BIG INPUTS - O(2^n) complexity!
Finds the minimum cost subcollection os S that covers all elements of U
Args:
universe (list): Universe of elements
subsets (dict): Subsets of U {S1:elements,S2:elements}
costs (dict): Costs of each subset in S - {S1:cost, S2:cost...}
"""
pset = powerset(subsets.keys())
best_set = None
best_cost = float("inf")
for subset in pset:
covered = set()
cost = 0
for s in subset:
covered.update(subsets[s])
cost += costs[s]
if len(covered) == len(universe) and cost < best_cost:
best_set = subset
best_cost = cost
return best_set
|
python
|
def optimal_set_cover(universe, subsets, costs):
""" Optimal algorithm - DONT USE ON BIG INPUTS - O(2^n) complexity!
Finds the minimum cost subcollection os S that covers all elements of U
Args:
universe (list): Universe of elements
subsets (dict): Subsets of U {S1:elements,S2:elements}
costs (dict): Costs of each subset in S - {S1:cost, S2:cost...}
"""
pset = powerset(subsets.keys())
best_set = None
best_cost = float("inf")
for subset in pset:
covered = set()
cost = 0
for s in subset:
covered.update(subsets[s])
cost += costs[s]
if len(covered) == len(universe) and cost < best_cost:
best_set = subset
best_cost = cost
return best_set
|
[
"def",
"optimal_set_cover",
"(",
"universe",
",",
"subsets",
",",
"costs",
")",
":",
"pset",
"=",
"powerset",
"(",
"subsets",
".",
"keys",
"(",
")",
")",
"best_set",
"=",
"None",
"best_cost",
"=",
"float",
"(",
"\"inf\"",
")",
"for",
"subset",
"in",
"pset",
":",
"covered",
"=",
"set",
"(",
")",
"cost",
"=",
"0",
"for",
"s",
"in",
"subset",
":",
"covered",
".",
"update",
"(",
"subsets",
"[",
"s",
"]",
")",
"cost",
"+=",
"costs",
"[",
"s",
"]",
"if",
"len",
"(",
"covered",
")",
"==",
"len",
"(",
"universe",
")",
"and",
"cost",
"<",
"best_cost",
":",
"best_set",
"=",
"subset",
"best_cost",
"=",
"cost",
"return",
"best_set"
] |
Optimal algorithm - DONT USE ON BIG INPUTS - O(2^n) complexity!
Finds the minimum cost subcollection os S that covers all elements of U
Args:
universe (list): Universe of elements
subsets (dict): Subsets of U {S1:elements,S2:elements}
costs (dict): Costs of each subset in S - {S1:cost, S2:cost...}
|
[
"Optimal",
"algorithm",
"-",
"DONT",
"USE",
"ON",
"BIG",
"INPUTS",
"-",
"O",
"(",
"2^n",
")",
"complexity!",
"Finds",
"the",
"minimum",
"cost",
"subcollection",
"os",
"S",
"that",
"covers",
"all",
"elements",
"of",
"U"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/set/set_covering.py#L37-L58
|
train
|
keon/algorithms
|
algorithms/set/set_covering.py
|
greedy_set_cover
|
def greedy_set_cover(universe, subsets, costs):
"""Approximate greedy algorithm for set-covering. Can be used on large
inputs - though not an optimal solution.
Args:
universe (list): Universe of elements
subsets (dict): Subsets of U {S1:elements,S2:elements}
costs (dict): Costs of each subset in S - {S1:cost, S2:cost...}
"""
elements = set(e for s in subsets.keys() for e in subsets[s])
# elements don't cover universe -> invalid input for set cover
if elements != universe:
return None
# track elements of universe covered
covered = set()
cover_sets = []
while covered != universe:
min_cost_elem_ratio = float("inf")
min_set = None
# find set with minimum cost:elements_added ratio
for s, elements in subsets.items():
new_elements = len(elements - covered)
# set may have same elements as already covered -> new_elements = 0
# check to avoid division by 0 error
if new_elements != 0:
cost_elem_ratio = costs[s] / new_elements
if cost_elem_ratio < min_cost_elem_ratio:
min_cost_elem_ratio = cost_elem_ratio
min_set = s
cover_sets.append(min_set)
# union
covered |= subsets[min_set]
return cover_sets
|
python
|
def greedy_set_cover(universe, subsets, costs):
"""Approximate greedy algorithm for set-covering. Can be used on large
inputs - though not an optimal solution.
Args:
universe (list): Universe of elements
subsets (dict): Subsets of U {S1:elements,S2:elements}
costs (dict): Costs of each subset in S - {S1:cost, S2:cost...}
"""
elements = set(e for s in subsets.keys() for e in subsets[s])
# elements don't cover universe -> invalid input for set cover
if elements != universe:
return None
# track elements of universe covered
covered = set()
cover_sets = []
while covered != universe:
min_cost_elem_ratio = float("inf")
min_set = None
# find set with minimum cost:elements_added ratio
for s, elements in subsets.items():
new_elements = len(elements - covered)
# set may have same elements as already covered -> new_elements = 0
# check to avoid division by 0 error
if new_elements != 0:
cost_elem_ratio = costs[s] / new_elements
if cost_elem_ratio < min_cost_elem_ratio:
min_cost_elem_ratio = cost_elem_ratio
min_set = s
cover_sets.append(min_set)
# union
covered |= subsets[min_set]
return cover_sets
|
[
"def",
"greedy_set_cover",
"(",
"universe",
",",
"subsets",
",",
"costs",
")",
":",
"elements",
"=",
"set",
"(",
"e",
"for",
"s",
"in",
"subsets",
".",
"keys",
"(",
")",
"for",
"e",
"in",
"subsets",
"[",
"s",
"]",
")",
"# elements don't cover universe -> invalid input for set cover",
"if",
"elements",
"!=",
"universe",
":",
"return",
"None",
"# track elements of universe covered",
"covered",
"=",
"set",
"(",
")",
"cover_sets",
"=",
"[",
"]",
"while",
"covered",
"!=",
"universe",
":",
"min_cost_elem_ratio",
"=",
"float",
"(",
"\"inf\"",
")",
"min_set",
"=",
"None",
"# find set with minimum cost:elements_added ratio",
"for",
"s",
",",
"elements",
"in",
"subsets",
".",
"items",
"(",
")",
":",
"new_elements",
"=",
"len",
"(",
"elements",
"-",
"covered",
")",
"# set may have same elements as already covered -> new_elements = 0",
"# check to avoid division by 0 error",
"if",
"new_elements",
"!=",
"0",
":",
"cost_elem_ratio",
"=",
"costs",
"[",
"s",
"]",
"/",
"new_elements",
"if",
"cost_elem_ratio",
"<",
"min_cost_elem_ratio",
":",
"min_cost_elem_ratio",
"=",
"cost_elem_ratio",
"min_set",
"=",
"s",
"cover_sets",
".",
"append",
"(",
"min_set",
")",
"# union",
"covered",
"|=",
"subsets",
"[",
"min_set",
"]",
"return",
"cover_sets"
] |
Approximate greedy algorithm for set-covering. Can be used on large
inputs - though not an optimal solution.
Args:
universe (list): Universe of elements
subsets (dict): Subsets of U {S1:elements,S2:elements}
costs (dict): Costs of each subset in S - {S1:cost, S2:cost...}
|
[
"Approximate",
"greedy",
"algorithm",
"for",
"set",
"-",
"covering",
".",
"Can",
"be",
"used",
"on",
"large",
"inputs",
"-",
"though",
"not",
"an",
"optimal",
"solution",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/set/set_covering.py#L61-L95
|
train
|
keon/algorithms
|
algorithms/tree/bst/unique_bst.py
|
num_trees
|
def num_trees(n):
"""
:type n: int
:rtype: int
"""
dp = [0] * (n+1)
dp[0] = 1
dp[1] = 1
for i in range(2, n+1):
for j in range(i+1):
dp[i] += dp[i-j] * dp[j-1]
return dp[-1]
|
python
|
def num_trees(n):
"""
:type n: int
:rtype: int
"""
dp = [0] * (n+1)
dp[0] = 1
dp[1] = 1
for i in range(2, n+1):
for j in range(i+1):
dp[i] += dp[i-j] * dp[j-1]
return dp[-1]
|
[
"def",
"num_trees",
"(",
"n",
")",
":",
"dp",
"=",
"[",
"0",
"]",
"*",
"(",
"n",
"+",
"1",
")",
"dp",
"[",
"0",
"]",
"=",
"1",
"dp",
"[",
"1",
"]",
"=",
"1",
"for",
"i",
"in",
"range",
"(",
"2",
",",
"n",
"+",
"1",
")",
":",
"for",
"j",
"in",
"range",
"(",
"i",
"+",
"1",
")",
":",
"dp",
"[",
"i",
"]",
"+=",
"dp",
"[",
"i",
"-",
"j",
"]",
"*",
"dp",
"[",
"j",
"-",
"1",
"]",
"return",
"dp",
"[",
"-",
"1",
"]"
] |
:type n: int
:rtype: int
|
[
":",
"type",
"n",
":",
"int",
":",
"rtype",
":",
"int"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/bst/unique_bst.py#L29-L40
|
train
|
keon/algorithms
|
algorithms/queues/moving_average.py
|
MovingAverage.next
|
def next(self, val):
"""
:type val: int
:rtype: float
"""
self.queue.append(val)
return sum(self.queue) / len(self.queue)
|
python
|
def next(self, val):
"""
:type val: int
:rtype: float
"""
self.queue.append(val)
return sum(self.queue) / len(self.queue)
|
[
"def",
"next",
"(",
"self",
",",
"val",
")",
":",
"self",
".",
"queue",
".",
"append",
"(",
"val",
")",
"return",
"sum",
"(",
"self",
".",
"queue",
")",
"/",
"len",
"(",
"self",
".",
"queue",
")"
] |
:type val: int
:rtype: float
|
[
":",
"type",
"val",
":",
"int",
":",
"rtype",
":",
"float"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/queues/moving_average.py#L13-L19
|
train
|
keon/algorithms
|
algorithms/arrays/n_sum.py
|
n_sum
|
def n_sum(n, nums, target, **kv):
"""
n: int
nums: list[object]
target: object
sum_closure: function, optional
Given two elements of nums, return sum of both.
compare_closure: function, optional
Given one object of nums and target, return -1, 1, or 0.
same_closure: function, optional
Given two object of nums, return bool.
return: list[list[object]]
Note:
1. type of sum_closure's return should be same
as type of compare_closure's first param
"""
def sum_closure_default(a, b):
return a + b
def compare_closure_default(num, target):
""" above, below, or right on? """
if num < target:
return -1
elif num > target:
return 1
else:
return 0
def same_closure_default(a, b):
return a == b
def n_sum(n, nums, target):
if n == 2: # want answers with only 2 terms? easy!
results = two_sum(nums, target)
else:
results = []
prev_num = None
for index, num in enumerate(nums):
if prev_num is not None and \
same_closure(prev_num, num):
continue
prev_num = num
n_minus1_results = (
n_sum( # recursive call
n - 1, # a
nums[index + 1:], # b
target - num # c
) # x = n_sum( a, b, c )
) # n_minus1_results = x
n_minus1_results = (
append_elem_to_each_list(num, n_minus1_results)
)
results += n_minus1_results
return union(results)
def two_sum(nums, target):
nums.sort()
lt = 0
rt = len(nums) - 1
results = []
while lt < rt:
sum_ = sum_closure(nums[lt], nums[rt])
flag = compare_closure(sum_, target)
if flag == -1:
lt += 1
elif flag == 1:
rt -= 1
else:
results.append(sorted([nums[lt], nums[rt]]))
lt += 1
rt -= 1
while (lt < len(nums) and
same_closure(nums[lt - 1], nums[lt])):
lt += 1
while (0 <= rt and
same_closure(nums[rt], nums[rt + 1])):
rt -= 1
return results
def append_elem_to_each_list(elem, container):
results = []
for elems in container:
elems.append(elem)
results.append(sorted(elems))
return results
def union(duplicate_results):
results = []
if len(duplicate_results) != 0:
duplicate_results.sort()
results.append(duplicate_results[0])
for result in duplicate_results[1:]:
if results[-1] != result:
results.append(result)
return results
sum_closure = kv.get('sum_closure', sum_closure_default)
same_closure = kv.get('same_closure', same_closure_default)
compare_closure = kv.get('compare_closure', compare_closure_default)
nums.sort()
return n_sum(n, nums, target)
|
python
|
def n_sum(n, nums, target, **kv):
"""
n: int
nums: list[object]
target: object
sum_closure: function, optional
Given two elements of nums, return sum of both.
compare_closure: function, optional
Given one object of nums and target, return -1, 1, or 0.
same_closure: function, optional
Given two object of nums, return bool.
return: list[list[object]]
Note:
1. type of sum_closure's return should be same
as type of compare_closure's first param
"""
def sum_closure_default(a, b):
return a + b
def compare_closure_default(num, target):
""" above, below, or right on? """
if num < target:
return -1
elif num > target:
return 1
else:
return 0
def same_closure_default(a, b):
return a == b
def n_sum(n, nums, target):
if n == 2: # want answers with only 2 terms? easy!
results = two_sum(nums, target)
else:
results = []
prev_num = None
for index, num in enumerate(nums):
if prev_num is not None and \
same_closure(prev_num, num):
continue
prev_num = num
n_minus1_results = (
n_sum( # recursive call
n - 1, # a
nums[index + 1:], # b
target - num # c
) # x = n_sum( a, b, c )
) # n_minus1_results = x
n_minus1_results = (
append_elem_to_each_list(num, n_minus1_results)
)
results += n_minus1_results
return union(results)
def two_sum(nums, target):
nums.sort()
lt = 0
rt = len(nums) - 1
results = []
while lt < rt:
sum_ = sum_closure(nums[lt], nums[rt])
flag = compare_closure(sum_, target)
if flag == -1:
lt += 1
elif flag == 1:
rt -= 1
else:
results.append(sorted([nums[lt], nums[rt]]))
lt += 1
rt -= 1
while (lt < len(nums) and
same_closure(nums[lt - 1], nums[lt])):
lt += 1
while (0 <= rt and
same_closure(nums[rt], nums[rt + 1])):
rt -= 1
return results
def append_elem_to_each_list(elem, container):
results = []
for elems in container:
elems.append(elem)
results.append(sorted(elems))
return results
def union(duplicate_results):
results = []
if len(duplicate_results) != 0:
duplicate_results.sort()
results.append(duplicate_results[0])
for result in duplicate_results[1:]:
if results[-1] != result:
results.append(result)
return results
sum_closure = kv.get('sum_closure', sum_closure_default)
same_closure = kv.get('same_closure', same_closure_default)
compare_closure = kv.get('compare_closure', compare_closure_default)
nums.sort()
return n_sum(n, nums, target)
|
[
"def",
"n_sum",
"(",
"n",
",",
"nums",
",",
"target",
",",
"*",
"*",
"kv",
")",
":",
"def",
"sum_closure_default",
"(",
"a",
",",
"b",
")",
":",
"return",
"a",
"+",
"b",
"def",
"compare_closure_default",
"(",
"num",
",",
"target",
")",
":",
"\"\"\" above, below, or right on? \"\"\"",
"if",
"num",
"<",
"target",
":",
"return",
"-",
"1",
"elif",
"num",
">",
"target",
":",
"return",
"1",
"else",
":",
"return",
"0",
"def",
"same_closure_default",
"(",
"a",
",",
"b",
")",
":",
"return",
"a",
"==",
"b",
"def",
"n_sum",
"(",
"n",
",",
"nums",
",",
"target",
")",
":",
"if",
"n",
"==",
"2",
":",
"# want answers with only 2 terms? easy!",
"results",
"=",
"two_sum",
"(",
"nums",
",",
"target",
")",
"else",
":",
"results",
"=",
"[",
"]",
"prev_num",
"=",
"None",
"for",
"index",
",",
"num",
"in",
"enumerate",
"(",
"nums",
")",
":",
"if",
"prev_num",
"is",
"not",
"None",
"and",
"same_closure",
"(",
"prev_num",
",",
"num",
")",
":",
"continue",
"prev_num",
"=",
"num",
"n_minus1_results",
"=",
"(",
"n_sum",
"(",
"# recursive call",
"n",
"-",
"1",
",",
"# a",
"nums",
"[",
"index",
"+",
"1",
":",
"]",
",",
"# b",
"target",
"-",
"num",
"# c",
")",
"# x = n_sum( a, b, c )",
")",
"# n_minus1_results = x",
"n_minus1_results",
"=",
"(",
"append_elem_to_each_list",
"(",
"num",
",",
"n_minus1_results",
")",
")",
"results",
"+=",
"n_minus1_results",
"return",
"union",
"(",
"results",
")",
"def",
"two_sum",
"(",
"nums",
",",
"target",
")",
":",
"nums",
".",
"sort",
"(",
")",
"lt",
"=",
"0",
"rt",
"=",
"len",
"(",
"nums",
")",
"-",
"1",
"results",
"=",
"[",
"]",
"while",
"lt",
"<",
"rt",
":",
"sum_",
"=",
"sum_closure",
"(",
"nums",
"[",
"lt",
"]",
",",
"nums",
"[",
"rt",
"]",
")",
"flag",
"=",
"compare_closure",
"(",
"sum_",
",",
"target",
")",
"if",
"flag",
"==",
"-",
"1",
":",
"lt",
"+=",
"1",
"elif",
"flag",
"==",
"1",
":",
"rt",
"-=",
"1",
"else",
":",
"results",
".",
"append",
"(",
"sorted",
"(",
"[",
"nums",
"[",
"lt",
"]",
",",
"nums",
"[",
"rt",
"]",
"]",
")",
")",
"lt",
"+=",
"1",
"rt",
"-=",
"1",
"while",
"(",
"lt",
"<",
"len",
"(",
"nums",
")",
"and",
"same_closure",
"(",
"nums",
"[",
"lt",
"-",
"1",
"]",
",",
"nums",
"[",
"lt",
"]",
")",
")",
":",
"lt",
"+=",
"1",
"while",
"(",
"0",
"<=",
"rt",
"and",
"same_closure",
"(",
"nums",
"[",
"rt",
"]",
",",
"nums",
"[",
"rt",
"+",
"1",
"]",
")",
")",
":",
"rt",
"-=",
"1",
"return",
"results",
"def",
"append_elem_to_each_list",
"(",
"elem",
",",
"container",
")",
":",
"results",
"=",
"[",
"]",
"for",
"elems",
"in",
"container",
":",
"elems",
".",
"append",
"(",
"elem",
")",
"results",
".",
"append",
"(",
"sorted",
"(",
"elems",
")",
")",
"return",
"results",
"def",
"union",
"(",
"duplicate_results",
")",
":",
"results",
"=",
"[",
"]",
"if",
"len",
"(",
"duplicate_results",
")",
"!=",
"0",
":",
"duplicate_results",
".",
"sort",
"(",
")",
"results",
".",
"append",
"(",
"duplicate_results",
"[",
"0",
"]",
")",
"for",
"result",
"in",
"duplicate_results",
"[",
"1",
":",
"]",
":",
"if",
"results",
"[",
"-",
"1",
"]",
"!=",
"result",
":",
"results",
".",
"append",
"(",
"result",
")",
"return",
"results",
"sum_closure",
"=",
"kv",
".",
"get",
"(",
"'sum_closure'",
",",
"sum_closure_default",
")",
"same_closure",
"=",
"kv",
".",
"get",
"(",
"'same_closure'",
",",
"same_closure_default",
")",
"compare_closure",
"=",
"kv",
".",
"get",
"(",
"'compare_closure'",
",",
"compare_closure_default",
")",
"nums",
".",
"sort",
"(",
")",
"return",
"n_sum",
"(",
"n",
",",
"nums",
",",
"target",
")"
] |
n: int
nums: list[object]
target: object
sum_closure: function, optional
Given two elements of nums, return sum of both.
compare_closure: function, optional
Given one object of nums and target, return -1, 1, or 0.
same_closure: function, optional
Given two object of nums, return bool.
return: list[list[object]]
Note:
1. type of sum_closure's return should be same
as type of compare_closure's first param
|
[
"n",
":",
"int",
"nums",
":",
"list",
"[",
"object",
"]",
"target",
":",
"object",
"sum_closure",
":",
"function",
"optional",
"Given",
"two",
"elements",
"of",
"nums",
"return",
"sum",
"of",
"both",
".",
"compare_closure",
":",
"function",
"optional",
"Given",
"one",
"object",
"of",
"nums",
"and",
"target",
"return",
"-",
"1",
"1",
"or",
"0",
".",
"same_closure",
":",
"function",
"optional",
"Given",
"two",
"object",
"of",
"nums",
"return",
"bool",
".",
"return",
":",
"list",
"[",
"list",
"[",
"object",
"]]"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/n_sum.py#L34-L140
|
train
|
keon/algorithms
|
algorithms/backtrack/pattern_match.py
|
pattern_match
|
def pattern_match(pattern, string):
"""
:type pattern: str
:type string: str
:rtype: bool
"""
def backtrack(pattern, string, dic):
if len(pattern) == 0 and len(string) > 0:
return False
if len(pattern) == len(string) == 0:
return True
for end in range(1, len(string)-len(pattern)+2):
if pattern[0] not in dic and string[:end] not in dic.values():
dic[pattern[0]] = string[:end]
if backtrack(pattern[1:], string[end:], dic):
return True
del dic[pattern[0]]
elif pattern[0] in dic and dic[pattern[0]] == string[:end]:
if backtrack(pattern[1:], string[end:], dic):
return True
return False
return backtrack(pattern, string, {})
|
python
|
def pattern_match(pattern, string):
"""
:type pattern: str
:type string: str
:rtype: bool
"""
def backtrack(pattern, string, dic):
if len(pattern) == 0 and len(string) > 0:
return False
if len(pattern) == len(string) == 0:
return True
for end in range(1, len(string)-len(pattern)+2):
if pattern[0] not in dic and string[:end] not in dic.values():
dic[pattern[0]] = string[:end]
if backtrack(pattern[1:], string[end:], dic):
return True
del dic[pattern[0]]
elif pattern[0] in dic and dic[pattern[0]] == string[:end]:
if backtrack(pattern[1:], string[end:], dic):
return True
return False
return backtrack(pattern, string, {})
|
[
"def",
"pattern_match",
"(",
"pattern",
",",
"string",
")",
":",
"def",
"backtrack",
"(",
"pattern",
",",
"string",
",",
"dic",
")",
":",
"if",
"len",
"(",
"pattern",
")",
"==",
"0",
"and",
"len",
"(",
"string",
")",
">",
"0",
":",
"return",
"False",
"if",
"len",
"(",
"pattern",
")",
"==",
"len",
"(",
"string",
")",
"==",
"0",
":",
"return",
"True",
"for",
"end",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"string",
")",
"-",
"len",
"(",
"pattern",
")",
"+",
"2",
")",
":",
"if",
"pattern",
"[",
"0",
"]",
"not",
"in",
"dic",
"and",
"string",
"[",
":",
"end",
"]",
"not",
"in",
"dic",
".",
"values",
"(",
")",
":",
"dic",
"[",
"pattern",
"[",
"0",
"]",
"]",
"=",
"string",
"[",
":",
"end",
"]",
"if",
"backtrack",
"(",
"pattern",
"[",
"1",
":",
"]",
",",
"string",
"[",
"end",
":",
"]",
",",
"dic",
")",
":",
"return",
"True",
"del",
"dic",
"[",
"pattern",
"[",
"0",
"]",
"]",
"elif",
"pattern",
"[",
"0",
"]",
"in",
"dic",
"and",
"dic",
"[",
"pattern",
"[",
"0",
"]",
"]",
"==",
"string",
"[",
":",
"end",
"]",
":",
"if",
"backtrack",
"(",
"pattern",
"[",
"1",
":",
"]",
",",
"string",
"[",
"end",
":",
"]",
",",
"dic",
")",
":",
"return",
"True",
"return",
"False",
"return",
"backtrack",
"(",
"pattern",
",",
"string",
",",
"{",
"}",
")"
] |
:type pattern: str
:type string: str
:rtype: bool
|
[
":",
"type",
"pattern",
":",
"str",
":",
"type",
"string",
":",
"str",
":",
"rtype",
":",
"bool"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/backtrack/pattern_match.py#L17-L42
|
train
|
keon/algorithms
|
algorithms/sort/bogo_sort.py
|
bogo_sort
|
def bogo_sort(arr, simulation=False):
"""Bogo Sort
Best Case Complexity: O(n)
Worst Case Complexity: O(∞)
Average Case Complexity: O(n(n-1)!)
"""
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
def is_sorted(arr):
#check the array is inorder
i = 0
arr_len = len(arr)
while i+1 < arr_len:
if arr[i] > arr[i+1]:
return False
i += 1
return True
while not is_sorted(arr):
random.shuffle(arr)
if simulation:
iteration = iteration + 1
print("iteration",iteration,":",*arr)
return arr
|
python
|
def bogo_sort(arr, simulation=False):
"""Bogo Sort
Best Case Complexity: O(n)
Worst Case Complexity: O(∞)
Average Case Complexity: O(n(n-1)!)
"""
iteration = 0
if simulation:
print("iteration",iteration,":",*arr)
def is_sorted(arr):
#check the array is inorder
i = 0
arr_len = len(arr)
while i+1 < arr_len:
if arr[i] > arr[i+1]:
return False
i += 1
return True
while not is_sorted(arr):
random.shuffle(arr)
if simulation:
iteration = iteration + 1
print("iteration",iteration,":",*arr)
return arr
|
[
"def",
"bogo_sort",
"(",
"arr",
",",
"simulation",
"=",
"False",
")",
":",
"iteration",
"=",
"0",
"if",
"simulation",
":",
"print",
"(",
"\"iteration\"",
",",
"iteration",
",",
"\":\"",
",",
"*",
"arr",
")",
"def",
"is_sorted",
"(",
"arr",
")",
":",
"#check the array is inorder",
"i",
"=",
"0",
"arr_len",
"=",
"len",
"(",
"arr",
")",
"while",
"i",
"+",
"1",
"<",
"arr_len",
":",
"if",
"arr",
"[",
"i",
"]",
">",
"arr",
"[",
"i",
"+",
"1",
"]",
":",
"return",
"False",
"i",
"+=",
"1",
"return",
"True",
"while",
"not",
"is_sorted",
"(",
"arr",
")",
":",
"random",
".",
"shuffle",
"(",
"arr",
")",
"if",
"simulation",
":",
"iteration",
"=",
"iteration",
"+",
"1",
"print",
"(",
"\"iteration\"",
",",
"iteration",
",",
"\":\"",
",",
"*",
"arr",
")",
"return",
"arr"
] |
Bogo Sort
Best Case Complexity: O(n)
Worst Case Complexity: O(∞)
Average Case Complexity: O(n(n-1)!)
|
[
"Bogo",
"Sort",
"Best",
"Case",
"Complexity",
":",
"O",
"(",
"n",
")",
"Worst",
"Case",
"Complexity",
":",
"O",
"(",
"∞",
")",
"Average",
"Case",
"Complexity",
":",
"O",
"(",
"n",
"(",
"n",
"-",
"1",
")",
"!",
")"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/sort/bogo_sort.py#L3-L32
|
train
|
keon/algorithms
|
algorithms/tree/avl/avl.py
|
AvlTree.insert
|
def insert(self, key):
"""
Insert new key into node
"""
# Create new node
n = TreeNode(key)
if not self.node:
self.node = n
self.node.left = AvlTree()
self.node.right = AvlTree()
elif key < self.node.val:
self.node.left.insert(key)
elif key > self.node.val:
self.node.right.insert(key)
self.re_balance()
|
python
|
def insert(self, key):
"""
Insert new key into node
"""
# Create new node
n = TreeNode(key)
if not self.node:
self.node = n
self.node.left = AvlTree()
self.node.right = AvlTree()
elif key < self.node.val:
self.node.left.insert(key)
elif key > self.node.val:
self.node.right.insert(key)
self.re_balance()
|
[
"def",
"insert",
"(",
"self",
",",
"key",
")",
":",
"# Create new node",
"n",
"=",
"TreeNode",
"(",
"key",
")",
"if",
"not",
"self",
".",
"node",
":",
"self",
".",
"node",
"=",
"n",
"self",
".",
"node",
".",
"left",
"=",
"AvlTree",
"(",
")",
"self",
".",
"node",
".",
"right",
"=",
"AvlTree",
"(",
")",
"elif",
"key",
"<",
"self",
".",
"node",
".",
"val",
":",
"self",
".",
"node",
".",
"left",
".",
"insert",
"(",
"key",
")",
"elif",
"key",
">",
"self",
".",
"node",
".",
"val",
":",
"self",
".",
"node",
".",
"right",
".",
"insert",
"(",
"key",
")",
"self",
".",
"re_balance",
"(",
")"
] |
Insert new key into node
|
[
"Insert",
"new",
"key",
"into",
"node"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/avl/avl.py#L15-L29
|
train
|
keon/algorithms
|
algorithms/tree/avl/avl.py
|
AvlTree.re_balance
|
def re_balance(self):
"""
Re balance tree. After inserting or deleting a node,
"""
self.update_heights(recursive=False)
self.update_balances(False)
while self.balance < -1 or self.balance > 1:
if self.balance > 1:
if self.node.left.balance < 0:
self.node.left.rotate_left()
self.update_heights()
self.update_balances()
self.rotate_right()
self.update_heights()
self.update_balances()
if self.balance < -1:
if self.node.right.balance > 0:
self.node.right.rotate_right()
self.update_heights()
self.update_balances()
self.rotate_left()
self.update_heights()
self.update_balances()
|
python
|
def re_balance(self):
"""
Re balance tree. After inserting or deleting a node,
"""
self.update_heights(recursive=False)
self.update_balances(False)
while self.balance < -1 or self.balance > 1:
if self.balance > 1:
if self.node.left.balance < 0:
self.node.left.rotate_left()
self.update_heights()
self.update_balances()
self.rotate_right()
self.update_heights()
self.update_balances()
if self.balance < -1:
if self.node.right.balance > 0:
self.node.right.rotate_right()
self.update_heights()
self.update_balances()
self.rotate_left()
self.update_heights()
self.update_balances()
|
[
"def",
"re_balance",
"(",
"self",
")",
":",
"self",
".",
"update_heights",
"(",
"recursive",
"=",
"False",
")",
"self",
".",
"update_balances",
"(",
"False",
")",
"while",
"self",
".",
"balance",
"<",
"-",
"1",
"or",
"self",
".",
"balance",
">",
"1",
":",
"if",
"self",
".",
"balance",
">",
"1",
":",
"if",
"self",
".",
"node",
".",
"left",
".",
"balance",
"<",
"0",
":",
"self",
".",
"node",
".",
"left",
".",
"rotate_left",
"(",
")",
"self",
".",
"update_heights",
"(",
")",
"self",
".",
"update_balances",
"(",
")",
"self",
".",
"rotate_right",
"(",
")",
"self",
".",
"update_heights",
"(",
")",
"self",
".",
"update_balances",
"(",
")",
"if",
"self",
".",
"balance",
"<",
"-",
"1",
":",
"if",
"self",
".",
"node",
".",
"right",
".",
"balance",
">",
"0",
":",
"self",
".",
"node",
".",
"right",
".",
"rotate_right",
"(",
")",
"self",
".",
"update_heights",
"(",
")",
"self",
".",
"update_balances",
"(",
")",
"self",
".",
"rotate_left",
"(",
")",
"self",
".",
"update_heights",
"(",
")",
"self",
".",
"update_balances",
"(",
")"
] |
Re balance tree. After inserting or deleting a node,
|
[
"Re",
"balance",
"tree",
".",
"After",
"inserting",
"or",
"deleting",
"a",
"node"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/avl/avl.py#L31-L55
|
train
|
keon/algorithms
|
algorithms/tree/avl/avl.py
|
AvlTree.update_heights
|
def update_heights(self, recursive=True):
"""
Update tree height
"""
if self.node:
if recursive:
if self.node.left:
self.node.left.update_heights()
if self.node.right:
self.node.right.update_heights()
self.height = 1 + max(self.node.left.height, self.node.right.height)
else:
self.height = -1
|
python
|
def update_heights(self, recursive=True):
"""
Update tree height
"""
if self.node:
if recursive:
if self.node.left:
self.node.left.update_heights()
if self.node.right:
self.node.right.update_heights()
self.height = 1 + max(self.node.left.height, self.node.right.height)
else:
self.height = -1
|
[
"def",
"update_heights",
"(",
"self",
",",
"recursive",
"=",
"True",
")",
":",
"if",
"self",
".",
"node",
":",
"if",
"recursive",
":",
"if",
"self",
".",
"node",
".",
"left",
":",
"self",
".",
"node",
".",
"left",
".",
"update_heights",
"(",
")",
"if",
"self",
".",
"node",
".",
"right",
":",
"self",
".",
"node",
".",
"right",
".",
"update_heights",
"(",
")",
"self",
".",
"height",
"=",
"1",
"+",
"max",
"(",
"self",
".",
"node",
".",
"left",
".",
"height",
",",
"self",
".",
"node",
".",
"right",
".",
"height",
")",
"else",
":",
"self",
".",
"height",
"=",
"-",
"1"
] |
Update tree height
|
[
"Update",
"tree",
"height"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/avl/avl.py#L57-L70
|
train
|
keon/algorithms
|
algorithms/tree/avl/avl.py
|
AvlTree.update_balances
|
def update_balances(self, recursive=True):
"""
Calculate tree balance factor
"""
if self.node:
if recursive:
if self.node.left:
self.node.left.update_balances()
if self.node.right:
self.node.right.update_balances()
self.balance = self.node.left.height - self.node.right.height
else:
self.balance = 0
|
python
|
def update_balances(self, recursive=True):
"""
Calculate tree balance factor
"""
if self.node:
if recursive:
if self.node.left:
self.node.left.update_balances()
if self.node.right:
self.node.right.update_balances()
self.balance = self.node.left.height - self.node.right.height
else:
self.balance = 0
|
[
"def",
"update_balances",
"(",
"self",
",",
"recursive",
"=",
"True",
")",
":",
"if",
"self",
".",
"node",
":",
"if",
"recursive",
":",
"if",
"self",
".",
"node",
".",
"left",
":",
"self",
".",
"node",
".",
"left",
".",
"update_balances",
"(",
")",
"if",
"self",
".",
"node",
".",
"right",
":",
"self",
".",
"node",
".",
"right",
".",
"update_balances",
"(",
")",
"self",
".",
"balance",
"=",
"self",
".",
"node",
".",
"left",
".",
"height",
"-",
"self",
".",
"node",
".",
"right",
".",
"height",
"else",
":",
"self",
".",
"balance",
"=",
"0"
] |
Calculate tree balance factor
|
[
"Calculate",
"tree",
"balance",
"factor"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/avl/avl.py#L72-L86
|
train
|
keon/algorithms
|
algorithms/tree/avl/avl.py
|
AvlTree.rotate_right
|
def rotate_right(self):
"""
Right rotation
"""
new_root = self.node.left.node
new_left_sub = new_root.right.node
old_root = self.node
self.node = new_root
old_root.left.node = new_left_sub
new_root.right.node = old_root
|
python
|
def rotate_right(self):
"""
Right rotation
"""
new_root = self.node.left.node
new_left_sub = new_root.right.node
old_root = self.node
self.node = new_root
old_root.left.node = new_left_sub
new_root.right.node = old_root
|
[
"def",
"rotate_right",
"(",
"self",
")",
":",
"new_root",
"=",
"self",
".",
"node",
".",
"left",
".",
"node",
"new_left_sub",
"=",
"new_root",
".",
"right",
".",
"node",
"old_root",
"=",
"self",
".",
"node",
"self",
".",
"node",
"=",
"new_root",
"old_root",
".",
"left",
".",
"node",
"=",
"new_left_sub",
"new_root",
".",
"right",
".",
"node",
"=",
"old_root"
] |
Right rotation
|
[
"Right",
"rotation"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/avl/avl.py#L88-L98
|
train
|
keon/algorithms
|
algorithms/tree/avl/avl.py
|
AvlTree.rotate_left
|
def rotate_left(self):
"""
Left rotation
"""
new_root = self.node.right.node
new_left_sub = new_root.left.node
old_root = self.node
self.node = new_root
old_root.right.node = new_left_sub
new_root.left.node = old_root
|
python
|
def rotate_left(self):
"""
Left rotation
"""
new_root = self.node.right.node
new_left_sub = new_root.left.node
old_root = self.node
self.node = new_root
old_root.right.node = new_left_sub
new_root.left.node = old_root
|
[
"def",
"rotate_left",
"(",
"self",
")",
":",
"new_root",
"=",
"self",
".",
"node",
".",
"right",
".",
"node",
"new_left_sub",
"=",
"new_root",
".",
"left",
".",
"node",
"old_root",
"=",
"self",
".",
"node",
"self",
".",
"node",
"=",
"new_root",
"old_root",
".",
"right",
".",
"node",
"=",
"new_left_sub",
"new_root",
".",
"left",
".",
"node",
"=",
"old_root"
] |
Left rotation
|
[
"Left",
"rotation"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/avl/avl.py#L100-L110
|
train
|
keon/algorithms
|
algorithms/tree/avl/avl.py
|
AvlTree.in_order_traverse
|
def in_order_traverse(self):
"""
In-order traversal of the tree
"""
result = []
if not self.node:
return result
result.extend(self.node.left.in_order_traverse())
result.append(self.node.key)
result.extend(self.node.right.in_order_traverse())
return result
|
python
|
def in_order_traverse(self):
"""
In-order traversal of the tree
"""
result = []
if not self.node:
return result
result.extend(self.node.left.in_order_traverse())
result.append(self.node.key)
result.extend(self.node.right.in_order_traverse())
return result
|
[
"def",
"in_order_traverse",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"node",
":",
"return",
"result",
"result",
".",
"extend",
"(",
"self",
".",
"node",
".",
"left",
".",
"in_order_traverse",
"(",
")",
")",
"result",
".",
"append",
"(",
"self",
".",
"node",
".",
"key",
")",
"result",
".",
"extend",
"(",
"self",
".",
"node",
".",
"right",
".",
"in_order_traverse",
"(",
")",
")",
"return",
"result"
] |
In-order traversal of the tree
|
[
"In",
"-",
"order",
"traversal",
"of",
"the",
"tree"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/tree/avl/avl.py#L112-L124
|
train
|
keon/algorithms
|
algorithms/maths/generate_strobogrammtic.py
|
strobogrammatic_in_range
|
def strobogrammatic_in_range(low, high):
"""
:type low: str
:type high: str
:rtype: int
"""
res = []
count = 0
low_len = len(low)
high_len = len(high)
for i in range(low_len, high_len + 1):
res.extend(helper2(i, i))
for perm in res:
if len(perm) == low_len and int(perm) < int(low):
continue
elif len(perm) == high_len and int(perm) > int(high):
continue
else:
count += 1
return count
|
python
|
def strobogrammatic_in_range(low, high):
"""
:type low: str
:type high: str
:rtype: int
"""
res = []
count = 0
low_len = len(low)
high_len = len(high)
for i in range(low_len, high_len + 1):
res.extend(helper2(i, i))
for perm in res:
if len(perm) == low_len and int(perm) < int(low):
continue
elif len(perm) == high_len and int(perm) > int(high):
continue
else:
count += 1
return count
|
[
"def",
"strobogrammatic_in_range",
"(",
"low",
",",
"high",
")",
":",
"res",
"=",
"[",
"]",
"count",
"=",
"0",
"low_len",
"=",
"len",
"(",
"low",
")",
"high_len",
"=",
"len",
"(",
"high",
")",
"for",
"i",
"in",
"range",
"(",
"low_len",
",",
"high_len",
"+",
"1",
")",
":",
"res",
".",
"extend",
"(",
"helper2",
"(",
"i",
",",
"i",
")",
")",
"for",
"perm",
"in",
"res",
":",
"if",
"len",
"(",
"perm",
")",
"==",
"low_len",
"and",
"int",
"(",
"perm",
")",
"<",
"int",
"(",
"low",
")",
":",
"continue",
"elif",
"len",
"(",
"perm",
")",
"==",
"high_len",
"and",
"int",
"(",
"perm",
")",
">",
"int",
"(",
"high",
")",
":",
"continue",
"else",
":",
"count",
"+=",
"1",
"return",
"count"
] |
:type low: str
:type high: str
:rtype: int
|
[
":",
"type",
"low",
":",
"str",
":",
"type",
"high",
":",
"str",
":",
"rtype",
":",
"int"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/maths/generate_strobogrammtic.py#L37-L56
|
train
|
keon/algorithms
|
algorithms/set/find_keyboard_row.py
|
find_keyboard_row
|
def find_keyboard_row(words):
"""
:type words: List[str]
:rtype: List[str]
"""
keyboard = [
set('qwertyuiop'),
set('asdfghjkl'),
set('zxcvbnm'),
]
result = []
for word in words:
for key in keyboard:
if set(word.lower()).issubset(key):
result.append(word)
return result
|
python
|
def find_keyboard_row(words):
"""
:type words: List[str]
:rtype: List[str]
"""
keyboard = [
set('qwertyuiop'),
set('asdfghjkl'),
set('zxcvbnm'),
]
result = []
for word in words:
for key in keyboard:
if set(word.lower()).issubset(key):
result.append(word)
return result
|
[
"def",
"find_keyboard_row",
"(",
"words",
")",
":",
"keyboard",
"=",
"[",
"set",
"(",
"'qwertyuiop'",
")",
",",
"set",
"(",
"'asdfghjkl'",
")",
",",
"set",
"(",
"'zxcvbnm'",
")",
",",
"]",
"result",
"=",
"[",
"]",
"for",
"word",
"in",
"words",
":",
"for",
"key",
"in",
"keyboard",
":",
"if",
"set",
"(",
"word",
".",
"lower",
"(",
")",
")",
".",
"issubset",
"(",
"key",
")",
":",
"result",
".",
"append",
"(",
"word",
")",
"return",
"result"
] |
:type words: List[str]
:rtype: List[str]
|
[
":",
"type",
"words",
":",
"List",
"[",
"str",
"]",
":",
"rtype",
":",
"List",
"[",
"str",
"]"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/set/find_keyboard_row.py#L11-L26
|
train
|
keon/algorithms
|
algorithms/linkedlist/kth_to_last.py
|
kth_to_last_eval
|
def kth_to_last_eval(head, k):
"""
This is a suboptimal, hacky method using eval(), which is not
safe for user input. We guard against danger by ensuring k in an int
"""
if not isinstance(k, int) or not head.val:
return False
nexts = '.'.join(['next' for n in range(1, k+1)])
seeker = str('.'.join(['head', nexts]))
while head:
if eval(seeker) is None:
return head
else:
head = head.next
return False
|
python
|
def kth_to_last_eval(head, k):
"""
This is a suboptimal, hacky method using eval(), which is not
safe for user input. We guard against danger by ensuring k in an int
"""
if not isinstance(k, int) or not head.val:
return False
nexts = '.'.join(['next' for n in range(1, k+1)])
seeker = str('.'.join(['head', nexts]))
while head:
if eval(seeker) is None:
return head
else:
head = head.next
return False
|
[
"def",
"kth_to_last_eval",
"(",
"head",
",",
"k",
")",
":",
"if",
"not",
"isinstance",
"(",
"k",
",",
"int",
")",
"or",
"not",
"head",
".",
"val",
":",
"return",
"False",
"nexts",
"=",
"'.'",
".",
"join",
"(",
"[",
"'next'",
"for",
"n",
"in",
"range",
"(",
"1",
",",
"k",
"+",
"1",
")",
"]",
")",
"seeker",
"=",
"str",
"(",
"'.'",
".",
"join",
"(",
"[",
"'head'",
",",
"nexts",
"]",
")",
")",
"while",
"head",
":",
"if",
"eval",
"(",
"seeker",
")",
"is",
"None",
":",
"return",
"head",
"else",
":",
"head",
"=",
"head",
".",
"next",
"return",
"False"
] |
This is a suboptimal, hacky method using eval(), which is not
safe for user input. We guard against danger by ensuring k in an int
|
[
"This",
"is",
"a",
"suboptimal",
"hacky",
"method",
"using",
"eval",
"()",
"which",
"is",
"not",
"safe",
"for",
"user",
"input",
".",
"We",
"guard",
"against",
"danger",
"by",
"ensuring",
"k",
"in",
"an",
"int"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/kth_to_last.py#L7-L24
|
train
|
keon/algorithms
|
algorithms/linkedlist/kth_to_last.py
|
kth_to_last_dict
|
def kth_to_last_dict(head, k):
"""
This is a brute force method where we keep a dict the size of the list
Then we check it for the value we need. If the key is not in the dict,
our and statement will short circuit and return False
"""
if not (head and k > -1):
return False
d = dict()
count = 0
while head:
d[count] = head
head = head.next
count += 1
return len(d)-k in d and d[len(d)-k]
|
python
|
def kth_to_last_dict(head, k):
"""
This is a brute force method where we keep a dict the size of the list
Then we check it for the value we need. If the key is not in the dict,
our and statement will short circuit and return False
"""
if not (head and k > -1):
return False
d = dict()
count = 0
while head:
d[count] = head
head = head.next
count += 1
return len(d)-k in d and d[len(d)-k]
|
[
"def",
"kth_to_last_dict",
"(",
"head",
",",
"k",
")",
":",
"if",
"not",
"(",
"head",
"and",
"k",
">",
"-",
"1",
")",
":",
"return",
"False",
"d",
"=",
"dict",
"(",
")",
"count",
"=",
"0",
"while",
"head",
":",
"d",
"[",
"count",
"]",
"=",
"head",
"head",
"=",
"head",
".",
"next",
"count",
"+=",
"1",
"return",
"len",
"(",
"d",
")",
"-",
"k",
"in",
"d",
"and",
"d",
"[",
"len",
"(",
"d",
")",
"-",
"k",
"]"
] |
This is a brute force method where we keep a dict the size of the list
Then we check it for the value we need. If the key is not in the dict,
our and statement will short circuit and return False
|
[
"This",
"is",
"a",
"brute",
"force",
"method",
"where",
"we",
"keep",
"a",
"dict",
"the",
"size",
"of",
"the",
"list",
"Then",
"we",
"check",
"it",
"for",
"the",
"value",
"we",
"need",
".",
"If",
"the",
"key",
"is",
"not",
"in",
"the",
"dict",
"our",
"and",
"statement",
"will",
"short",
"circuit",
"and",
"return",
"False"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/kth_to_last.py#L27-L41
|
train
|
keon/algorithms
|
algorithms/linkedlist/kth_to_last.py
|
kth_to_last
|
def kth_to_last(head, k):
"""
This is an optimal method using iteration.
We move p1 k steps ahead into the list.
Then we move p1 and p2 together until p1 hits the end.
"""
if not (head or k > -1):
return False
p1 = head
p2 = head
for i in range(1, k+1):
if p1 is None:
# Went too far, k is not valid
raise IndexError
p1 = p1.next
while p1:
p1 = p1.next
p2 = p2.next
return p2
|
python
|
def kth_to_last(head, k):
"""
This is an optimal method using iteration.
We move p1 k steps ahead into the list.
Then we move p1 and p2 together until p1 hits the end.
"""
if not (head or k > -1):
return False
p1 = head
p2 = head
for i in range(1, k+1):
if p1 is None:
# Went too far, k is not valid
raise IndexError
p1 = p1.next
while p1:
p1 = p1.next
p2 = p2.next
return p2
|
[
"def",
"kth_to_last",
"(",
"head",
",",
"k",
")",
":",
"if",
"not",
"(",
"head",
"or",
"k",
">",
"-",
"1",
")",
":",
"return",
"False",
"p1",
"=",
"head",
"p2",
"=",
"head",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"k",
"+",
"1",
")",
":",
"if",
"p1",
"is",
"None",
":",
"# Went too far, k is not valid",
"raise",
"IndexError",
"p1",
"=",
"p1",
".",
"next",
"while",
"p1",
":",
"p1",
"=",
"p1",
".",
"next",
"p2",
"=",
"p2",
".",
"next",
"return",
"p2"
] |
This is an optimal method using iteration.
We move p1 k steps ahead into the list.
Then we move p1 and p2 together until p1 hits the end.
|
[
"This",
"is",
"an",
"optimal",
"method",
"using",
"iteration",
".",
"We",
"move",
"p1",
"k",
"steps",
"ahead",
"into",
"the",
"list",
".",
"Then",
"we",
"move",
"p1",
"and",
"p2",
"together",
"until",
"p1",
"hits",
"the",
"end",
"."
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/linkedlist/kth_to_last.py#L44-L62
|
train
|
keon/algorithms
|
algorithms/heap/skyline.py
|
get_skyline
|
def get_skyline(lrh):
"""
Wortst Time Complexity: O(NlogN)
:type buildings: List[List[int]]
:rtype: List[List[int]]
"""
skyline, live = [], []
i, n = 0, len(lrh)
while i < n or live:
if not live or i < n and lrh[i][0] <= -live[0][1]:
x = lrh[i][0]
while i < n and lrh[i][0] == x:
heapq.heappush(live, (-lrh[i][2], -lrh[i][1]))
i += 1
else:
x = -live[0][1]
while live and -live[0][1] <= x:
heapq.heappop(live)
height = len(live) and -live[0][0]
if not skyline or height != skyline[-1][1]:
skyline += [x, height],
return skyline
|
python
|
def get_skyline(lrh):
"""
Wortst Time Complexity: O(NlogN)
:type buildings: List[List[int]]
:rtype: List[List[int]]
"""
skyline, live = [], []
i, n = 0, len(lrh)
while i < n or live:
if not live or i < n and lrh[i][0] <= -live[0][1]:
x = lrh[i][0]
while i < n and lrh[i][0] == x:
heapq.heappush(live, (-lrh[i][2], -lrh[i][1]))
i += 1
else:
x = -live[0][1]
while live and -live[0][1] <= x:
heapq.heappop(live)
height = len(live) and -live[0][0]
if not skyline or height != skyline[-1][1]:
skyline += [x, height],
return skyline
|
[
"def",
"get_skyline",
"(",
"lrh",
")",
":",
"skyline",
",",
"live",
"=",
"[",
"]",
",",
"[",
"]",
"i",
",",
"n",
"=",
"0",
",",
"len",
"(",
"lrh",
")",
"while",
"i",
"<",
"n",
"or",
"live",
":",
"if",
"not",
"live",
"or",
"i",
"<",
"n",
"and",
"lrh",
"[",
"i",
"]",
"[",
"0",
"]",
"<=",
"-",
"live",
"[",
"0",
"]",
"[",
"1",
"]",
":",
"x",
"=",
"lrh",
"[",
"i",
"]",
"[",
"0",
"]",
"while",
"i",
"<",
"n",
"and",
"lrh",
"[",
"i",
"]",
"[",
"0",
"]",
"==",
"x",
":",
"heapq",
".",
"heappush",
"(",
"live",
",",
"(",
"-",
"lrh",
"[",
"i",
"]",
"[",
"2",
"]",
",",
"-",
"lrh",
"[",
"i",
"]",
"[",
"1",
"]",
")",
")",
"i",
"+=",
"1",
"else",
":",
"x",
"=",
"-",
"live",
"[",
"0",
"]",
"[",
"1",
"]",
"while",
"live",
"and",
"-",
"live",
"[",
"0",
"]",
"[",
"1",
"]",
"<=",
"x",
":",
"heapq",
".",
"heappop",
"(",
"live",
")",
"height",
"=",
"len",
"(",
"live",
")",
"and",
"-",
"live",
"[",
"0",
"]",
"[",
"0",
"]",
"if",
"not",
"skyline",
"or",
"height",
"!=",
"skyline",
"[",
"-",
"1",
"]",
"[",
"1",
"]",
":",
"skyline",
"+=",
"[",
"x",
",",
"height",
"]",
",",
"return",
"skyline"
] |
Wortst Time Complexity: O(NlogN)
:type buildings: List[List[int]]
:rtype: List[List[int]]
|
[
"Wortst",
"Time",
"Complexity",
":",
"O",
"(",
"NlogN",
")",
":",
"type",
"buildings",
":",
"List",
"[",
"List",
"[",
"int",
"]]",
":",
"rtype",
":",
"List",
"[",
"List",
"[",
"int",
"]]"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/heap/skyline.py#L39-L60
|
train
|
keon/algorithms
|
algorithms/arrays/summarize_ranges.py
|
summarize_ranges
|
def summarize_ranges(array):
"""
:type array: List[int]
:rtype: List[]
"""
res = []
if len(array) == 1:
return [str(array[0])]
i = 0
while i < len(array):
num = array[i]
while i + 1 < len(array) and array[i + 1] - array[i] == 1:
i += 1
if array[i] != num:
res.append((num, array[i]))
else:
res.append((num, num))
i += 1
return res
|
python
|
def summarize_ranges(array):
"""
:type array: List[int]
:rtype: List[]
"""
res = []
if len(array) == 1:
return [str(array[0])]
i = 0
while i < len(array):
num = array[i]
while i + 1 < len(array) and array[i + 1] - array[i] == 1:
i += 1
if array[i] != num:
res.append((num, array[i]))
else:
res.append((num, num))
i += 1
return res
|
[
"def",
"summarize_ranges",
"(",
"array",
")",
":",
"res",
"=",
"[",
"]",
"if",
"len",
"(",
"array",
")",
"==",
"1",
":",
"return",
"[",
"str",
"(",
"array",
"[",
"0",
"]",
")",
"]",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"array",
")",
":",
"num",
"=",
"array",
"[",
"i",
"]",
"while",
"i",
"+",
"1",
"<",
"len",
"(",
"array",
")",
"and",
"array",
"[",
"i",
"+",
"1",
"]",
"-",
"array",
"[",
"i",
"]",
"==",
"1",
":",
"i",
"+=",
"1",
"if",
"array",
"[",
"i",
"]",
"!=",
"num",
":",
"res",
".",
"append",
"(",
"(",
"num",
",",
"array",
"[",
"i",
"]",
")",
")",
"else",
":",
"res",
".",
"append",
"(",
"(",
"num",
",",
"num",
")",
")",
"i",
"+=",
"1",
"return",
"res"
] |
:type array: List[int]
:rtype: List[]
|
[
":",
"type",
"array",
":",
"List",
"[",
"int",
"]",
":",
"rtype",
":",
"List",
"[]"
] |
4d6569464a62a75c1357acc97e2dd32ee2f9f4a3
|
https://github.com/keon/algorithms/blob/4d6569464a62a75c1357acc97e2dd32ee2f9f4a3/algorithms/arrays/summarize_ranges.py#L9-L27
|
train
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.