Initial Commit
This commit is contained in:
commit
3f7e7eda67
|
@ -0,0 +1,595 @@
|
||||||
|
### JetBrains template
|
||||||
|
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
|
||||||
|
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||||
|
|
||||||
|
# User-specific stuff
|
||||||
|
.idea/**/workspace.xml
|
||||||
|
.idea/**/tasks.xml
|
||||||
|
.idea/**/usage.statistics.xml
|
||||||
|
.idea/**/dictionaries
|
||||||
|
.idea/**/shelf
|
||||||
|
|
||||||
|
# AWS User-specific
|
||||||
|
.idea/**/aws.xml
|
||||||
|
|
||||||
|
# Generated files
|
||||||
|
.idea/**/contentModel.xml
|
||||||
|
|
||||||
|
# Sensitive or high-churn files
|
||||||
|
.idea/**/dataSources/
|
||||||
|
.idea/**/dataSources.ids
|
||||||
|
.idea/**/dataSources.local.xml
|
||||||
|
.idea/**/sqlDataSources.xml
|
||||||
|
.idea/**/dynamic.xml
|
||||||
|
.idea/**/uiDesigner.xml
|
||||||
|
.idea/**/dbnavigator.xml
|
||||||
|
|
||||||
|
# Gradle
|
||||||
|
.idea/**/gradle.xml
|
||||||
|
.idea/**/libraries
|
||||||
|
|
||||||
|
# Gradle and Maven with auto-import
|
||||||
|
# When using Gradle or Maven with auto-import, you should exclude module files,
|
||||||
|
# since they will be recreated, and may cause churn. Uncomment if using
|
||||||
|
# auto-import.
|
||||||
|
# .idea/artifacts
|
||||||
|
# .idea/compiler.xml
|
||||||
|
# .idea/jarRepositories.xml
|
||||||
|
# .idea/modules.xml
|
||||||
|
# .idea/*.iml
|
||||||
|
# .idea/modules
|
||||||
|
# *.iml
|
||||||
|
# *.ipr
|
||||||
|
|
||||||
|
# CMake
|
||||||
|
cmake-build-*/
|
||||||
|
|
||||||
|
# Mongo Explorer plugin
|
||||||
|
.idea/**/mongoSettings.xml
|
||||||
|
|
||||||
|
# File-based project format
|
||||||
|
*.iws
|
||||||
|
|
||||||
|
# IntelliJ
|
||||||
|
out/
|
||||||
|
|
||||||
|
# mpeltonen/sbt-idea plugin
|
||||||
|
.idea_modules/
|
||||||
|
|
||||||
|
# JIRA plugin
|
||||||
|
atlassian-ide-plugin.xml
|
||||||
|
|
||||||
|
# Cursive Clojure plugin
|
||||||
|
.idea/replstate.xml
|
||||||
|
|
||||||
|
# SonarLint plugin
|
||||||
|
.idea/sonarlint/
|
||||||
|
|
||||||
|
# Crashlytics plugin (for Android Studio and IntelliJ)
|
||||||
|
com_crashlytics_export_strings.xml
|
||||||
|
crashlytics.properties
|
||||||
|
crashlytics-build.properties
|
||||||
|
fabric.properties
|
||||||
|
|
||||||
|
# Editor-based Rest Client
|
||||||
|
.idea/httpRequests
|
||||||
|
|
||||||
|
# Android studio 3.1+ serialized cache file
|
||||||
|
.idea/caches/build_file_checksums.ser
|
||||||
|
|
||||||
|
### VirtualEnv template
|
||||||
|
# Virtualenv
|
||||||
|
# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/
|
||||||
|
.Python
|
||||||
|
[Bb]in
|
||||||
|
[Ii]nclude
|
||||||
|
[Ll]ib
|
||||||
|
[Ll]ib64
|
||||||
|
[Ll]ocal
|
||||||
|
[Ss]cripts
|
||||||
|
pyvenv.cfg
|
||||||
|
.venv
|
||||||
|
pip-selfcheck.json
|
||||||
|
|
||||||
|
### TeX template
|
||||||
|
## Core latex/pdflatex auxiliary files:
|
||||||
|
*.aux
|
||||||
|
*.lof
|
||||||
|
*.log
|
||||||
|
*.lot
|
||||||
|
*.fls
|
||||||
|
*.out
|
||||||
|
*.toc
|
||||||
|
*.fmt
|
||||||
|
*.fot
|
||||||
|
*.cb
|
||||||
|
*.cb2
|
||||||
|
.*.lb
|
||||||
|
|
||||||
|
## Intermediate documents:
|
||||||
|
*.dvi
|
||||||
|
*.xdv
|
||||||
|
*-converted-to.*
|
||||||
|
# these rules might exclude image files for figures etc.
|
||||||
|
# *.ps
|
||||||
|
# *.eps
|
||||||
|
# *.pdf
|
||||||
|
|
||||||
|
## Generated if empty string is given at "Please type another file name for output:"
|
||||||
|
.pdf
|
||||||
|
|
||||||
|
## Bibliography auxiliary files (bibtex/biblatex/biber):
|
||||||
|
*.bbl
|
||||||
|
*.bcf
|
||||||
|
*.blg
|
||||||
|
*-blx.aux
|
||||||
|
*-blx.bib
|
||||||
|
*.run.xml
|
||||||
|
|
||||||
|
## Build tool auxiliary files:
|
||||||
|
*.fdb_latexmk
|
||||||
|
*.synctex
|
||||||
|
*.synctex(busy)
|
||||||
|
*.synctex.gz
|
||||||
|
*.synctex.gz(busy)
|
||||||
|
*.pdfsync
|
||||||
|
|
||||||
|
## Build tool directories for auxiliary files
|
||||||
|
# latexrun
|
||||||
|
latex.out/
|
||||||
|
|
||||||
|
## Auxiliary and intermediate files from other packages:
|
||||||
|
# algorithms
|
||||||
|
*.alg
|
||||||
|
*.loa
|
||||||
|
|
||||||
|
# achemso
|
||||||
|
acs-*.bib
|
||||||
|
|
||||||
|
# amsthm
|
||||||
|
*.thm
|
||||||
|
|
||||||
|
# beamer
|
||||||
|
*.nav
|
||||||
|
*.pre
|
||||||
|
*.snm
|
||||||
|
*.vrb
|
||||||
|
|
||||||
|
# changes
|
||||||
|
*.soc
|
||||||
|
|
||||||
|
# comment
|
||||||
|
*.cut
|
||||||
|
|
||||||
|
# cprotect
|
||||||
|
*.cpt
|
||||||
|
|
||||||
|
# elsarticle (documentclass of Elsevier journals)
|
||||||
|
*.spl
|
||||||
|
|
||||||
|
# endnotes
|
||||||
|
*.ent
|
||||||
|
|
||||||
|
# fixme
|
||||||
|
*.lox
|
||||||
|
|
||||||
|
# feynmf/feynmp
|
||||||
|
*.mf
|
||||||
|
*.mp
|
||||||
|
*.t[1-9]
|
||||||
|
*.t[1-9][0-9]
|
||||||
|
*.tfm
|
||||||
|
|
||||||
|
#(r)(e)ledmac/(r)(e)ledpar
|
||||||
|
*.end
|
||||||
|
*.?end
|
||||||
|
*.[1-9]
|
||||||
|
*.[1-9][0-9]
|
||||||
|
*.[1-9][0-9][0-9]
|
||||||
|
*.[1-9]R
|
||||||
|
*.[1-9][0-9]R
|
||||||
|
*.[1-9][0-9][0-9]R
|
||||||
|
*.eledsec[1-9]
|
||||||
|
*.eledsec[1-9]R
|
||||||
|
*.eledsec[1-9][0-9]
|
||||||
|
*.eledsec[1-9][0-9]R
|
||||||
|
*.eledsec[1-9][0-9][0-9]
|
||||||
|
*.eledsec[1-9][0-9][0-9]R
|
||||||
|
|
||||||
|
# glossaries
|
||||||
|
*.acn
|
||||||
|
*.acr
|
||||||
|
*.glg
|
||||||
|
*.glo
|
||||||
|
*.gls
|
||||||
|
*.glsdefs
|
||||||
|
*.lzo
|
||||||
|
*.lzs
|
||||||
|
*.slg
|
||||||
|
*.slo
|
||||||
|
*.sls
|
||||||
|
|
||||||
|
# uncomment this for glossaries-extra (will ignore makeindex's style files!)
|
||||||
|
# *.ist
|
||||||
|
|
||||||
|
# gnuplot
|
||||||
|
*.gnuplot
|
||||||
|
*.table
|
||||||
|
|
||||||
|
# gnuplottex
|
||||||
|
*-gnuplottex-*
|
||||||
|
|
||||||
|
# gregoriotex
|
||||||
|
*.gaux
|
||||||
|
*.glog
|
||||||
|
*.gtex
|
||||||
|
|
||||||
|
# htlatex
|
||||||
|
*.4ct
|
||||||
|
*.4tc
|
||||||
|
*.idv
|
||||||
|
*.lg
|
||||||
|
*.trc
|
||||||
|
*.xref
|
||||||
|
|
||||||
|
# hyperref
|
||||||
|
*.brf
|
||||||
|
|
||||||
|
# knitr
|
||||||
|
*-concordance.tex
|
||||||
|
# TODO Uncomment the next line if you use knitr and want to ignore its generated tikz files
|
||||||
|
# *.tikz
|
||||||
|
*-tikzDictionary
|
||||||
|
|
||||||
|
# listings
|
||||||
|
*.lol
|
||||||
|
|
||||||
|
# luatexja-ruby
|
||||||
|
*.ltjruby
|
||||||
|
|
||||||
|
# makeidx
|
||||||
|
*.idx
|
||||||
|
*.ilg
|
||||||
|
*.ind
|
||||||
|
|
||||||
|
# minitoc
|
||||||
|
*.maf
|
||||||
|
*.mlf
|
||||||
|
*.mlt
|
||||||
|
*.mtc[0-9]*
|
||||||
|
*.slf[0-9]*
|
||||||
|
*.slt[0-9]*
|
||||||
|
*.stc[0-9]*
|
||||||
|
|
||||||
|
# minted
|
||||||
|
_minted*
|
||||||
|
*.pyg
|
||||||
|
|
||||||
|
# morewrites
|
||||||
|
*.mw
|
||||||
|
|
||||||
|
# newpax
|
||||||
|
*.newpax
|
||||||
|
|
||||||
|
# nomencl
|
||||||
|
*.nlg
|
||||||
|
*.nlo
|
||||||
|
*.nls
|
||||||
|
|
||||||
|
# pax
|
||||||
|
*.pax
|
||||||
|
|
||||||
|
# pdfpcnotes
|
||||||
|
*.pdfpc
|
||||||
|
|
||||||
|
# sagetex
|
||||||
|
*.sagetex.sage
|
||||||
|
*.sagetex.py
|
||||||
|
*.sagetex.scmd
|
||||||
|
|
||||||
|
# scrwfile
|
||||||
|
*.wrt
|
||||||
|
|
||||||
|
# svg
|
||||||
|
svg-inkscape/
|
||||||
|
|
||||||
|
# sympy
|
||||||
|
*.sout
|
||||||
|
*.sympy
|
||||||
|
sympy-plots-for-*.tex/
|
||||||
|
|
||||||
|
# pdfcomment
|
||||||
|
*.upa
|
||||||
|
*.upb
|
||||||
|
|
||||||
|
# pythontex
|
||||||
|
*.pytxcode
|
||||||
|
pythontex-files-*/
|
||||||
|
|
||||||
|
# tcolorbox
|
||||||
|
*.listing
|
||||||
|
|
||||||
|
# thmtools
|
||||||
|
*.loe
|
||||||
|
|
||||||
|
# TikZ & PGF
|
||||||
|
*.dpth
|
||||||
|
*.md5
|
||||||
|
*.auxlock
|
||||||
|
|
||||||
|
# titletoc
|
||||||
|
*.ptc
|
||||||
|
|
||||||
|
# todonotes
|
||||||
|
*.tdo
|
||||||
|
|
||||||
|
# vhistory
|
||||||
|
*.hst
|
||||||
|
*.ver
|
||||||
|
|
||||||
|
# easy-todo
|
||||||
|
*.lod
|
||||||
|
|
||||||
|
# xcolor
|
||||||
|
*.xcp
|
||||||
|
|
||||||
|
# xmpincl
|
||||||
|
*.xmpi
|
||||||
|
|
||||||
|
# xindy
|
||||||
|
*.xdy
|
||||||
|
|
||||||
|
# xypic precompiled matrices and outlines
|
||||||
|
*.xyc
|
||||||
|
*.xyd
|
||||||
|
|
||||||
|
# endfloat
|
||||||
|
*.ttt
|
||||||
|
*.fff
|
||||||
|
|
||||||
|
# Latexian
|
||||||
|
TSWLatexianTemp*
|
||||||
|
|
||||||
|
## Editors:
|
||||||
|
# WinEdt
|
||||||
|
*.bak
|
||||||
|
*.sav
|
||||||
|
|
||||||
|
# Texpad
|
||||||
|
.texpadtmp
|
||||||
|
|
||||||
|
# LyX
|
||||||
|
*.lyx~
|
||||||
|
|
||||||
|
# Kile
|
||||||
|
*.backup
|
||||||
|
|
||||||
|
# gummi
|
||||||
|
.*.swp
|
||||||
|
|
||||||
|
# KBibTeX
|
||||||
|
*~[0-9]*
|
||||||
|
|
||||||
|
# TeXnicCenter
|
||||||
|
*.tps
|
||||||
|
|
||||||
|
# auto folder when using emacs and auctex
|
||||||
|
./auto/*
|
||||||
|
*.el
|
||||||
|
|
||||||
|
# expex forward references with \gathertags
|
||||||
|
*-tags.tex
|
||||||
|
|
||||||
|
# standalone packages
|
||||||
|
*.sta
|
||||||
|
|
||||||
|
# Makeindex log files
|
||||||
|
*.lpz
|
||||||
|
|
||||||
|
# xwatermark package
|
||||||
|
*.xwm
|
||||||
|
|
||||||
|
# REVTeX puts footnotes in the bibliography by default, unless the nofootinbib
|
||||||
|
# option is specified. Footnotes are the stored in a file with suffix Notes.bib.
|
||||||
|
# Uncomment the next line to have this generated file ignored.
|
||||||
|
#*Notes.bib
|
||||||
|
|
||||||
|
### Example user template template
|
||||||
|
### Example user template
|
||||||
|
|
||||||
|
# IntelliJ project files
|
||||||
|
.idea
|
||||||
|
*.iml
|
||||||
|
out
|
||||||
|
gen
|
||||||
|
### Windows template
|
||||||
|
# Windows thumbnail cache files
|
||||||
|
Thumbs.db
|
||||||
|
Thumbs.db:encryptable
|
||||||
|
ehthumbs.db
|
||||||
|
ehthumbs_vista.db
|
||||||
|
|
||||||
|
# Dump file
|
||||||
|
*.stackdump
|
||||||
|
|
||||||
|
# Folder config file
|
||||||
|
[Dd]esktop.ini
|
||||||
|
|
||||||
|
# Recycle Bin used on file shares
|
||||||
|
$RECYCLE.BIN/
|
||||||
|
|
||||||
|
# Windows Installer files
|
||||||
|
*.cab
|
||||||
|
*.msi
|
||||||
|
*.msix
|
||||||
|
*.msm
|
||||||
|
*.msp
|
||||||
|
|
||||||
|
# Windows shortcuts
|
||||||
|
*.lnk
|
||||||
|
|
||||||
|
### Syncthing template
|
||||||
|
# Syncthing caches
|
||||||
|
.stversions
|
||||||
|
|
||||||
|
### Python template
|
||||||
|
# Byte-compiled / optimized / DLL files
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
*$py.class
|
||||||
|
|
||||||
|
# C extensions
|
||||||
|
*.so
|
||||||
|
|
||||||
|
# Distribution / packaging
|
||||||
|
.Python
|
||||||
|
build/
|
||||||
|
develop-eggs/
|
||||||
|
dist/
|
||||||
|
downloads/
|
||||||
|
eggs/
|
||||||
|
.eggs/
|
||||||
|
lib/
|
||||||
|
lib64/
|
||||||
|
parts/
|
||||||
|
sdist/
|
||||||
|
var/
|
||||||
|
wheels/
|
||||||
|
share/python-wheels/
|
||||||
|
*.egg-info/
|
||||||
|
.installed.cfg
|
||||||
|
*.egg
|
||||||
|
MANIFEST
|
||||||
|
|
||||||
|
# PyInstaller
|
||||||
|
# Usually these files are written by a python script from a template
|
||||||
|
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||||
|
*.manifest
|
||||||
|
*.spec
|
||||||
|
|
||||||
|
# Installer logs
|
||||||
|
pip-log.txt
|
||||||
|
pip-delete-this-directory.txt
|
||||||
|
|
||||||
|
# Unit test / coverage reports
|
||||||
|
htmlcov/
|
||||||
|
.tox/
|
||||||
|
.nox/
|
||||||
|
.coverage
|
||||||
|
.coverage.*
|
||||||
|
.cache
|
||||||
|
nosetests.xml
|
||||||
|
coverage.xml
|
||||||
|
*.cover
|
||||||
|
*.py,cover
|
||||||
|
.hypothesis/
|
||||||
|
.pytest_cache/
|
||||||
|
cover/
|
||||||
|
|
||||||
|
# Translations
|
||||||
|
*.mo
|
||||||
|
*.pot
|
||||||
|
|
||||||
|
# Django stuff:
|
||||||
|
*.log
|
||||||
|
local_settings.py
|
||||||
|
db.sqlite3
|
||||||
|
db.sqlite3-journal
|
||||||
|
|
||||||
|
# Flask stuff:
|
||||||
|
instance/
|
||||||
|
.webassets-cache
|
||||||
|
|
||||||
|
# Scrapy stuff:
|
||||||
|
.scrapy
|
||||||
|
|
||||||
|
# Sphinx documentation
|
||||||
|
docs/_build/
|
||||||
|
|
||||||
|
# PyBuilder
|
||||||
|
.pybuilder/
|
||||||
|
target/
|
||||||
|
|
||||||
|
# Jupyter Notebook
|
||||||
|
.ipynb_checkpoints
|
||||||
|
|
||||||
|
# IPython
|
||||||
|
profile_default/
|
||||||
|
ipython_config.py
|
||||||
|
|
||||||
|
# pyenv
|
||||||
|
# For a library or package, you might want to ignore these files since the code is
|
||||||
|
# intended to run in multiple environments; otherwise, check them in:
|
||||||
|
# .python-version
|
||||||
|
|
||||||
|
# pipenv
|
||||||
|
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||||
|
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||||
|
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||||
|
# install all needed dependencies.
|
||||||
|
#Pipfile.lock
|
||||||
|
|
||||||
|
# poetry
|
||||||
|
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||||
|
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||||
|
# commonly ignored for libraries.
|
||||||
|
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||||
|
#poetry.lock
|
||||||
|
|
||||||
|
# pdm
|
||||||
|
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||||
|
#pdm.lock
|
||||||
|
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||||
|
# in version control.
|
||||||
|
# https://pdm.fming.dev/#use-with-ide
|
||||||
|
.pdm.toml
|
||||||
|
|
||||||
|
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||||
|
__pypackages__/
|
||||||
|
|
||||||
|
# Celery stuff
|
||||||
|
celerybeat-schedule
|
||||||
|
celerybeat.pid
|
||||||
|
|
||||||
|
# SageMath parsed files
|
||||||
|
*.sage.py
|
||||||
|
|
||||||
|
# Environments
|
||||||
|
.env
|
||||||
|
.venv
|
||||||
|
env/
|
||||||
|
venv/
|
||||||
|
ENV/
|
||||||
|
env.bak/
|
||||||
|
venv.bak/
|
||||||
|
|
||||||
|
# Spyder project settings
|
||||||
|
.spyderproject
|
||||||
|
.spyproject
|
||||||
|
|
||||||
|
# Rope project settings
|
||||||
|
.ropeproject
|
||||||
|
|
||||||
|
# mkdocs documentation
|
||||||
|
/site
|
||||||
|
|
||||||
|
# mypy
|
||||||
|
.mypy_cache/
|
||||||
|
.dmypy.json
|
||||||
|
dmypy.json
|
||||||
|
|
||||||
|
# Pyre type checker
|
||||||
|
.pyre/
|
||||||
|
|
||||||
|
# pytype static type analyzer
|
||||||
|
.pytype/
|
||||||
|
|
||||||
|
# Cython debug symbols
|
||||||
|
cython_debug/
|
||||||
|
|
||||||
|
# PyCharm
|
||||||
|
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||||
|
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||||
|
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||||
|
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||||
|
#.idea/
|
|
@ -0,0 +1,77 @@
|
||||||
|
#!/bin/python3
|
||||||
|
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
|
||||||
|
#
|
||||||
|
# Complete the 'arrayManipulation' function below.
|
||||||
|
#
|
||||||
|
# The function is expected to return a LONG_INTEGER.
|
||||||
|
# The function accepts following parameters:
|
||||||
|
# 1. INTEGER n
|
||||||
|
# 2. 2D_INTEGER_ARRAY queries
|
||||||
|
#
|
||||||
|
#Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array.
|
||||||
|
|
||||||
|
def arrayManipulation(n, queries):
|
||||||
|
# Write your code here
|
||||||
|
# create an array of zeros
|
||||||
|
arr = [0] * (n + 1)
|
||||||
|
sum = 0
|
||||||
|
max = 0
|
||||||
|
# iterate through queries
|
||||||
|
for i in range(len(queries)):
|
||||||
|
# get the start and end indices
|
||||||
|
start = queries[i][0]
|
||||||
|
end = queries[i][1]
|
||||||
|
# get the value to add
|
||||||
|
value = queries[i][2]
|
||||||
|
# add the value to the start index
|
||||||
|
arr[start] += value
|
||||||
|
# subtract the value from the end index + 1
|
||||||
|
if end + 1 <= n:
|
||||||
|
arr[end + 1] -= value
|
||||||
|
# iterate through the array
|
||||||
|
for i in range(1, len(arr)):
|
||||||
|
# add the value at the current index to the sum
|
||||||
|
sum += arr[i]
|
||||||
|
# if the sum is greater than the max, set the max to the sum
|
||||||
|
if sum > max:
|
||||||
|
max = sum
|
||||||
|
# return the max
|
||||||
|
return max
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
fptr = open(os.environ['OUTPUT_PATH'], 'w')
|
||||||
|
|
||||||
|
first_multiple_input = input().rstrip().split()
|
||||||
|
|
||||||
|
n = int(first_multiple_input[0])
|
||||||
|
|
||||||
|
m = int(first_multiple_input[1])
|
||||||
|
|
||||||
|
queries = []
|
||||||
|
|
||||||
|
for _ in range(m):
|
||||||
|
queries.append(list(map(int, input().rstrip().split())))
|
||||||
|
|
||||||
|
result = arrayManipulation(n, queries)
|
||||||
|
|
||||||
|
fptr.write(str(result) + '\n')
|
||||||
|
|
||||||
|
fptr.close()
|
||||||
|
|
||||||
|
|
||||||
|
# Sample Input
|
||||||
|
#
|
||||||
|
# 5 3
|
||||||
|
# 1 2 100
|
||||||
|
# 2 5 100
|
||||||
|
# 3 4 100
|
||||||
|
# Sample Output
|
||||||
|
#
|
||||||
|
# 200
|
|
@ -0,0 +1,59 @@
|
||||||
|
#!/bin/python3
|
||||||
|
|
||||||
|
class Stack:
|
||||||
|
def __init__(self):
|
||||||
|
self.top = -1
|
||||||
|
self.data = []
|
||||||
|
|
||||||
|
def push(self, value):
|
||||||
|
self.data.append(0)
|
||||||
|
self.top += 1
|
||||||
|
self.data[self.top] = value
|
||||||
|
|
||||||
|
def pop(self):
|
||||||
|
value = self.data[self.top]
|
||||||
|
del self.data[self.top]
|
||||||
|
self.top -= 1
|
||||||
|
return value
|
||||||
|
|
||||||
|
def isEmpty(self):
|
||||||
|
return self.top == -1
|
||||||
|
|
||||||
|
|
||||||
|
def enqueue(stack1, value):
|
||||||
|
stack1.push(value)
|
||||||
|
|
||||||
|
|
||||||
|
def dequeue(stack1, stack2):
|
||||||
|
if stack2.isEmpty():
|
||||||
|
while not stack1.isEmpty():
|
||||||
|
stack2.push(stack1.pop())
|
||||||
|
return stack2.pop()
|
||||||
|
|
||||||
|
|
||||||
|
def peek(stack1, stack2):
|
||||||
|
if stack2.isEmpty():
|
||||||
|
while not stack1.isEmpty():
|
||||||
|
stack2.push(stack1.pop())
|
||||||
|
return stack2.data[stack2.top]
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
stack1 = Stack()
|
||||||
|
stack2 = Stack()
|
||||||
|
|
||||||
|
# Get number of queries
|
||||||
|
q = int(input())
|
||||||
|
queries = []
|
||||||
|
for i in range(q):
|
||||||
|
queries.append(list(map(int, input().rstrip().split())))
|
||||||
|
query = queries[i][0]
|
||||||
|
# if the query is 1, enqueue
|
||||||
|
if query == 1:
|
||||||
|
enqueue(stack1, queries[i][1])
|
||||||
|
# if the query is 2, dequeue
|
||||||
|
elif query == 2:
|
||||||
|
dequeue(stack1, stack2)
|
||||||
|
# if the query is 3, print the top of the queue
|
||||||
|
elif query == 3:
|
||||||
|
print(peek(stack1, stack2))
|
|
@ -0,0 +1,40 @@
|
||||||
|
#!/bin/python3
|
||||||
|
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
|
||||||
|
#
|
||||||
|
# Complete the 'superDigit' function below.
|
||||||
|
#
|
||||||
|
# The function is expected to return an INTEGER.
|
||||||
|
# The function accepts following parameters:
|
||||||
|
# 1. STRING n
|
||||||
|
# 2. INTEGER k
|
||||||
|
#
|
||||||
|
|
||||||
|
def superDigit(n, k):
|
||||||
|
# Write your code here
|
||||||
|
if len(n) == 1:
|
||||||
|
return int(n)
|
||||||
|
else:
|
||||||
|
n = str(sum([int(i) for i in n]) * k)
|
||||||
|
return superDigit(n, 1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
fptr = open(os.environ['OUTPUT_PATH'], 'w')
|
||||||
|
|
||||||
|
first_multiple_input = input().rstrip().split()
|
||||||
|
|
||||||
|
n = first_multiple_input[0]
|
||||||
|
|
||||||
|
k = int(first_multiple_input[1])
|
||||||
|
|
||||||
|
result = superDigit(n, k)
|
||||||
|
|
||||||
|
fptr.write(str(result) + '\n')
|
||||||
|
|
||||||
|
fptr.close()
|
|
@ -0,0 +1,251 @@
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
|
||||||
|
|
||||||
|
class BST:
|
||||||
|
root = None
|
||||||
|
|
||||||
|
def put(self, key, val):
|
||||||
|
self.root = self.put2(self.root, key, val)
|
||||||
|
|
||||||
|
def put2(self, node, key, val):
|
||||||
|
if node is None:
|
||||||
|
# key is not in tree, create node and return node to parent
|
||||||
|
return Node(key, val)
|
||||||
|
if key < node.key:
|
||||||
|
# key is in left subtree
|
||||||
|
node.left = self.put2(node.left, key, val)
|
||||||
|
elif key > node.key:
|
||||||
|
# key is in right subtree
|
||||||
|
node.right = self.put2(node.right, key, val)
|
||||||
|
else:
|
||||||
|
node.val = val
|
||||||
|
return node
|
||||||
|
|
||||||
|
def createTree(self, a):
|
||||||
|
|
||||||
|
for x in a:
|
||||||
|
n = x.split(":")
|
||||||
|
self.put(n[0], n[1])
|
||||||
|
|
||||||
|
# Create a AVL Tree, you are allowed to create other helper functions
|
||||||
|
def createBalancedTree(self, a):
|
||||||
|
for x in a:
|
||||||
|
n = x.split(":")
|
||||||
|
self.insertAVL(n[0], n[1])
|
||||||
|
|
||||||
|
# preOrder Traversal, this should be a recursive function
|
||||||
|
def preOrder(self, node):
|
||||||
|
if node is None:
|
||||||
|
return []
|
||||||
|
return [node.key + ":" + node.val] + self.preOrder(node.left) + self.preOrder(node.right)
|
||||||
|
|
||||||
|
# inOrder Traversal, this should be a recursive function
|
||||||
|
def inOrder(self, node):
|
||||||
|
if node is None:
|
||||||
|
return []
|
||||||
|
return self.inOrder(node.left) + [node.key + ":" + node.val] + self.inOrder(node.right)
|
||||||
|
|
||||||
|
# postOrder Traversal, this should be a recursive function
|
||||||
|
def postOrder(self, node):
|
||||||
|
if node is None:
|
||||||
|
return []
|
||||||
|
return self.postOrder(node.left) + self.postOrder(node.right) + [node.key + ":" + node.val]
|
||||||
|
|
||||||
|
# given a key, obtain its value
|
||||||
|
def get(self, key):
|
||||||
|
return self.get2(self.root, key)
|
||||||
|
|
||||||
|
# given a key, find the node and obtain the depth, you are allowed to create other helper functions
|
||||||
|
def depth(self, key):
|
||||||
|
return self.depth2(self.root, key, 0)
|
||||||
|
|
||||||
|
# given a key, find the node and obtain the height, you are allowed to create other helper functions
|
||||||
|
def height(self, key):
|
||||||
|
return self.height2(self.root, key)
|
||||||
|
|
||||||
|
# given a key, find the node and obtain the size, you are allowed to create other helper functions
|
||||||
|
def size(self, key):
|
||||||
|
return self.size2(self.root, key)
|
||||||
|
|
||||||
|
# given a key, delete the node, you are allowed to create other helper functions
|
||||||
|
def delete(self, key):
|
||||||
|
self.root = self.delete2(self.root, key)
|
||||||
|
return True
|
||||||
|
|
||||||
|
def get2(self, root, key):
|
||||||
|
if root is None:
|
||||||
|
return None
|
||||||
|
if key < root.key:
|
||||||
|
return self.get2(root.left, key)
|
||||||
|
elif key > root.key:
|
||||||
|
return self.get2(root.right, key)
|
||||||
|
else:
|
||||||
|
return root.val
|
||||||
|
|
||||||
|
def size2(self, root, key):
|
||||||
|
if root is None:
|
||||||
|
return 0
|
||||||
|
if key < root.key:
|
||||||
|
return self.size2(root.left, key) + 1
|
||||||
|
elif key > root.key:
|
||||||
|
return self.size2(root.right, key) + 1
|
||||||
|
else:
|
||||||
|
return self.size2(root.left, key) + self.size2(root.right, key)
|
||||||
|
|
||||||
|
def depth2(self, root, key, param):
|
||||||
|
if root is None:
|
||||||
|
return 0
|
||||||
|
if key < root.key:
|
||||||
|
return self.depth2(root.left, key, param + 1)
|
||||||
|
elif key > root.key:
|
||||||
|
return self.depth2(root.right, key, param + 1)
|
||||||
|
else:
|
||||||
|
return param
|
||||||
|
|
||||||
|
def height2(self, current_node, key):
|
||||||
|
if current_node is None:
|
||||||
|
return -1
|
||||||
|
else:
|
||||||
|
return max(self.height2(current_node.left, key), self.height2(current_node.right, key)) + 1
|
||||||
|
|
||||||
|
def delete2(self, root, key):
|
||||||
|
if root is None:
|
||||||
|
return None
|
||||||
|
# Search for key to delete
|
||||||
|
if key < root.key:
|
||||||
|
root.left = self.delete2(root.left, key)
|
||||||
|
elif key > root.key:
|
||||||
|
root.right = self.delete2(root.right, key)
|
||||||
|
else:
|
||||||
|
# Found key
|
||||||
|
if root.right is None:
|
||||||
|
return root.left
|
||||||
|
if root.left is None:
|
||||||
|
return root.right
|
||||||
|
# Node has two children
|
||||||
|
temp = root
|
||||||
|
root = self.min(temp.right)
|
||||||
|
root.right = self.deleteMin(temp.right)
|
||||||
|
root.left = temp.left
|
||||||
|
return root
|
||||||
|
|
||||||
|
def deleteMin(self, node):
|
||||||
|
if node.left is None:
|
||||||
|
return node.right
|
||||||
|
node.left = self.deleteMin(node.left)
|
||||||
|
return node
|
||||||
|
|
||||||
|
def min(self, right):
|
||||||
|
if right.left is None:
|
||||||
|
return right
|
||||||
|
return self.min(right.left)
|
||||||
|
|
||||||
|
def getBalance(self, root):
|
||||||
|
if not root:
|
||||||
|
return 0
|
||||||
|
return self.getAVLHeight(root.left) - self.getAVLHeight(root.right)
|
||||||
|
|
||||||
|
def leftRotate(self, z):
|
||||||
|
y = z.right
|
||||||
|
T2 = y.left
|
||||||
|
y.left = z
|
||||||
|
z.right = T2
|
||||||
|
return y
|
||||||
|
|
||||||
|
def rightRotate(self, z):
|
||||||
|
y = z.left
|
||||||
|
T3 = y.right
|
||||||
|
y.right = z
|
||||||
|
z.left = T3
|
||||||
|
return y
|
||||||
|
|
||||||
|
def getAVLHeight(self, root):
|
||||||
|
if not root:
|
||||||
|
return -1
|
||||||
|
return 1 + max(self.getAVLHeight(root.left), self.getAVLHeight(root.right))
|
||||||
|
|
||||||
|
def insertAVL(self, key, val):
|
||||||
|
self.root = self.insertAVL2(self.root, key, val)
|
||||||
|
|
||||||
|
def insertAVL2(self, root, key, val):
|
||||||
|
if not root:
|
||||||
|
return Node(key, val)
|
||||||
|
elif key < root.key:
|
||||||
|
root.left = self.insertAVL2(root.left, key, val)
|
||||||
|
else:
|
||||||
|
root.right = self.insertAVL2(root.right, key, val)
|
||||||
|
balance = self.getBalance(root)
|
||||||
|
if balance > 1 and key < root.left.key:
|
||||||
|
return self.rightRotate(root)
|
||||||
|
if balance < -1 and key > root.right.key:
|
||||||
|
return self.leftRotate(root)
|
||||||
|
if balance > 1 and key > root.left.key:
|
||||||
|
root.left = self.leftRotate(root.left)
|
||||||
|
return self.rightRotate(root)
|
||||||
|
if balance < -1 and key < root.right.key:
|
||||||
|
root.right = self.rightRotate(root.right)
|
||||||
|
return self.leftRotate(root)
|
||||||
|
return root
|
||||||
|
|
||||||
|
class Node:
|
||||||
|
left = None
|
||||||
|
right = None
|
||||||
|
key = 0
|
||||||
|
val = 0
|
||||||
|
|
||||||
|
def __init__(self, key, val):
|
||||||
|
self.key = key
|
||||||
|
self.val = val
|
||||||
|
|
||||||
|
|
||||||
|
array = input("Enter a list of key:value pairs separated by commas:\n")
|
||||||
|
array = [str(x) for x in array.split(",")]
|
||||||
|
|
||||||
|
bst = BST()
|
||||||
|
bst.createTree(array)
|
||||||
|
|
||||||
|
###testcase 0 (get())
|
||||||
|
for i in range(2):
|
||||||
|
key1 = input("Input key for get() method:\n")
|
||||||
|
if key1 != '-':
|
||||||
|
print("The value of", key1, "is", bst.get(key1))
|
||||||
|
|
||||||
|
###testcase 1 (size(),depth(),height())
|
||||||
|
key1 = input("Input key for size() method:\n")
|
||||||
|
if key1 != '-':
|
||||||
|
print("The size of", key1, "is", bst.size(key1))
|
||||||
|
|
||||||
|
key1 = input("Input key for depth() method:\n")
|
||||||
|
if key1 != '-':
|
||||||
|
print("The depth of", key1, "is", bst.depth(key1))
|
||||||
|
|
||||||
|
key1 = input("Input key for height() method:\n")
|
||||||
|
if key1 != '-':
|
||||||
|
print("The height of", key1, "is", bst.height(key1))
|
||||||
|
|
||||||
|
print()
|
||||||
|
|
||||||
|
###testcase 2 (preOrder(), inOrder(), postOrder())
|
||||||
|
print("The preOrder traversal is", bst.preOrder(bst.root))
|
||||||
|
print("The inOrder traversal is", bst.inOrder(bst.root))
|
||||||
|
print("The postOrder traversal is", bst.postOrder(bst.root))
|
||||||
|
print()
|
||||||
|
|
||||||
|
###testcase 3 delete()
|
||||||
|
for i in range(2):
|
||||||
|
key1 = input("Input key for delete() method:\n")
|
||||||
|
if key1 != '-':
|
||||||
|
print("Deleting", key1, "is", bst.delete(key1))
|
||||||
|
print("The preOrder traversal is", bst.preOrder(bst.root))
|
||||||
|
print("The inOrder traversal is", bst.inOrder(bst.root))
|
||||||
|
print("The postOrder traversal is", bst.postOrder(bst.root))
|
||||||
|
|
||||||
|
###testcase 4 createbalancedTree()
|
||||||
|
key1 = input("Test balanced Tree? \n")
|
||||||
|
if key1 == 'Y':
|
||||||
|
bst = BST()
|
||||||
|
bst.createBalancedTree(array)
|
||||||
|
print("The preOrder traversal is", bst.preOrder(bst.root))
|
||||||
|
print("The inOrder traversal is", bst.inOrder(bst.root))
|
||||||
|
print("The postOrder traversal is", bst.postOrder(bst.root))
|
|
@ -0,0 +1,80 @@
|
||||||
|
class Node:
|
||||||
|
def __init__(self, info):
|
||||||
|
self.info = info
|
||||||
|
self.left = None
|
||||||
|
self.right = None
|
||||||
|
self.level = None
|
||||||
|
|
||||||
|
def __str__(self):
|
||||||
|
return str(self.info)
|
||||||
|
|
||||||
|
|
||||||
|
class BinarySearchTree:
|
||||||
|
def __init__(self):
|
||||||
|
self.root = None
|
||||||
|
|
||||||
|
def create(self, val):
|
||||||
|
if self.root == None:
|
||||||
|
self.root = Node(val)
|
||||||
|
else:
|
||||||
|
current = self.root
|
||||||
|
|
||||||
|
while True:
|
||||||
|
if val < current.info:
|
||||||
|
if current.left:
|
||||||
|
current = current.left
|
||||||
|
else:
|
||||||
|
current.left = Node(val)
|
||||||
|
break
|
||||||
|
elif val > current.info:
|
||||||
|
if current.right:
|
||||||
|
current = current.right
|
||||||
|
else:
|
||||||
|
current.right = Node(val)
|
||||||
|
break
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
|
||||||
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
|
||||||
|
'''
|
||||||
|
class Node:
|
||||||
|
def __init__(self,info):
|
||||||
|
self.info = info
|
||||||
|
self.left = None
|
||||||
|
self.right = None
|
||||||
|
|
||||||
|
|
||||||
|
// this is a node of the tree , which contains info as data, left , right
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def lca(root, v1, v2):
|
||||||
|
# Enter your code here
|
||||||
|
if root is None:
|
||||||
|
return None
|
||||||
|
if root.info == v1 or root.info == v2:
|
||||||
|
return root
|
||||||
|
left = lca(root.left, v1, v2)
|
||||||
|
right = lca(root.right, v1, v2)
|
||||||
|
if left and right:
|
||||||
|
return root
|
||||||
|
if left is None:
|
||||||
|
return right
|
||||||
|
else:
|
||||||
|
return left
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
tree = BinarySearchTree()
|
||||||
|
t = int(input())
|
||||||
|
|
||||||
|
arr = list(map(int, input().split()))
|
||||||
|
|
||||||
|
for i in range(t):
|
||||||
|
tree.create(arr[i])
|
||||||
|
|
||||||
|
v = list(map(int, input().split()))
|
||||||
|
|
||||||
|
ans = lca(tree.root, v[0], v[1])
|
||||||
|
print(ans.info)
|
|
@ -0,0 +1,20 @@
|
||||||
|
""" Node is defined as
|
||||||
|
class node:
|
||||||
|
def __init__(self, data):
|
||||||
|
self.data = data
|
||||||
|
self.left = None
|
||||||
|
self.right = None
|
||||||
|
"""
|
||||||
|
def check_binary_search_tree_(root):
|
||||||
|
# Use the inorder traversal to check if the tree is a binary search tree
|
||||||
|
sequence = inorder_trav(root)
|
||||||
|
for i in range(len(sequence) - 1):
|
||||||
|
if sequence[i] >= sequence[i + 1]:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def inorder_trav(root):
|
||||||
|
if root is None:
|
||||||
|
return []
|
||||||
|
return inorder_trav(root.left) + [root.data] + inorder_trav(root.right)
|
|
@ -0,0 +1,20 @@
|
||||||
|
def largest(arr):
|
||||||
|
biggest = arr[0]
|
||||||
|
i = 0
|
||||||
|
for index, item in enumerate(arr):
|
||||||
|
if item > biggest:
|
||||||
|
biggest = item
|
||||||
|
i = index
|
||||||
|
return i
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||||
|
print("Question 1: Write an algorithm that returns the index of the first occurrence of the largest element in an "
|
||||||
|
"array")
|
||||||
|
print("index: " + str(largest(arr)))
|
||||||
|
print("value: " + str(arr[largest(arr)]))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
|
@ -0,0 +1,15 @@
|
||||||
|
def reverse(arr):
|
||||||
|
arr_tmp = []
|
||||||
|
for i in range(len(arr)):
|
||||||
|
arr_tmp.append(arr[len(arr) - 1 - i])
|
||||||
|
return arr_tmp
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||||
|
print("Question 2: Write an algorithm that reverses the array")
|
||||||
|
print(reverse(arr))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
|
@ -0,0 +1,23 @@
|
||||||
|
def smallesttwo(arr):
|
||||||
|
small = arr[0]
|
||||||
|
small2 = arr[0]
|
||||||
|
for item in arr:
|
||||||
|
if item < small:
|
||||||
|
small = item
|
||||||
|
for item in arr:
|
||||||
|
if item < small2 and item != small:
|
||||||
|
small2 = item
|
||||||
|
|
||||||
|
return small, small2
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print("Question 3: Write an algorithm that output the smallest and the second smallest values in the array s[0],"
|
||||||
|
"…s[n-1]. Assume that n>1 and the values in the array are distinct.")
|
||||||
|
arr = [9, 2, 4, 5, 6, 7, 8, 3, 10]
|
||||||
|
small, small2 = smallesttwo(arr)
|
||||||
|
print("Smallest: " + str(small))
|
||||||
|
print("Second Smallest: " + str(small2))
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
|
@ -0,0 +1,17 @@
|
||||||
|
# Question 5
|
||||||
|
An algorithm for finding the maximum element of an array is in the following
|
||||||
|
```python
|
||||||
|
def arrayMax(a,n):
|
||||||
|
currentMax = a[0]
|
||||||
|
for i in range(1,n):
|
||||||
|
if a[i] > currentMax:
|
||||||
|
currentMax = a[i]
|
||||||
|
return currentMax
|
||||||
|
```
|
||||||
|
|
||||||
|
Determine the number of times that the statement "currentMax = a[i]" will be
|
||||||
|
executed in the best case and in the worst case.
|
||||||
|
|
||||||
|
The best case is when the array is already sorted in ascending order. In this case, the statement "currentMax = a[i]" will be executed only once, when i = 0.
|
||||||
|
|
||||||
|
The worst case is when the array is sorted in descending order. In this case, the statement "currentMax = a[i]" will be executed n-1 times, when i = 1, 2, ..., n-1.
|
|
@ -0,0 +1,33 @@
|
||||||
|
class Student:
|
||||||
|
def __init__(self, name, student_number, examDict):
|
||||||
|
self.name = name
|
||||||
|
self.student_number = student_number
|
||||||
|
self.examDict = examDict
|
||||||
|
|
||||||
|
def getBestExamScore(self):
|
||||||
|
return max(self.examDict, key=self.examDict.get)
|
||||||
|
|
||||||
|
def getFaileModules(self):
|
||||||
|
listOfFailedModules = []
|
||||||
|
for key, value in self.examDict.items():
|
||||||
|
if value < 40:
|
||||||
|
listOfFailedModules.append(key)
|
||||||
|
|
||||||
|
print(listOfFailedModules)
|
||||||
|
# return [key for key, value in self.examDict.items() if value < 40]
|
||||||
|
|
||||||
|
def addScore(self, subjectCode, examScore):
|
||||||
|
self.examDict[subjectCode] = examScore
|
||||||
|
|
||||||
|
def printScore(self):
|
||||||
|
print(self.name)
|
||||||
|
print(self.examDict)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
examDict = {"ICT1008": 96, "ICT1002": 78, "ICT1005": 30}
|
||||||
|
student = Student("Cristal", "123456", examDict)
|
||||||
|
student.addScore("ICT1010", 70)
|
||||||
|
student.printScore()
|
||||||
|
print(student.getBestExamScore())
|
||||||
|
student.getFaileModules()
|
|
@ -0,0 +1,24 @@
|
||||||
|
def main():
|
||||||
|
print("Question 4: Given an array s[0],…,s[n-1] such that n > 1 and s[i] ≤ s[i+1] for all i. Write an "
|
||||||
|
"algorithm that inserts an input value x into the array so that s[i] ≤ s[i+1] for all i.")
|
||||||
|
|
||||||
|
arr = []
|
||||||
|
i = int(input("Enter size of array: "))
|
||||||
|
|
||||||
|
while i > 0:
|
||||||
|
x = int(input("Enter a number: "))
|
||||||
|
if arr:
|
||||||
|
if x >= arr[len(arr) - 1]:
|
||||||
|
arr.append(x)
|
||||||
|
i -= 1
|
||||||
|
else:
|
||||||
|
print("Number must be greater than or equal to the last number in the array")
|
||||||
|
|
||||||
|
else:
|
||||||
|
arr.append(x)
|
||||||
|
|
||||||
|
print(arr)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
Binary file not shown.
|
@ -0,0 +1,26 @@
|
||||||
|
# question 4
|
||||||
|
def orderInsert(a, value):
|
||||||
|
# remove pass
|
||||||
|
left = 0
|
||||||
|
right = len(a) - 1
|
||||||
|
|
||||||
|
while left <= right:
|
||||||
|
mid = (left + right) >> 1
|
||||||
|
if a[mid] == value:
|
||||||
|
a.insert(mid, value)
|
||||||
|
return
|
||||||
|
elif a[mid] < value:
|
||||||
|
left = mid + 1
|
||||||
|
else:
|
||||||
|
right = mid - 1
|
||||||
|
|
||||||
|
a.insert(left, value)
|
||||||
|
|
||||||
|
|
||||||
|
array = input("Enter a list of numbers in increasing order separated by commas:\n")
|
||||||
|
array = [int(x) for x in array.split(",")]
|
||||||
|
|
||||||
|
number = input("Enter a number to be inserted into the array:\n")
|
||||||
|
|
||||||
|
orderInsert(array, int(number))
|
||||||
|
print(array)
|
|
@ -0,0 +1,51 @@
|
||||||
|
class Stack:
|
||||||
|
def __init__(self):
|
||||||
|
self.top = -1
|
||||||
|
# this stack is implemented with Python list (array)
|
||||||
|
self.data = []
|
||||||
|
|
||||||
|
def push(self, value):
|
||||||
|
# increment the size of data using append()
|
||||||
|
self.data.append(0)
|
||||||
|
self.top += 1
|
||||||
|
self.data[self.top] = value
|
||||||
|
pass
|
||||||
|
|
||||||
|
def pop(self):
|
||||||
|
value = self.data[self.top]
|
||||||
|
# delete the top value using del
|
||||||
|
del self.data[self.top]
|
||||||
|
self.top -= 1
|
||||||
|
return value
|
||||||
|
|
||||||
|
def isEmpty(self):
|
||||||
|
return self.top == -1
|
||||||
|
|
||||||
|
def peek(self):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def printStack(self):
|
||||||
|
print(self.data)
|
||||||
|
|
||||||
|
def invert(self):
|
||||||
|
# remove pass and add your code here
|
||||||
|
|
||||||
|
tmpStack = Stack()
|
||||||
|
while not self.isEmpty():
|
||||||
|
tmpStack.push(self.pop())
|
||||||
|
self.data = tmpStack.data
|
||||||
|
self.top = tmpStack.top
|
||||||
|
|
||||||
|
|
||||||
|
array = input("Enter a list of numbers separated by commas:\n")
|
||||||
|
array = [int(x) for x in array.split(",")]
|
||||||
|
|
||||||
|
s = Stack()
|
||||||
|
for n in array:
|
||||||
|
s.push(n)
|
||||||
|
|
||||||
|
s.printStack()
|
||||||
|
s.invert()
|
||||||
|
s.printStack()
|
||||||
|
s.invert()
|
||||||
|
s.printStack()
|
|
@ -0,0 +1,141 @@
|
||||||
|
class SinglyListNode:
|
||||||
|
def __init__(self, data):
|
||||||
|
self.data = data
|
||||||
|
self.next = None
|
||||||
|
|
||||||
|
|
||||||
|
class SinglyLinkedList:
|
||||||
|
def __init__(self):
|
||||||
|
self.head = None
|
||||||
|
|
||||||
|
# return the value of the node at index
|
||||||
|
|
||||||
|
def search(self, index):
|
||||||
|
temp = self.head
|
||||||
|
prev = None
|
||||||
|
counter = 0
|
||||||
|
while temp is not None and counter < index:
|
||||||
|
prev = temp
|
||||||
|
temp = temp.next
|
||||||
|
counter += 1
|
||||||
|
|
||||||
|
if temp is None:
|
||||||
|
print('search error: invalid index')
|
||||||
|
else:
|
||||||
|
return temp
|
||||||
|
|
||||||
|
def insertAtHead(self, node):
|
||||||
|
if self.head is None:
|
||||||
|
self.head = node
|
||||||
|
else:
|
||||||
|
node.next = self.head
|
||||||
|
self.head = node
|
||||||
|
|
||||||
|
def delete(self, value):
|
||||||
|
prev = None
|
||||||
|
temp = self.head
|
||||||
|
|
||||||
|
while temp is not None and temp.data != value:
|
||||||
|
prev = temp
|
||||||
|
temp = temp.next
|
||||||
|
|
||||||
|
# node to be deleted is head
|
||||||
|
if temp == self.head:
|
||||||
|
self.deleteAtHead()
|
||||||
|
|
||||||
|
# Value found
|
||||||
|
elif temp != None:
|
||||||
|
prev.next = temp.next
|
||||||
|
del temp
|
||||||
|
# Value not found
|
||||||
|
else:
|
||||||
|
print('Value ', value, ' cannot be found')
|
||||||
|
|
||||||
|
# delete the node at index
|
||||||
|
def deleteAt(self, index):
|
||||||
|
temp = self.head
|
||||||
|
prev = None
|
||||||
|
counter = 0
|
||||||
|
while temp is not None and counter < index:
|
||||||
|
prev = temp
|
||||||
|
temp = temp.next
|
||||||
|
counter += 1
|
||||||
|
|
||||||
|
if temp is None:
|
||||||
|
print('search error: invalid index')
|
||||||
|
else:
|
||||||
|
if prev is None:
|
||||||
|
self.head = temp.next
|
||||||
|
else:
|
||||||
|
prev.next = temp.next
|
||||||
|
del temp
|
||||||
|
|
||||||
|
def deleteAtHead(self):
|
||||||
|
temp = self.head
|
||||||
|
self.head = self.head.next
|
||||||
|
del temp
|
||||||
|
|
||||||
|
def printList(self):
|
||||||
|
output = "Current list content: [ "
|
||||||
|
temp = self.head
|
||||||
|
while temp is not None:
|
||||||
|
output += str(temp.data) + " "
|
||||||
|
temp = temp.next
|
||||||
|
output += "]"
|
||||||
|
print(output)
|
||||||
|
|
||||||
|
# return the number of elements in the queue
|
||||||
|
def size(self):
|
||||||
|
temp = self.head
|
||||||
|
size = 0
|
||||||
|
while temp is not None:
|
||||||
|
size += 1
|
||||||
|
temp = temp.next
|
||||||
|
return size
|
||||||
|
|
||||||
|
|
||||||
|
class Queue:
|
||||||
|
def __init__(self):
|
||||||
|
# You must implement this Queue with a SinglyLinkedList
|
||||||
|
self.q = SinglyLinkedList()
|
||||||
|
|
||||||
|
def enqueue(self, value):
|
||||||
|
# remove pass and add your code here
|
||||||
|
self.q.insertAtHead(SinglyListNode(value))
|
||||||
|
|
||||||
|
def printQueue(self):
|
||||||
|
self.q.printList()
|
||||||
|
|
||||||
|
def dequeue(self):
|
||||||
|
self.q.deleteAt(self.q.size() - 1)
|
||||||
|
|
||||||
|
def isEmpty(self):
|
||||||
|
return self.q.size() == 0
|
||||||
|
|
||||||
|
def peek(self):
|
||||||
|
return self.q.search(self.q.size() - 1).data
|
||||||
|
|
||||||
|
|
||||||
|
Q = Queue()
|
||||||
|
|
||||||
|
array = input("Enter a list of command separated by commas:\n")
|
||||||
|
array = [x for x in array.split(",")]
|
||||||
|
|
||||||
|
for cmd in array:
|
||||||
|
if cmd.startswith("I"):
|
||||||
|
print("Checking if queue is empty")
|
||||||
|
print(Q.isEmpty())
|
||||||
|
elif cmd.startswith("E"):
|
||||||
|
c, v = cmd.split()
|
||||||
|
Q.enqueue(int(v))
|
||||||
|
print("After enqueuing", int(v))
|
||||||
|
Q.printQueue()
|
||||||
|
elif cmd.startswith("P"):
|
||||||
|
print("Peeking at queue")
|
||||||
|
print(Q.peek())
|
||||||
|
elif cmd.startswith("D"):
|
||||||
|
Q.dequeue()
|
||||||
|
print("After dequeing")
|
||||||
|
Q.printQueue()
|
||||||
|
else:
|
||||||
|
print("Command not recognized!")
|
|
@ -0,0 +1,167 @@
|
||||||
|
# Enter your code here. Read input from STDIN. Print output to STDOUT
|
||||||
|
class SinglyListNode:
|
||||||
|
def __init__(self, data):
|
||||||
|
self.data = data
|
||||||
|
self.next = None
|
||||||
|
|
||||||
|
|
||||||
|
class SinglyLinkedList:
|
||||||
|
def __init__(self):
|
||||||
|
self.head = None
|
||||||
|
self.data = []
|
||||||
|
|
||||||
|
def search(self, value):
|
||||||
|
temp = self.head
|
||||||
|
prev = None
|
||||||
|
counter = 0
|
||||||
|
while temp is not None and counter < value:
|
||||||
|
prev = temp
|
||||||
|
temp = temp.next
|
||||||
|
counter += 1
|
||||||
|
|
||||||
|
if temp is None:
|
||||||
|
print('Error: invalid index')
|
||||||
|
else:
|
||||||
|
return temp
|
||||||
|
|
||||||
|
def insert(self, node, index):
|
||||||
|
if index == 0:
|
||||||
|
self.insertAtHead(node)
|
||||||
|
else:
|
||||||
|
temp = self.search(index)
|
||||||
|
if temp is not None:
|
||||||
|
node.next = temp.next
|
||||||
|
temp.next = node
|
||||||
|
|
||||||
|
def insertAtHead(self, node):
|
||||||
|
if self.head is None:
|
||||||
|
self.head = node
|
||||||
|
else:
|
||||||
|
node.next = self.head
|
||||||
|
self.head = node
|
||||||
|
|
||||||
|
def delete(self, value):
|
||||||
|
prev = None
|
||||||
|
temp = self.head
|
||||||
|
|
||||||
|
while temp != None and temp.data != value:
|
||||||
|
prev = temp
|
||||||
|
temp = temp.next
|
||||||
|
|
||||||
|
# node to be deleted is head
|
||||||
|
if temp == self.head:
|
||||||
|
self.deleteAtHead()
|
||||||
|
|
||||||
|
# Value found
|
||||||
|
elif temp != None:
|
||||||
|
prev.next = temp.next
|
||||||
|
del temp
|
||||||
|
# Value not found
|
||||||
|
else:
|
||||||
|
print('Value ', value, ' cannot be found')
|
||||||
|
|
||||||
|
# delete the node at index
|
||||||
|
def deleteAt(self, index):
|
||||||
|
temp = self.head
|
||||||
|
prev = None
|
||||||
|
counter = 0
|
||||||
|
while temp is not None and counter < index:
|
||||||
|
prev = temp
|
||||||
|
temp = temp.next
|
||||||
|
counter += 1
|
||||||
|
|
||||||
|
if temp is None:
|
||||||
|
print('search error: invalid index')
|
||||||
|
else:
|
||||||
|
if prev is None:
|
||||||
|
self.head = temp.next
|
||||||
|
else:
|
||||||
|
prev.next = temp.next
|
||||||
|
del temp
|
||||||
|
|
||||||
|
def deleteAtHead(self):
|
||||||
|
temp = self.head
|
||||||
|
self.head = self.head.next
|
||||||
|
del temp
|
||||||
|
|
||||||
|
def printList(self):
|
||||||
|
output = "[ "
|
||||||
|
temp = self.head
|
||||||
|
while temp is not None:
|
||||||
|
output += str(temp.data) + " "
|
||||||
|
temp = temp.next
|
||||||
|
output += "]"
|
||||||
|
print(output)
|
||||||
|
|
||||||
|
# return the number of elements in the queue
|
||||||
|
def size(self):
|
||||||
|
temp = self.head
|
||||||
|
size = 0
|
||||||
|
while temp is not None:
|
||||||
|
size += 1
|
||||||
|
temp = temp.next
|
||||||
|
return size
|
||||||
|
|
||||||
|
def reverse(self):
|
||||||
|
prev = None
|
||||||
|
current = self.head
|
||||||
|
while current is not None:
|
||||||
|
next = current.next
|
||||||
|
current.next = prev
|
||||||
|
prev = current
|
||||||
|
current = next
|
||||||
|
self.head = prev
|
||||||
|
|
||||||
|
|
||||||
|
def mergesort(list1, list2):
|
||||||
|
merged_list = SinglyLinkedList()
|
||||||
|
|
||||||
|
while list1.head is not None and list2.head is not None:
|
||||||
|
if int(list1.head.data) < int(list2.head.data):
|
||||||
|
merged_list.insertAtHead(SinglyListNode(list1.head.data))
|
||||||
|
list1.deleteAtHead()
|
||||||
|
else:
|
||||||
|
merged_list.insertAtHead(SinglyListNode(list2.head.data))
|
||||||
|
list2.deleteAtHead()
|
||||||
|
while list1.head is not None:
|
||||||
|
merged_list.insertAtHead(SinglyListNode(list1.head.data))
|
||||||
|
list1.deleteAtHead()
|
||||||
|
|
||||||
|
while list2.head is not None:
|
||||||
|
merged_list.insertAtHead(SinglyListNode(list2.head.data))
|
||||||
|
list2.deleteAtHead()
|
||||||
|
|
||||||
|
merged_list.reverse()
|
||||||
|
print("Content of merged list")
|
||||||
|
merged_list.printList()
|
||||||
|
|
||||||
|
|
||||||
|
def reverse(array):
|
||||||
|
reversed_array = []
|
||||||
|
for i in range(len(array)):
|
||||||
|
reversed_array.append(array[len(array) - 1 - i])
|
||||||
|
return reversed_array
|
||||||
|
|
||||||
|
|
||||||
|
array1 = input("Enter a list of numbers in descending order for list 1 separated by commas:")
|
||||||
|
array1 = [x for x in array1.split(",")]
|
||||||
|
array1 = reverse(array1)
|
||||||
|
list1 = SinglyLinkedList()
|
||||||
|
list2 = SinglyLinkedList()
|
||||||
|
|
||||||
|
for n in array1:
|
||||||
|
list1.insertAtHead(SinglyListNode(n))
|
||||||
|
|
||||||
|
array2 = input("\nEnter a list of numbers in descending order for list 2 separated by commas:")
|
||||||
|
array2 = [x for x in array2.split(",")]
|
||||||
|
array2 = reverse(array2)
|
||||||
|
|
||||||
|
for n in array2:
|
||||||
|
list2.insertAtHead(SinglyListNode(n))
|
||||||
|
|
||||||
|
print("\nContent of list 1")
|
||||||
|
list1.printList()
|
||||||
|
|
||||||
|
print("Content of list 2")
|
||||||
|
list2.printList()
|
||||||
|
mergesort(list1, list2)
|
|
@ -0,0 +1,47 @@
|
||||||
|
class Stack:
|
||||||
|
def __init__(self):
|
||||||
|
self.top = -1
|
||||||
|
# this stack is implemented with Python list (array)
|
||||||
|
self.data = []
|
||||||
|
|
||||||
|
def push(self, value):
|
||||||
|
# increment the size of data using append()
|
||||||
|
self.data.append(0)
|
||||||
|
self.top += 1
|
||||||
|
self.data[self.top] = value
|
||||||
|
|
||||||
|
def pop(self):
|
||||||
|
value = self.data[self.top]
|
||||||
|
# delete the top value using del
|
||||||
|
del self.data[self.top]
|
||||||
|
self.top -= 1
|
||||||
|
return value
|
||||||
|
|
||||||
|
def isEmpty(self):
|
||||||
|
return (self.top == -1)
|
||||||
|
|
||||||
|
def printStack(self):
|
||||||
|
print(self.data)
|
||||||
|
|
||||||
|
|
||||||
|
def checkBrace(s):
|
||||||
|
stack = Stack()
|
||||||
|
for i in s:
|
||||||
|
if i == "(" or i== "[" or i == "{":
|
||||||
|
stack.push(i)
|
||||||
|
elif i == ")" or i == "]" or i == "}":
|
||||||
|
if stack.isEmpty():
|
||||||
|
return False
|
||||||
|
else:
|
||||||
|
stack.pop()
|
||||||
|
if stack.isEmpty():
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
array = input("Enter a string to check:\n")
|
||||||
|
|
||||||
|
if checkBrace(array):
|
||||||
|
print("The string", array, "is balanced")
|
||||||
|
else:
|
||||||
|
print("The string", array, "is not balanced")
|
|
@ -0,0 +1,39 @@
|
||||||
|
# recursive function to add first n term of the series 1+1/2 - 1/3+1/4-1/5
|
||||||
|
|
||||||
|
def sum(n):
|
||||||
|
if n == 1: # base case
|
||||||
|
return 1
|
||||||
|
else:
|
||||||
|
if n % 2 == 0: # if n is even
|
||||||
|
return 1 / n + sum(n - 1) # add 1/n
|
||||||
|
else:
|
||||||
|
return -1 / n + sum(n - 1) # subtract 1/n
|
||||||
|
|
||||||
|
|
||||||
|
# Test cases
|
||||||
|
# assert sum(1) == 1, "sum(1) should be 1, but returned " + str(sum(1))
|
||||||
|
# assert sum(2) == 1.5, "sum(2) should be 1.5, but returned " + str(sum(2))
|
||||||
|
# assert sum(3) == (1 + 1/2 - 1/3), "sum(3) should be 1.1666666666666667, but returned " + str(sum(3))
|
||||||
|
# assert sum(4) == (1 + 1/2 - 1/3 + 1/4), "sum(4) should be 1.4166666666666667, but returned " + str(sum(4))
|
||||||
|
# assert sum(5) == (1 + 1/2 - 1/3 + 1/4 - 1/5), "sum(5) should be 1.2833333333333332, but returned " + str(sum(5))
|
||||||
|
#
|
||||||
|
# print("All tests passed!")
|
||||||
|
|
||||||
|
|
||||||
|
def sumNTerm(n):
|
||||||
|
# remove pass and insert your code here
|
||||||
|
# for the purpose of this exercise you
|
||||||
|
# should be calling sumNTerm() with a smaller
|
||||||
|
# value of n inside this function
|
||||||
|
if n == 1.0:
|
||||||
|
return 1.0
|
||||||
|
else:
|
||||||
|
if n % 2 == 0:
|
||||||
|
return 1 / n + sumNTerm(n - 1)
|
||||||
|
else:
|
||||||
|
return -1 / n + sumNTerm(n - 1)
|
||||||
|
|
||||||
|
|
||||||
|
n = int(input("Enter the number of terms to sum:\n"))
|
||||||
|
|
||||||
|
print("Sum of first", n, "terms =", sumNTerm(n))
|
|
@ -0,0 +1,35 @@
|
||||||
|
# def GCD(n, m):
|
||||||
|
# if m <= n and n % m == 0: # base case
|
||||||
|
# return m
|
||||||
|
# elif n < m: # if n < m, swap n and m
|
||||||
|
# return GCD(m, n)
|
||||||
|
# else:
|
||||||
|
# return GCD(m, n % m) # recursive call to find gcd with n % m
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def GCD(n,m):
|
||||||
|
# remove pass and insert your code here
|
||||||
|
# for hte purpose of this exercise you should
|
||||||
|
# call the function GCD() with a smaller value of
|
||||||
|
# the parameters appropriately.
|
||||||
|
if m <= n and n % m == 0:
|
||||||
|
return m
|
||||||
|
elif n < m:
|
||||||
|
return GCD(m, n)
|
||||||
|
else:
|
||||||
|
return GCD(m, n % m)
|
||||||
|
|
||||||
|
n1 = int(input("Enter the first number:\n"))
|
||||||
|
n2 = int(input("Enter the second number:\n"))
|
||||||
|
|
||||||
|
print("The GCD of", n1, "and", n2, "is", GCD(n1,n2))
|
||||||
|
|
||||||
|
# Test cases
|
||||||
|
assert GCD(12, 8) == 4, "GCD(12, 8) should be 4, but returned " + str(GCD(12, 8))
|
||||||
|
assert GCD(8, 12) == 4, "GCD(8, 12) should be 4, but returned " + str(GCD(8, 12))
|
||||||
|
assert GCD(12, 9) == 3, "GCD(12, 9) should be 3, but returned " + str(GCD(12, 9))
|
||||||
|
assert GCD(9, 12) == 3, "GCD(9, 12) should be 3, but returned " + str(GCD(9, 12))
|
||||||
|
|
||||||
|
print("All tests passed!")
|
|
@ -0,0 +1,30 @@
|
||||||
|
def hanoi(n, source, target, spare):
|
||||||
|
if n == 1:
|
||||||
|
print("Move disk", n, "from", source, "to", target)
|
||||||
|
else:
|
||||||
|
hanoi(n - 1, source, spare, target)
|
||||||
|
print("Move disk", n, "from", source, "to", target)
|
||||||
|
hanoi(n - 1, spare, target, source)
|
||||||
|
|
||||||
|
|
||||||
|
hanoi(3, "A", "B", "C")
|
||||||
|
|
||||||
|
|
||||||
|
def moveTower(height, fromPole, toPole, withPole):
|
||||||
|
# add code here
|
||||||
|
# call moveDisk in your function call.
|
||||||
|
if height == 1:
|
||||||
|
moveDisk(fromPole, toPole)
|
||||||
|
|
||||||
|
else:
|
||||||
|
moveTower(height - 1, fromPole, withPole, toPole)
|
||||||
|
moveDisk(fromPole, toPole)
|
||||||
|
moveTower(height - 1, withPole, toPole, fromPole)
|
||||||
|
|
||||||
|
|
||||||
|
def moveDisk(fp, tp):
|
||||||
|
print("moving disk from", fp, "to", tp)
|
||||||
|
|
||||||
|
|
||||||
|
disks = int(input("Enter the number of disks:\n"))
|
||||||
|
moveTower(disks, "A", "B", "C")
|
|
@ -0,0 +1,49 @@
|
||||||
|
#! /bin/python
|
||||||
|
|
||||||
|
|
||||||
|
# this function checks if a queen can be placed in location (col,row)
|
||||||
|
def isValid(col, row, chessBoard):
|
||||||
|
# check if there is a queen in the same row
|
||||||
|
for i in range(col):
|
||||||
|
if chessBoard[row][i] == 1:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Check if there is a quen in the same column
|
||||||
|
for i in range(row):
|
||||||
|
if chessBoard[i][col] == 1:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# check if there is a queen in the same diagonal
|
||||||
|
for i in range(8):
|
||||||
|
for j in range(8):
|
||||||
|
if (i + j == col + row) or (i - j == col - row):
|
||||||
|
if chessBoard[j][i] == 1:
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
# initialize chessboard
|
||||||
|
N = 8
|
||||||
|
chessBoard = []
|
||||||
|
for i in range(N):
|
||||||
|
chessBoard.append([])
|
||||||
|
for j in range(N):
|
||||||
|
chessBoard[i].append(0)
|
||||||
|
|
||||||
|
# place a queen in the upper left corner of the board
|
||||||
|
chessBoard[1][1] = 1
|
||||||
|
chessBoard[0][4] = 1
|
||||||
|
chessBoard[2][6] = 1
|
||||||
|
|
||||||
|
columnIndex = int(input("Enter a column index:\n"))
|
||||||
|
rowIndex = int(input("Enter a row index:\n"))
|
||||||
|
|
||||||
|
|
||||||
|
print(
|
||||||
|
"Placing a queen at column",
|
||||||
|
columnIndex,
|
||||||
|
"row",
|
||||||
|
rowIndex,
|
||||||
|
":",
|
||||||
|
isValid(columnIndex, rowIndex, chessBoard),
|
||||||
|
)
|
|
@ -0,0 +1,86 @@
|
||||||
|
#! /bin/python
|
||||||
|
|
||||||
|
map = []
|
||||||
|
countryColor = []
|
||||||
|
colorCode = ["Red", "Green", "Blue", "Yellow"]
|
||||||
|
|
||||||
|
|
||||||
|
# This function initailize the 2-dimensional map array
|
||||||
|
def createMap():
|
||||||
|
global map
|
||||||
|
mapString = (
|
||||||
|
"0,1,1,1,0,0,0\n"
|
||||||
|
"1,0,0,1,1,1,0\n"
|
||||||
|
"1,0,0,1,0,0,1\n"
|
||||||
|
"1,1,1,0,1,0,1\n"
|
||||||
|
"0,1,0,1,0,1,1\n"
|
||||||
|
"0,1,0,0,1,0,0\n"
|
||||||
|
"0,0,1,1,1,0,0"
|
||||||
|
)
|
||||||
|
|
||||||
|
for r in mapString.split("\n"):
|
||||||
|
map.append([int(x) for x in r.split(",")])
|
||||||
|
|
||||||
|
|
||||||
|
# This function initialize the color of each country to 0 = no color
|
||||||
|
def initializeColor():
|
||||||
|
global map
|
||||||
|
N = len(map)
|
||||||
|
for i in range(N):
|
||||||
|
countryColor.append(0)
|
||||||
|
|
||||||
|
|
||||||
|
# print the solution in the format required
|
||||||
|
def printSolution():
|
||||||
|
global colorCode
|
||||||
|
|
||||||
|
output = "Country\n"
|
||||||
|
for i in range(len(countryColor)):
|
||||||
|
output += str(i) + "\t"
|
||||||
|
output += "\n"
|
||||||
|
for i in range(len(countryColor)):
|
||||||
|
output += colorCode[countryColor[i] - 1] + "\t"
|
||||||
|
output += "\n"
|
||||||
|
print(output)
|
||||||
|
|
||||||
|
# This function tries to recursively color a country
|
||||||
|
# Here the parameter country is the index to the list of country from 0...N-1
|
||||||
|
# The skeleton of the program has been provided to you
|
||||||
|
# Remove the passes and fill in the missing codes for this function
|
||||||
|
global countryColor
|
||||||
|
|
||||||
|
|
||||||
|
def color(country):
|
||||||
|
global map
|
||||||
|
N = len(map)
|
||||||
|
|
||||||
|
# if country = number of countries to color
|
||||||
|
# print solution and exit
|
||||||
|
if country == N:
|
||||||
|
printSolution()
|
||||||
|
return
|
||||||
|
|
||||||
|
availableColor = set([1, 2, 3, 4])
|
||||||
|
# remove the color of any neighbour of country i from the set availableColor
|
||||||
|
for i in range(N):
|
||||||
|
if map[country][i] == 1:
|
||||||
|
if countryColor[i] in availableColor:
|
||||||
|
availableColor.remove(countryColor[i])
|
||||||
|
|
||||||
|
# for each remaining color in the set availableColor
|
||||||
|
# color country i with the color and then recursively color the next country
|
||||||
|
for colors in availableColor:
|
||||||
|
countryColor[country] = colors
|
||||||
|
color(country + 1)
|
||||||
|
countryColor[country] = 0
|
||||||
|
|
||||||
|
# reset the color of this country to none before backtracking
|
||||||
|
countryColor[country] = 0
|
||||||
|
|
||||||
|
|
||||||
|
# read the map array
|
||||||
|
createMap()
|
||||||
|
# set all countries to no color
|
||||||
|
initializeColor()
|
||||||
|
# first try to color country 0
|
||||||
|
color(0)
|
|
@ -0,0 +1,44 @@
|
||||||
|
count={}
|
||||||
|
|
||||||
|
# swap elements at index i and j or array a
|
||||||
|
def swap(a,i,j):
|
||||||
|
global count
|
||||||
|
a[i],a[j]=a[j],a[i]
|
||||||
|
count[a[i]]=count[a[i]]+1
|
||||||
|
count[a[j]]=count[a[j]]+1
|
||||||
|
|
||||||
|
# remove pass and implement insertion sort
|
||||||
|
# that sorts an input array a using the swap
|
||||||
|
# function defined above to swap two elements
|
||||||
|
# of an array. The swap function will
|
||||||
|
# automatically keep track of the number of
|
||||||
|
# swap for each item
|
||||||
|
def insertionSort(a):
|
||||||
|
for i in range(1, len(a)):
|
||||||
|
|
||||||
|
currentVal = a[i]
|
||||||
|
position = i
|
||||||
|
|
||||||
|
while position > 0 and a[position-1] > currentVal:
|
||||||
|
swap(a,position,position-1)
|
||||||
|
position = position-1
|
||||||
|
|
||||||
|
print(a)
|
||||||
|
a[position] = currentVal
|
||||||
|
|
||||||
|
|
||||||
|
# get user input
|
||||||
|
array = input("Enter a list of string to sort separated by commas:\n")
|
||||||
|
array = [str(x) for x in array.split(",")]
|
||||||
|
|
||||||
|
# set up the dictionary to track counts
|
||||||
|
for x in array:
|
||||||
|
count[x]=0
|
||||||
|
|
||||||
|
print(array)
|
||||||
|
insertionSort(array)
|
||||||
|
print("Number of swap for each item:",count)
|
||||||
|
total = 0
|
||||||
|
for i in count.keys():
|
||||||
|
total = total+count[i]
|
||||||
|
print("Average number of swap for each item:", round((total*1.0)/len(count.keys()),1))
|
|
@ -0,0 +1,41 @@
|
||||||
|
count = {}
|
||||||
|
|
||||||
|
|
||||||
|
# swap elements at index i and j or array a
|
||||||
|
def swap(a, i, j):
|
||||||
|
global count
|
||||||
|
a[i], a[j] = a[j], a[i]
|
||||||
|
|
||||||
|
count[a[i]] = count[a[i]] + 1
|
||||||
|
count[a[j]] = count[a[j]] + 1
|
||||||
|
|
||||||
|
|
||||||
|
# remove pass and implement selection sort
|
||||||
|
# use the swap function defined above to
|
||||||
|
# swap two elements of an array. The swap
|
||||||
|
# function will automatically keep track of
|
||||||
|
# the number of swap for each item
|
||||||
|
def selectionSort(a):
|
||||||
|
for j in range(len(a)):
|
||||||
|
imin = j
|
||||||
|
for i in range(j+1, len(a)):
|
||||||
|
if a[i] < a[imin]:
|
||||||
|
imin = i
|
||||||
|
if imin != j:
|
||||||
|
swap(a, j, imin)
|
||||||
|
|
||||||
|
|
||||||
|
# get user input
|
||||||
|
array = input("Enter a list of string to sort separated by commas:\n")
|
||||||
|
array = [str(x) for x in array.split(",")]
|
||||||
|
|
||||||
|
# set up the dictionary to track counts
|
||||||
|
for x in array:
|
||||||
|
count[x] = 0
|
||||||
|
|
||||||
|
selectionSort(array)
|
||||||
|
print("Number of swap for each item:", count)
|
||||||
|
total = 0
|
||||||
|
for i in count.keys():
|
||||||
|
total = total + count[i]
|
||||||
|
print("Average number of swap for each item:", (total * 1.0) / len(count.keys()))
|
|
@ -0,0 +1,33 @@
|
||||||
|
import random
|
||||||
|
|
||||||
|
random.seed(1)
|
||||||
|
dataSize = int(input("Enter the size of the list:\n"))
|
||||||
|
data = [random.randint(1,dataSize) for i in range(dataSize)]
|
||||||
|
data.sort()
|
||||||
|
|
||||||
|
# iterative version of binary search
|
||||||
|
def binarySearchIterative(arr,low,high,value):
|
||||||
|
while low <= high:
|
||||||
|
mid = (low + high) >> 1
|
||||||
|
if arr[mid] == value:
|
||||||
|
return mid
|
||||||
|
elif value < arr[mid]:
|
||||||
|
high = mid - 1
|
||||||
|
else:
|
||||||
|
low = mid + 1
|
||||||
|
return -1
|
||||||
|
|
||||||
|
#recursive version of binary search
|
||||||
|
def binarySearchRecursive(arr,low,high,value):
|
||||||
|
if low > high:
|
||||||
|
return -1
|
||||||
|
mid = (low + high) >> 1
|
||||||
|
if arr[mid] == value:
|
||||||
|
return mid
|
||||||
|
elif value < arr[mid]:
|
||||||
|
return binarySearchRecursive(arr,low,mid-1,value)
|
||||||
|
else:
|
||||||
|
return binarySearchRecursive(arr,mid+1,high,value)
|
||||||
|
|
||||||
|
print("Iterative: 9132 is at index ", binarySearchIterative(data,0,len(data)-1,9132))
|
||||||
|
print("Recursive: 9132 is at index ", binarySearchRecursive(data,0,len(data)-1,9132))
|
|
@ -0,0 +1,48 @@
|
||||||
|
compare = 0
|
||||||
|
|
||||||
|
|
||||||
|
class Node:
|
||||||
|
key = None
|
||||||
|
value = None
|
||||||
|
left = None
|
||||||
|
right = None
|
||||||
|
|
||||||
|
def __init__(self, k, v):
|
||||||
|
self.key = k
|
||||||
|
self.value = v
|
||||||
|
|
||||||
|
def insert(self, k, v):
|
||||||
|
global compare
|
||||||
|
if self.key == k:
|
||||||
|
compare = compare + 1
|
||||||
|
self.v = v
|
||||||
|
return
|
||||||
|
elif k < self.key:
|
||||||
|
compare = compare + 1
|
||||||
|
# remove pass and add your code here
|
||||||
|
# if left child is none, add the node as the left child
|
||||||
|
# else call the left child to insert the node
|
||||||
|
if self.left is None:
|
||||||
|
self.left = Node(k, v)
|
||||||
|
else:
|
||||||
|
self.left.insert(k, v)
|
||||||
|
|
||||||
|
else:
|
||||||
|
compare = compare + 1
|
||||||
|
# remove pass and add your code here
|
||||||
|
# if right child is none, add the node as the right child
|
||||||
|
# else call the right child to insert the node
|
||||||
|
if self.right is None:
|
||||||
|
self.right = Node(k, v)
|
||||||
|
else:
|
||||||
|
self.right.insert(k, v)
|
||||||
|
|
||||||
|
|
||||||
|
input = input("Enter a list of letters to insert into the binary tree separated by commas:\n")
|
||||||
|
input = input.split(",")
|
||||||
|
|
||||||
|
root = Node(input[0], 1)
|
||||||
|
for i in range(1, len(input)):
|
||||||
|
root.insert(input[i], 2)
|
||||||
|
|
||||||
|
print("Number of compares to create the BST =", compare)
|
|
@ -0,0 +1,112 @@
|
||||||
|
# Class describing a node of tree
|
||||||
|
class Node:
|
||||||
|
def __init__(self, v):
|
||||||
|
self.left = None
|
||||||
|
self.right = None
|
||||||
|
self.data = v
|
||||||
|
|
||||||
|
def insert(self, v):
|
||||||
|
if self.data:
|
||||||
|
if v < self.data:
|
||||||
|
if self.left is None:
|
||||||
|
self.left = Node(v)
|
||||||
|
else:
|
||||||
|
self.left.insert(v)
|
||||||
|
elif v > self.data:
|
||||||
|
if self.right is None:
|
||||||
|
self.right = Node(v)
|
||||||
|
else:
|
||||||
|
self.right.insert(v)
|
||||||
|
else:
|
||||||
|
self.data = v
|
||||||
|
|
||||||
|
def printTree(self):
|
||||||
|
if self.left:
|
||||||
|
self.left.printTree()
|
||||||
|
print(chr(self.data), end=" ")
|
||||||
|
if self.right:
|
||||||
|
self.right.printTree()
|
||||||
|
|
||||||
|
# Inorder Traversal
|
||||||
|
def printInorder(root):
|
||||||
|
if root:
|
||||||
|
# Traverse left subtree
|
||||||
|
printInorder(root.left)
|
||||||
|
|
||||||
|
# Visit node
|
||||||
|
print(chr(root.data), end=" ")
|
||||||
|
|
||||||
|
# Traverse right subtree
|
||||||
|
printInorder(root.right)
|
||||||
|
|
||||||
|
|
||||||
|
# Preorder Traversal
|
||||||
|
def printPostOrder(node):
|
||||||
|
if node is None:
|
||||||
|
return
|
||||||
|
|
||||||
|
# Traverse left subtree
|
||||||
|
printPostOrder(node.left)
|
||||||
|
|
||||||
|
# Traverse right subtree
|
||||||
|
printPostOrder(node.right)
|
||||||
|
|
||||||
|
# Visit Node
|
||||||
|
print(chr(node.data), end=" ")
|
||||||
|
|
||||||
|
|
||||||
|
# Preorder Traversal
|
||||||
|
def printPreOrder(node):
|
||||||
|
if node is None:
|
||||||
|
return
|
||||||
|
# Visit Node
|
||||||
|
print(chr(node.data), end=" ")
|
||||||
|
|
||||||
|
# Traverse left subtree
|
||||||
|
printPreOrder(node.left)
|
||||||
|
|
||||||
|
# Traverse right subtree
|
||||||
|
printPreOrder(node.right)
|
||||||
|
|
||||||
|
|
||||||
|
# Driver code
|
||||||
|
if __name__ == "__main__":
|
||||||
|
# Build the tree
|
||||||
|
root = Node(ord('E'))
|
||||||
|
#root.left = Node(ord('A'))
|
||||||
|
#root.right = Node(ord('S'))
|
||||||
|
#root.right.right = Node(ord('Y'))
|
||||||
|
#root.right.right.left = Node(ord('U'))
|
||||||
|
#root.right.right.left.left = Node(ord('S'))
|
||||||
|
#root.right.right.left.left.right = Node(ord('T'))
|
||||||
|
#root.right.left = Node(ord('Q'))
|
||||||
|
#root.right.left.left = Node(ord('E'))
|
||||||
|
#root.right.left.left.right = Node(ord('I'))
|
||||||
|
#root.right.left.left.right.right = Node(ord('O'))
|
||||||
|
#root.right.left.left.right.right.left = Node(ord('N'))
|
||||||
|
|
||||||
|
# Insert EASYQUESTION
|
||||||
|
root.insert(ord('A'))
|
||||||
|
root.insert(ord('S'))
|
||||||
|
root.insert(ord('Y'))
|
||||||
|
root.insert(ord('Q'))
|
||||||
|
root.insert(ord('U'))
|
||||||
|
root.insert(ord('E'))
|
||||||
|
root.insert(ord('I'))
|
||||||
|
root.insert(ord('O'))
|
||||||
|
root.insert(ord('N'))
|
||||||
|
|
||||||
|
# Print the tree
|
||||||
|
print("Tree:")
|
||||||
|
root.printTree()
|
||||||
|
|
||||||
|
|
||||||
|
# Function call
|
||||||
|
print("Inorder Traversal:", end=" ")
|
||||||
|
printInorder(root)
|
||||||
|
print("\nPreorder Traversal:", end=" ")
|
||||||
|
printPreOrder(root)
|
||||||
|
print("\nPostorder Traversal:", end=" ")
|
||||||
|
printPostOrder(root)
|
||||||
|
|
||||||
|
# This code is contributed by ajaymakvana.
|
|
@ -0,0 +1,45 @@
|
||||||
|
def iterativeBinarySearch(array, value):
|
||||||
|
left = 0
|
||||||
|
right = len(array)
|
||||||
|
|
||||||
|
while left <= right:
|
||||||
|
mid = (left + right) >> 1
|
||||||
|
if array[mid] == value:
|
||||||
|
return mid
|
||||||
|
elif array[mid] < value:
|
||||||
|
left = mid + 1
|
||||||
|
else:
|
||||||
|
right = mid - 1
|
||||||
|
return -1
|
||||||
|
|
||||||
|
def binarySearchWithForLoop(array, value):
|
||||||
|
left = 0
|
||||||
|
right = len(array)
|
||||||
|
|
||||||
|
for i in range(len(array)):
|
||||||
|
mid = (left + right) >> 1
|
||||||
|
if array[mid] == value:
|
||||||
|
return mid
|
||||||
|
elif array[mid] < value:
|
||||||
|
left = mid + 1
|
||||||
|
else:
|
||||||
|
right = mid - 1
|
||||||
|
return -1
|
||||||
|
|
||||||
|
def recursiveBinarySearch(array, value, left, right):
|
||||||
|
if left > right:
|
||||||
|
return -1
|
||||||
|
|
||||||
|
mid = (left + right) >> 1
|
||||||
|
if array[mid] == value:
|
||||||
|
return mid
|
||||||
|
elif array[mid] < value:
|
||||||
|
return recursiveBinarySearch(array, value, mid + 1, right)
|
||||||
|
else:
|
||||||
|
return recursiveBinarySearch(array, value, left, mid - 1)
|
||||||
|
|
||||||
|
|
||||||
|
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||||
|
print(iterativeBinarySearch(array, 10))
|
||||||
|
print(recursiveBinarySearch(array, 4, 0, len(array) - 1))
|
||||||
|
print(binarySearchWithForLoop(array, 5))
|
|
@ -0,0 +1,27 @@
|
||||||
|
def insertionSort(a):
|
||||||
|
for i in range(1, len(a)):
|
||||||
|
currentValue = a[i]
|
||||||
|
position = i
|
||||||
|
|
||||||
|
while position > 0 and a[position - 1] > currentValue:
|
||||||
|
a[position] = a[position - 1]
|
||||||
|
position -= 1
|
||||||
|
a[position] = currentValue
|
||||||
|
|
||||||
|
return a
|
||||||
|
|
||||||
|
|
||||||
|
array = [4, 2, 5, 9, 1, 3, 6, 8, 7]
|
||||||
|
insertionSort(array)
|
||||||
|
print(array)
|
||||||
|
|
||||||
|
# Output
|
||||||
|
# [2, 4, 5, 9, 1, 3, 6, 8, 7]
|
||||||
|
# [2, 4, 5, 9, 1, 3, 6, 8, 7]
|
||||||
|
# [2, 4, 5, 9, 1, 3, 6, 8, 7]
|
||||||
|
# [1, 2, 4, 5, 9, 3, 6, 8, 7]
|
||||||
|
# [1, 2, 3, 4, 5, 9, 6, 8, 7]
|
||||||
|
# [1, 2, 3, 4, 5, 6, 9, 8, 7]
|
||||||
|
# [1, 2, 3, 4, 5, 6, 8, 9, 7]
|
||||||
|
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
|
||||||
|
|
|
@ -0,0 +1,41 @@
|
||||||
|
def merge(array1, array2):
|
||||||
|
array3 = []
|
||||||
|
size1 = len(array1)
|
||||||
|
size2 = len(array2)
|
||||||
|
|
||||||
|
index1 = index2 = 0
|
||||||
|
|
||||||
|
while index1 < size1 and index2 < size2:
|
||||||
|
if array1[index1] < array2[index2]:
|
||||||
|
array3.append(array1[index1])
|
||||||
|
index1 += 1
|
||||||
|
else:
|
||||||
|
array3.append(array2[index2])
|
||||||
|
index2 += 1
|
||||||
|
|
||||||
|
for i in range(index1, size1):
|
||||||
|
array3.append(array1[i])
|
||||||
|
|
||||||
|
for i in range(index2, size2):
|
||||||
|
array3.append(array2[i])
|
||||||
|
|
||||||
|
return array3
|
||||||
|
|
||||||
|
|
||||||
|
def mergeSort(array):
|
||||||
|
size = len(array)
|
||||||
|
|
||||||
|
if size <= 1:
|
||||||
|
return array
|
||||||
|
|
||||||
|
mid = size // 2
|
||||||
|
|
||||||
|
left = mergeSort(array[:mid])
|
||||||
|
right = mergeSort(array[mid:])
|
||||||
|
|
||||||
|
#return merge(left, right)
|
||||||
|
return merge1(left, right)
|
||||||
|
|
||||||
|
|
||||||
|
array = [4, 2, 5, 9, 1, 3, 6, 8, 7]
|
||||||
|
print(mergeSort(array))
|
|
@ -0,0 +1,11 @@
|
||||||
|
def bubbleSort(a):
|
||||||
|
for i in range(len(a)):
|
||||||
|
# -i because the last i elements are already sorted
|
||||||
|
# -1 because we compare j and j+1
|
||||||
|
for j in range(len(a) - i - 1):
|
||||||
|
if a[j] > a[j + 1]:
|
||||||
|
a[j], a[j + 1] = a[j + 1], a[j]
|
||||||
|
|
||||||
|
array = [3,4,2,9,5,1,6]
|
||||||
|
bubbleSort(array)
|
||||||
|
print(array)
|
|
@ -0,0 +1,24 @@
|
||||||
|
def partition(a):
|
||||||
|
pivot = a[0]
|
||||||
|
pivotIndex = 0
|
||||||
|
|
||||||
|
for i in range(1, len(a)):
|
||||||
|
if a[i] < pivot:
|
||||||
|
a[i], a[pivotIndex + 1] = a[pivotIndex + 1], a[i]
|
||||||
|
pivotIndex += 1
|
||||||
|
|
||||||
|
a[0], a[pivotIndex] = a[pivotIndex], a[0]
|
||||||
|
return pivotIndex
|
||||||
|
|
||||||
|
|
||||||
|
def quickSort(a):
|
||||||
|
if len(a) <= 1:
|
||||||
|
return a
|
||||||
|
pivotIndex = partition(a)
|
||||||
|
left = quickSort(a[:pivotIndex])
|
||||||
|
right = quickSort(a[pivotIndex + 1:])
|
||||||
|
return left + [a[pivotIndex]] + right
|
||||||
|
|
||||||
|
|
||||||
|
array = [4, 2, 5, 9, 1, 3, 6, 8, 7]
|
||||||
|
print(quickSort(array))
|
|
@ -0,0 +1,27 @@
|
||||||
|
def partition(a):
|
||||||
|
pivot = a[0]
|
||||||
|
index = 0
|
||||||
|
|
||||||
|
for i in range(1, len(a)):
|
||||||
|
if a[i] > pivot:
|
||||||
|
a[i], a[index + 1] = a[index + 1], a[i]
|
||||||
|
index += 1
|
||||||
|
|
||||||
|
a[0], a[index] = a[index], a[0]
|
||||||
|
return index
|
||||||
|
|
||||||
|
|
||||||
|
def quickSort(a):
|
||||||
|
if len(a) <= 1:
|
||||||
|
return a
|
||||||
|
|
||||||
|
pivot = partition(a)
|
||||||
|
|
||||||
|
left = quickSort(a[:pivot])
|
||||||
|
right = quickSort(a[pivot + 1:])
|
||||||
|
|
||||||
|
return left + [a[pivot]] + right
|
||||||
|
|
||||||
|
|
||||||
|
array = [4, 2, 5, 9, 1, 3, 6, 8, 7]
|
||||||
|
print(quickSort(array))
|
|
@ -0,0 +1,29 @@
|
||||||
|
|
||||||
|
def selSort(a):
|
||||||
|
for i in range(len(a)):
|
||||||
|
minIndex = i
|
||||||
|
for j in range(i + 1, len(a)):
|
||||||
|
if a[j] < a[minIndex]:
|
||||||
|
minIndex = j
|
||||||
|
a[i], a[minIndex] = a[minIndex], a[i]
|
||||||
|
|
||||||
|
return a
|
||||||
|
|
||||||
|
def selSortMax(a):
|
||||||
|
# For each element in the array starting from the end
|
||||||
|
for i in range(len(a) - 1, 0, -1):
|
||||||
|
maxIndex = i
|
||||||
|
# Search for max element in the array from the beginning
|
||||||
|
for j in range(i):
|
||||||
|
if a[j] > a[maxIndex]:
|
||||||
|
maxIndex = j
|
||||||
|
# Swap the max element with the last element
|
||||||
|
a[i], a[maxIndex] = a[maxIndex], a[i]
|
||||||
|
|
||||||
|
return a
|
||||||
|
|
||||||
|
array = [4, 2, 5, 9, 1, 3, 6, 8, 7]
|
||||||
|
selSort(array)
|
||||||
|
selSortMax(array)
|
||||||
|
print(array)
|
||||||
|
|
|
@ -0,0 +1,12 @@
|
||||||
|
|
||||||
|
# Checking if a value is an even number or not
|
||||||
|
|
||||||
|
|
||||||
|
def checkEven(n):
|
||||||
|
return n & 1 == 0
|
||||||
|
|
||||||
|
|
||||||
|
assert checkEven(2) == True, "checkEven(2) should be True, but returned " + str(checkEven(2))
|
||||||
|
assert checkEven(3) == False, "checkEven(3) should be False, but returned " + str(checkEven(3))
|
||||||
|
|
||||||
|
print("All tests passed!")
|
|
@ -0,0 +1,77 @@
|
||||||
|
class node:
|
||||||
|
def __init__(self, data):
|
||||||
|
self.data = data
|
||||||
|
self.next = None
|
||||||
|
self.prev = None
|
||||||
|
|
||||||
|
class doublyLinkedList:
|
||||||
|
def __init__(self):
|
||||||
|
self.head = None
|
||||||
|
self.prev = None
|
||||||
|
|
||||||
|
def insert(self, node):
|
||||||
|
if self.head is None:
|
||||||
|
self.head = self.prev = node
|
||||||
|
else:
|
||||||
|
self.head.prev = node
|
||||||
|
node.next = self.head
|
||||||
|
self.head = node
|
||||||
|
|
||||||
|
|
||||||
|
def delete(self, value):
|
||||||
|
temp = self.head
|
||||||
|
while temp is not None and temp.data is not value:
|
||||||
|
temp = temp.next
|
||||||
|
if temp is None:
|
||||||
|
print("Error, value not found")
|
||||||
|
else:
|
||||||
|
if temp is self.head:
|
||||||
|
self.head = self.head.next
|
||||||
|
elif temp is self.tail:
|
||||||
|
self.tail = self.tail.prev
|
||||||
|
else:
|
||||||
|
temp.prev.next = temp.next
|
||||||
|
temp.next.prev = temp.prev
|
||||||
|
|
||||||
|
def peek(self):
|
||||||
|
return self.head.data
|
||||||
|
|
||||||
|
def search(self, value):
|
||||||
|
temp = self.head
|
||||||
|
counter = 0
|
||||||
|
while temp is not None and temp.data is not value:
|
||||||
|
temp = temp.next
|
||||||
|
counter += 1
|
||||||
|
if temp is None:
|
||||||
|
print("Error: Unable to search")
|
||||||
|
else:
|
||||||
|
return counter
|
||||||
|
|
||||||
|
def printList(self):
|
||||||
|
temp = self.head
|
||||||
|
while temp is not None:
|
||||||
|
if temp.next is not None:
|
||||||
|
print(temp.data, end=" -> ")
|
||||||
|
else:
|
||||||
|
print(temp.data)
|
||||||
|
temp = temp.next
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
dll = doublyLinkedList()
|
||||||
|
dll.insert(node(5))
|
||||||
|
dll.insert(node(6))
|
||||||
|
dll.insert(node(7))
|
||||||
|
|
||||||
|
dll.printList()
|
||||||
|
# Asserts
|
||||||
|
assert(dll.peek() == 7), f"Top of Doubly Linked List not 7, got:{dll.peek()}"
|
||||||
|
assert(dll.search(5) == 2), f"Index of 5 not 2, got:{dll.search(5)}"
|
||||||
|
assert(dll.search(6) == 1), f"Index of 6 not 1, got:{dll.search(6)}"
|
||||||
|
assert(dll.search(7) == 0), f"Index of 7 not 0, got:{dll.search(7)}"
|
||||||
|
|
||||||
|
print("All tests passed")
|
||||||
|
dll.printList()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
|
@ -0,0 +1,46 @@
|
||||||
|
class queue:
|
||||||
|
def __init__(self):
|
||||||
|
self.data = []
|
||||||
|
self.rear = -1
|
||||||
|
|
||||||
|
def enqueue(self, value):
|
||||||
|
self.data.append(value)
|
||||||
|
self.rear += 1
|
||||||
|
|
||||||
|
def dequeue(self):
|
||||||
|
value = self.data[0] # Dequeue from the front
|
||||||
|
del self.data[0]
|
||||||
|
self.rear -= 1
|
||||||
|
return value
|
||||||
|
|
||||||
|
def peek(self):
|
||||||
|
if self.rear != -1 and self.data is not None:
|
||||||
|
return self.data[self.rear]
|
||||||
|
else:
|
||||||
|
return "Empty Queue"
|
||||||
|
|
||||||
|
def printQueue(self):
|
||||||
|
return(self.data)
|
||||||
|
|
||||||
|
def main():
|
||||||
|
q1 = queue()
|
||||||
|
|
||||||
|
print(q1.printQueue())
|
||||||
|
q1.enqueue(10)
|
||||||
|
assert(q1.peek() == 10), f"Top of queue not 10, got:{q1.peek()}"
|
||||||
|
q1.enqueue(11)
|
||||||
|
assert(q1.peek() == 11), f"Top of queue not 11, got:{q1.peek()}"
|
||||||
|
|
||||||
|
print(q1.printQueue())
|
||||||
|
|
||||||
|
q1.dequeue()
|
||||||
|
assert(q1.peek() == 11), f"Top of queue not 11, got:{q1.peek()}"
|
||||||
|
print(q1.printQueue())
|
||||||
|
q1.dequeue()
|
||||||
|
assert(q1.peek() == "Empty Queue"), f"Top of queue not Empty Queue, got:{q1.peek()}"
|
||||||
|
|
||||||
|
print("No errors found")
|
||||||
|
print(q1.printQueue())
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
|
@ -0,0 +1,13 @@
|
||||||
|
def reverse():
|
||||||
|
ch = raw_input()
|
||||||
|
if ch != 'end':
|
||||||
|
reverse()
|
||||||
|
print ch,
|
||||||
|
|
||||||
|
reverse()
|
||||||
|
|
||||||
|
# input:
|
||||||
|
# a b c d end
|
||||||
|
|
||||||
|
# output:
|
||||||
|
# end d c b a
|
|
@ -0,0 +1,131 @@
|
||||||
|
class SinglyListNode:
|
||||||
|
def __init__(self, data):
|
||||||
|
self.data = data
|
||||||
|
self.next = None
|
||||||
|
|
||||||
|
|
||||||
|
class SinglyLinkedList:
|
||||||
|
def __init__(self):
|
||||||
|
self.head = None
|
||||||
|
|
||||||
|
def insertAtHead(self, node):
|
||||||
|
if self.head is None:
|
||||||
|
self.head = node
|
||||||
|
else:
|
||||||
|
node.next = self.head
|
||||||
|
self.head = node
|
||||||
|
|
||||||
|
def search(self, index):
|
||||||
|
temp = self.head
|
||||||
|
prev = None
|
||||||
|
counter = 0
|
||||||
|
while temp is not None and counter < index:
|
||||||
|
prev = temp
|
||||||
|
temp = temp.next
|
||||||
|
counter += 1
|
||||||
|
if temp is None:
|
||||||
|
print("Error: invalid index")
|
||||||
|
else:
|
||||||
|
return temp
|
||||||
|
|
||||||
|
def searchValue(self, value):
|
||||||
|
temp = self.head
|
||||||
|
#prev = None
|
||||||
|
counter = 0
|
||||||
|
|
||||||
|
while temp is not None and temp.data != value:
|
||||||
|
#prev = temp
|
||||||
|
temp = temp.next
|
||||||
|
counter += 1
|
||||||
|
|
||||||
|
if temp is None:
|
||||||
|
print("Not Found")
|
||||||
|
elif temp.data == value:
|
||||||
|
return counter
|
||||||
|
def delete(self, value):
|
||||||
|
temp = self.head
|
||||||
|
prev = None
|
||||||
|
while temp is not None and temp.data is not value:
|
||||||
|
prev = temp
|
||||||
|
temp = temp.next
|
||||||
|
|
||||||
|
if temp is None:
|
||||||
|
print("Error: value not found")
|
||||||
|
elif temp.next == self.head:
|
||||||
|
self.deleteAtHead()
|
||||||
|
else:
|
||||||
|
prev.next = temp.next
|
||||||
|
del temp
|
||||||
|
|
||||||
|
def deleteAtHead(self):
|
||||||
|
temp = self.head
|
||||||
|
self.head = self.head.next
|
||||||
|
del temp
|
||||||
|
|
||||||
|
def peek(self):
|
||||||
|
return self.head.data
|
||||||
|
|
||||||
|
def isEmpty(self):
|
||||||
|
return self.head is None
|
||||||
|
|
||||||
|
def printList(self):
|
||||||
|
temp = self.head
|
||||||
|
while temp is not None:
|
||||||
|
if temp.next is None:
|
||||||
|
print(temp.data)
|
||||||
|
else:
|
||||||
|
print(temp.data, end=" -> ")
|
||||||
|
temp = temp.next
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
linkL = SinglyLinkedList()
|
||||||
|
|
||||||
|
# Nodes
|
||||||
|
aNode = SinglyListNode(10)
|
||||||
|
bNode = SinglyListNode(11)
|
||||||
|
cNode = SinglyListNode(12)
|
||||||
|
dNode = SinglyListNode(13)
|
||||||
|
|
||||||
|
linkL.insertAtHead(aNode)
|
||||||
|
linkL.insertAtHead(bNode)
|
||||||
|
linkL.insertAtHead(cNode)
|
||||||
|
linkL.insertAtHead(dNode)
|
||||||
|
|
||||||
|
assert linkL.search(3).data == 10, f"Node containing 10 not found, got:{linkL.search(3).data}"
|
||||||
|
assert linkL.search(2).data == 11, f"Node containing 11 not found, got:{linkL.search(2).data}"
|
||||||
|
assert linkL.search(1).data == 12, f"Node containing 12 not found, got:{linkL.search(1).data}"
|
||||||
|
assert linkL.search(0).data == 13, f"Node containing 13 not found, got:{linkL.search(0).data}"
|
||||||
|
|
||||||
|
print("No Errors: Linked List Contents: ")
|
||||||
|
linkL.printList()
|
||||||
|
print()
|
||||||
|
|
||||||
|
linkL.delete(12)
|
||||||
|
print("After Deletion")
|
||||||
|
assert linkL.search(1).data == 11, f"Node containing 11 not found, got:{linkL.search(1).data}"
|
||||||
|
print("No Errors: Linked List Contents: ")
|
||||||
|
linkL.printList()
|
||||||
|
print()
|
||||||
|
|
||||||
|
linkL.deleteAtHead()
|
||||||
|
assert linkL.search(0).data == 11, f"Node containing 11 not found, got:{linkL.search(0).data}"
|
||||||
|
print("No Errors: Linked List Contents: ")
|
||||||
|
linkL.printList()
|
||||||
|
print()
|
||||||
|
|
||||||
|
assert linkL.searchValue(10) == 1, f"Index of node containing 10 not found, got:{linkL.searchValue(10)}"
|
||||||
|
print("Index of node containing 10 is: ", linkL.searchValue(10))
|
||||||
|
|
||||||
|
assert linkL.peek() == 11, f"Head of linked list is not 11, got:{linkL.peek()}"
|
||||||
|
print("Head of linked list is: ", linkL.peek())
|
||||||
|
|
||||||
|
linkL.deleteAtHead()
|
||||||
|
linkL.deleteAtHead()
|
||||||
|
|
||||||
|
assert linkL.isEmpty() == True, f"Linked list is not empty, got:{linkL.printList()}"
|
||||||
|
print("Linked list is empty!")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
|
@ -0,0 +1,66 @@
|
||||||
|
class Stack:
|
||||||
|
# Complete the code here
|
||||||
|
def __init__(self):
|
||||||
|
self.top = -1
|
||||||
|
self.data = []
|
||||||
|
|
||||||
|
def push(self, value):
|
||||||
|
self.data.append(0)
|
||||||
|
self.top += 1
|
||||||
|
self.data[self.top] = value
|
||||||
|
|
||||||
|
def pop(self):
|
||||||
|
value = self.data[self.top]
|
||||||
|
del self.data[self.top]
|
||||||
|
self.top -= 1
|
||||||
|
return value
|
||||||
|
|
||||||
|
def peek(self):
|
||||||
|
if self.top != -1 and self.data is not None:
|
||||||
|
return self.data[self.top]
|
||||||
|
else:
|
||||||
|
return "Empty Stack"
|
||||||
|
def printStack(self):
|
||||||
|
print(self.data)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
tmpStack = Stack()
|
||||||
|
|
||||||
|
print(tmpStack.peek())
|
||||||
|
|
||||||
|
tmpStack.push(10)
|
||||||
|
topOfStack = tmpStack.peek()
|
||||||
|
assert (topOfStack == 10), f"Top of stack not 10, got:{topOfStack}"
|
||||||
|
|
||||||
|
tmpStack.push(11)
|
||||||
|
topOfStack = tmpStack.peek()
|
||||||
|
assert (topOfStack == 11), f"Top of stack not 11, got:{topOfStack}"
|
||||||
|
|
||||||
|
tmpStack.push(12)
|
||||||
|
topOfStack = tmpStack.peek()
|
||||||
|
assert (topOfStack == 12), f"Top of stack not 12, got:{topOfStack}"
|
||||||
|
|
||||||
|
tmpStack.push(13)
|
||||||
|
topOfStack = tmpStack.peek()
|
||||||
|
assert (topOfStack == 13), f"Top of stack not 13, got:{topOfStack}"
|
||||||
|
|
||||||
|
tmpStack.push(14)
|
||||||
|
topOfStack = tmpStack.peek()
|
||||||
|
assert (topOfStack == 14), f"Top of stack not 14, got:{topOfStack}"
|
||||||
|
|
||||||
|
tmpStack.pop()
|
||||||
|
topOfStack = tmpStack.peek()
|
||||||
|
assert (topOfStack == 13), f"Top of stack not 13, got:{topOfStack}"
|
||||||
|
|
||||||
|
tmpStack.pop()
|
||||||
|
topOfStack = tmpStack.peek()
|
||||||
|
assert (topOfStack == 12), f"Top of stack not 12, got:{topOfStack}"
|
||||||
|
|
||||||
|
print("No Errors! Stack contents: ")
|
||||||
|
tmpStack.printStack()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
|
@ -0,0 +1,40 @@
|
||||||
|
#!/bin/python3
|
||||||
|
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import random
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
|
||||||
|
#
|
||||||
|
# Complete the 'superDigit' function below.
|
||||||
|
#
|
||||||
|
# The function is expected to return an INTEGER.
|
||||||
|
# The function accepts following parameters:
|
||||||
|
# 1. STRING n
|
||||||
|
# 2. INTEGER k
|
||||||
|
#
|
||||||
|
|
||||||
|
def superDigit(n, k):
|
||||||
|
# Write your code here
|
||||||
|
if len(n) == 1:
|
||||||
|
return n
|
||||||
|
else:
|
||||||
|
digits = [int(x) for x in n] * k
|
||||||
|
return superDigit(str(sum(digits)), 1)
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
#fptr = open(os.environ['OUTPUT_PATH'], 'w')
|
||||||
|
|
||||||
|
first_multiple_input = input().rstrip().split()
|
||||||
|
|
||||||
|
n = first_multiple_input[0]
|
||||||
|
|
||||||
|
k = int(first_multiple_input[1])
|
||||||
|
|
||||||
|
result = superDigit(n, k)
|
||||||
|
print(result)
|
||||||
|
|
||||||
|
#fptr.write(str(result) + '\n')
|
||||||
|
|
||||||
|
#fptr.close()
|
|
@ -0,0 +1,57 @@
|
||||||
|
def partition(a):
|
||||||
|
pivot = a[0]
|
||||||
|
pivotIndex = 0
|
||||||
|
|
||||||
|
for i in range(1, len(a)):
|
||||||
|
if a[i] < pivot:
|
||||||
|
a[i], a[pivotIndex + 1] = a[pivotIndex + 1], a[i]
|
||||||
|
pivotIndex += 1
|
||||||
|
|
||||||
|
a[0], a[pivotIndex] = a[pivotIndex], a[0]
|
||||||
|
return pivotIndex
|
||||||
|
|
||||||
|
# Using partition to find 0 to kth smallest element
|
||||||
|
# Without using quickSort
|
||||||
|
# Obfuscate this line
|
||||||
|
def findKthsmallest(nums, k): print(nums[:partition(nums)][::-1])
|
||||||
|
#partition(nums)
|
||||||
|
#for i in range(k):
|
||||||
|
# if i == k - 1:
|
||||||
|
# print(nums[i])
|
||||||
|
# else:
|
||||||
|
# print(nums[i], end=", ")
|
||||||
|
|
||||||
|
# 1 line partition to find 0 to kth smallest element and reverse
|
||||||
|
|
||||||
|
def quickSort(a):
|
||||||
|
if len(a) <= 1:
|
||||||
|
return a
|
||||||
|
pivotIndex = partition(a)
|
||||||
|
left = quickSort(a[:pivotIndex])
|
||||||
|
right = quickSort(a[pivotIndex + 1:])
|
||||||
|
return left + [a[pivotIndex]] + right
|
||||||
|
|
||||||
|
|
||||||
|
def findKthLargest(nums, k):
|
||||||
|
sortedArray = quickSort(nums)
|
||||||
|
for i in range(k):
|
||||||
|
print(sortedArray[i])
|
||||||
|
|
||||||
|
def binarySerarchK(nums,k):
|
||||||
|
left = 0
|
||||||
|
right = len(nums) - 1
|
||||||
|
|
||||||
|
# Return element 1 to k
|
||||||
|
while left <= right:
|
||||||
|
mid = (left + right) >> 1
|
||||||
|
if mid == k:
|
||||||
|
return nums[:mid]
|
||||||
|
elif mid < k:
|
||||||
|
left = mid + 1
|
||||||
|
else:
|
||||||
|
right = mid - 1
|
||||||
|
return -1
|
||||||
|
|
||||||
|
array = [4, 2, 5, 9, 1, 3, 6, 8, 7]
|
||||||
|
findKthsmallest(array, 3)
|
||||||
|
print(quickSort(array))
|
|
@ -0,0 +1,16 @@
|
||||||
|
# This is a sample Python script.
|
||||||
|
|
||||||
|
# Press Shift+F10 to execute it or replace it with your code.
|
||||||
|
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
|
||||||
|
|
||||||
|
|
||||||
|
def print_hi(name):
|
||||||
|
# Use a breakpoint in the code line below to debug your script.
|
||||||
|
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
|
||||||
|
|
||||||
|
|
||||||
|
# Press the green button in the gutter to run the script.
|
||||||
|
if __name__ == '__main__':
|
||||||
|
print_hi('PyCharm')
|
||||||
|
|
||||||
|
# See PyCharm help at https://www.jetbrains.com/help/pycharm/
|
Loading…
Reference in New Issue