├── .gitignore ├── HackerRank ├── 0 - Tutorials │ ├── 10 Days of Statistics │ │ ├── Day 0 - Mean Median and Mode.py │ │ ├── Day 0 - Weighted Mean.py │ │ ├── Day 1 - Interquartile Range.py │ │ ├── Day 1 - Quartiles.py │ │ ├── Day 1 - Standard Deviation.py │ │ ├── Day 2 - Basic Probability.py │ │ ├── Day 2 - Compound Event Probability.py │ │ └── Day 2 - More Dice.py │ └── 30 Days of Code │ │ ├── Day 0 - Hello, World.py │ │ ├── Day 1 - Data Types.py │ │ ├── Day 10 - Binary Numbers.py │ │ ├── Day 11- 2D Arrays.py │ │ ├── Day 12 - Inheritance.py │ │ ├── Day 13 - Abstract Classes.py │ │ ├── Day 14 - Scope.py │ │ ├── Day 15 - Linked List.py │ │ ├── Day 16 - Exceptions String To Integer.py │ │ ├── Day 17 - More Exceptions.py │ │ ├── Day 18 - Queues and Stacks.py │ │ ├── Day 2 - Operators.py │ │ ├── Day 20 - Sorting.py │ │ ├── Day 22 - Binary Search Trees.py │ │ ├── Day 23 - BST Level-Order Traversal.py │ │ ├── Day 24 - More Linked Lists.py │ │ ├── Day 25 - Running Time and Complexity.py │ │ ├── Day 26 - Nested Logic.py │ │ ├── Day 27 - Testing.py │ │ ├── Day 28 - RegEx, Patterns, and Intro to Databases.py │ │ ├── Day 29 - Bitwise AND.py │ │ ├── Day 3 - Introduction to Conditional Statements.py │ │ ├── Day 4 - Class vs. Instance.py │ │ ├── Day 5 - Loops.py │ │ ├── Day 6 - Let's Review.py │ │ ├── Day 7 - Arrays.py │ │ ├── Day 8 - Dictionaries and Maps.py │ │ └── Day 9 - Recursion.py ├── 1 - Algorithms │ ├── 0 - Warmup │ │ ├── 1 - Solve Me First.py │ │ ├── 2 - Simple Array Sum.py │ │ ├── 3 - Compare the Triplets.py │ │ ├── 4 - A Very Big Sum.py │ │ ├── 5 - Diagonal Difference.py │ │ ├── 6 - Plus Minus.py │ │ ├── 7 - Staircase.py │ │ ├── 8 - Time Conversion.py │ │ └── 9 - Circular Array Rotation.py │ ├── 1 - Implementation │ │ ├── 0 - Kangaroo.py │ │ ├── 1 - Divisible Sum Pairs.py │ │ ├── 10 - Strange Counter.py │ │ ├── 2 - Utopian Tree.py │ │ ├── 3 - Angry Professor.py │ │ ├── 4 - Cut The Sticks.py │ │ ├── 5 - Encryption.py │ │ ├── 6 - Repeated String.py │ │ ├── 7 - Jumping on the Clouds.py │ │ ├── 8 - Bigger is Greater.py │ │ ├── 9 - Save the Prisoner!.py │ │ ├── Non-Divisible Subset.py │ │ ├── X - Caesar Cypher.py │ │ ├── X - Chocolate Feast.py │ │ ├── X - Find Digits.py │ │ ├── X - Kaprekar - Numbers.py │ │ ├── X - Matrix Rotation.py │ │ ├── X - Service Lane.py │ │ └── X - Sherlock And Squares.py │ ├── 2 - Strings │ │ ├── 1 - Pangrams.py │ │ ├── 2 - Alternating Characters.py │ │ ├── 3 - The Love-Letter Mystery.py │ │ ├── 4 - Gemstones.py │ │ ├── 5 - Funny String.py │ │ ├── 6 - Anagram.py │ │ ├── 7 - Palindrome Index.py │ │ └── Super Reduced String.py │ ├── 3 - Sorting │ │ ├── 0 - Intro to Tutorial Challenges.py │ │ └── 1 - Insertion Sort - Part 1.py │ ├── 6 - Greedy │ │ ├── 1 - Grid Challenge.py │ │ ├── 2 - Luck Challenge.py │ │ ├── 3 - Beautiful Pairs.py │ │ ├── 4 - Sherlock And The Beast.py │ │ └── 5 - Jim and the Orders.py │ └── 8 - Bit Manipulation │ │ ├── 1 - Lonely Integer.py │ │ ├── 2 - Maximize XOR.py │ │ ├── 3 - Counter Game.py │ │ ├── 4 - Sansa and XOR.py │ │ └── 5 - Flipping Bits.py ├── 2 - Data Structures │ ├── 1 - Arrays │ │ ├── 1 - Arrays - DS.py │ │ ├── 2 - 2D Array - DS.py │ │ ├── 3 - Dynamic Array.py │ │ ├── 4 - Array Left Rotation.py │ │ └── 5 - Sparse Arrays.py │ ├── 2 - Linked Lists │ │ ├── 1 - Print the Elements of a Linked List.py │ │ ├── 10 - Get Node Value.py │ │ ├── 2 - Insert a Node at the Tail of a Linked List.py │ │ ├── 3 - Insert a node at the head of a linked list.py │ │ ├── 4 - Delete a Node.py │ │ ├── 5 - Insert a node at a specific position in a linked list.py │ │ ├── 6 - Print in Reverse.py │ │ ├── 7 - Reverse a linked list.py │ │ ├── 8 - Compare two linked lists.py │ │ ├── 9 - Merge two sorted linked lists.py │ │ └── Node.py │ └── 3 - Trees │ │ ├── 1 - Preorder Traversal.py │ │ ├── 2 - Inorder Traversal.py │ │ ├── 3 - Postorder Traversal.py │ │ └── Node.py ├── 3 - Mathematics │ └── Fundamentals │ │ ├── 0 - Find Point.py │ │ ├── 1 - Maximum Draws.py │ │ ├── 2 - Handshake.py │ │ ├── 3 - Possible Path.py │ │ └── 4 - Leonardos Prime Factors.py └── 6 - Python │ ├── Built-Ins │ ├── 0 - Zipped!.py │ ├── 1 - Input().py │ ├── 2 - Python Evaluation.py │ ├── 3 - Sort Data.py │ ├── 4 - Any Or All..py │ └── 5 - ginortS.py │ ├── Classes │ ├── 0 - Dealing With Complex Numbers.py │ └── 1 - Find The Torsional Angle.py │ ├── Collections │ ├── 1 - Collections.Counter.py │ ├── 2 - DefaultDict Tutorial.py │ ├── 3 - Collections.NamedTuple.py │ ├── 4 - Collections.OrderedDict.py │ ├── 5 - Word Order.py │ ├── 6 - Collections.Deque.py │ ├── 7 - Piling Up!.py │ └── 8 - Most Common.py │ ├── Data Types │ ├── 1 - Lists.py │ ├── 2 - Tuples.py │ ├── 3 - Set - Symmetric Difference.py │ ├── 4 - List Comprehensions.py │ ├── 5 - Find The Second Largest Number.py │ └── 6 - Nested Lists.py │ ├── Date AndTime │ ├── 1 - Calendar Module.py │ └── 2 - Time Delta.py │ ├── Errors And Exceptions │ ├── 1 - Exceptions.py │ └── 2 - Incorrect Regex.py │ ├── Functionals │ ├── 1 - Map And Lambda Function.py │ └── 2 - Validating Email Addresses With a Filter.py │ ├── Introduction │ ├── 1 - Hello World.py │ ├── 10 - Interchange Two Numbers.py │ ├── 11 - Finding The Percentage.py │ ├── 12 - Print Function.py │ ├── 2 - Raw Input.py │ ├── 3 - Arithmetic Operators.py │ ├── 4 - Python Division.py │ ├── 5 - Mod Divmod.py │ ├── 6 - Power - Mod Power.py │ ├── 7 - Integers Come In All Sizes.py │ ├── 8 - Loops.py │ └── 9 - What's Your Name.py │ ├── Itertools │ ├── 1 - Itertools.Product.py │ ├── 2 - Itertools.Permutations.py │ ├── 3 - Itertools.Combinations.py │ ├── 4 - Itertools.Combinations With Replacement.py │ ├── 5 - Compress The String.py │ ├── 6 - Iteratables And Iterators.py │ └── 7 - Maximize It.py │ ├── Math │ ├── 1 - Polar Coordinates.py │ ├── 2 - Find Angle.py │ ├── 3 - Triangle Quest 2.py │ └── 4 - Triangle Quest.py │ ├── Regex And Patterns │ ├── 1 - Introduction To Regex Module.py │ ├── 10 - Hex Color Code.py │ ├── 11 - HTML Parser - Part 1.py │ ├── 12 - HTML Parser - Part 2.py │ ├── 13 - Detect HTML Tags, Attributes and Attribute Values.py │ ├── 14 - Validating UID.py │ ├── 2 - Re.split().py │ ├── 3 - Group(), Groups() & Groupdict().py │ ├── 4 - Re.findall() & Re.finditer().py │ ├── 5 - Re.start() & Re.end().py │ ├── 6 - Regex Substitution.py │ ├── 7 - Validating A Roman Number.py │ ├── 8 - Validating Phone Numbers.py │ └── 9 - Validating & Parsing Email Address.py │ ├── Sets │ ├── 1 - Introduction To Sets.py │ ├── 10 - The Captain's Room.py │ ├── 11 - Check Subset.py │ ├── 12 - Check Strict Superset.py │ ├── 2 - No Idea.py │ ├── 3 - Set Add.py │ ├── 4 - Set Discard Remove And Pop.py │ ├── 5 - Set Union.py │ ├── 6 - Set Intersection.py │ ├── 7 - Set Difference.py │ ├── 8 - Set Symmetric Difference.py │ └── 9 - Set Mutations.py │ └── Strings │ ├── 1 - sWAP cASE.py │ ├── 10 - Alphabet Rangoli.py │ ├── 11 - Capitalize.py │ ├── 12 - The Minion Game.py │ ├── 2 - String Split And Join.py │ ├── 3 - Mutations.py │ ├── 4 - Find A String.py │ ├── 5 - String Validators.py │ ├── 6 - Text Alignment.py │ ├── 7 - Text Wrap.py │ ├── 8 - Desginer Door Mat.py │ └── 9 - String Formatting.py ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/10 Days of Statistics/Day 0 - Mean Median and Mode.py: -------------------------------------------------------------------------------- 1 | def mean(values: list) -> int: 2 | length = len(values) 3 | result = 0 4 | for value in values: 5 | result += value 6 | result /= length 7 | return result 8 | 9 | 10 | def median(values: list) -> float: 11 | length = len(values) 12 | values = sorted(values) 13 | if length % 2 != 0: 14 | return values[length // 2] 15 | else: 16 | return (values[length // 2] + values[length // 2 - 1]) / 2 17 | 18 | 19 | def mode(values: list) -> int: 20 | counters = dict() 21 | result = None 22 | for value in values: 23 | if value in counters: 24 | counters[value] += 1 25 | else: 26 | counters[value] = 1 27 | if (result is None) or (counters[value] > counters[result]): 28 | result = value 29 | elif (counters[value] == counters[result]) and (value < result): 30 | result = value 31 | return result 32 | 33 | 34 | n = int(input()) 35 | x = [int(token) for token in input().split()] 36 | print(mean(x)) 37 | print(median(x)) 38 | print(mode(x)) 39 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/10 Days of Statistics/Day 0 - Weighted Mean.py: -------------------------------------------------------------------------------- 1 | def weighted_mean(values: list, weights: list) -> float: 2 | sum_weighted_values = 0 3 | sum_weights = 0 4 | for i in range(len(values)): 5 | value = values[i] 6 | weight = weights[i] 7 | sum_weighted_values += value * weight 8 | sum_weights += weight 9 | result = sum_weighted_values / sum_weights 10 | return result 11 | 12 | 13 | n = int(input()) 14 | x = [int(token) for token in input().split()] 15 | w = [int(token) for token in input().split()] 16 | print(round(weighted_mean(x, w), 1)) 17 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/10 Days of Statistics/Day 1 - Interquartile Range.py: -------------------------------------------------------------------------------- 1 | def median(values: list, start_index: int, stop_index: int) -> float: 2 | length = stop_index - start_index + 1 3 | middle_index = start_index + length // 2 4 | if (length % 2) == 0: 5 | return (values[middle_index - 1] + values[middle_index]) / 2 6 | else: 7 | return values[middle_index] 8 | 9 | 10 | def quartiles(values: list) -> tuple: 11 | values = sorted(values) 12 | length = len(values) 13 | q2 = median(values, 0, length - 1) 14 | middle_index = length // 2 15 | if (length % 2) == 0: 16 | q1 = median(values, 0, middle_index - 1) 17 | q3 = median(values, middle_index, length - 1) 18 | else: 19 | q1 = median(values, 0, middle_index - 1) 20 | q3 = median(values, middle_index + 1, length - 1) 21 | return q1, q2, q3 22 | 23 | 24 | def interquatile_range(values: list, frequencies: list) -> float: 25 | n = len(values) 26 | s = [] 27 | for i in range(n): 28 | value = values[i] 29 | frequency = frequencies[i] 30 | for j in range(frequency): 31 | s.append(value) 32 | s.sort() 33 | qs = quartiles(s) 34 | result = float(qs[2] - qs[0]) 35 | return result 36 | 37 | 38 | n = int(input()) 39 | x = [int(i) for i in input().split()] 40 | f = [int(i) for i in input().split()] 41 | print(interquatile_range(x, f)) 42 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/10 Days of Statistics/Day 1 - Quartiles.py: -------------------------------------------------------------------------------- 1 | def median_core(values: list, start_index: int, stop_index: int) -> float: 2 | n = stop_index - start_index + 1 3 | m = start_index + n // 2 4 | if (n % 2) == 0: 5 | return (values[m - 1] + values[m]) / 2 6 | else: 7 | return values[m] 8 | 9 | 10 | def quartiles(values: list) -> tuple: 11 | values = sorted(values) 12 | length = len(values) 13 | q2 = median_core(values, 0, length - 1) 14 | m = length // 2 15 | if (length % 2) == 0: 16 | q1 = median_core(values, 0, m - 1) 17 | q3 = median_core(values, m , length - 1) 18 | else: 19 | q1 = median_core(values, 0, m - 1) 20 | q3 = median_core(values, m + 1, length - 1) 21 | return q1, q2, q3 22 | 23 | 24 | n = int(input()) 25 | x = [int(i) for i in input().split()] 26 | result = map('{:g}'.format, quartiles(x)) 27 | print(*result, sep="\n") 28 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/10 Days of Statistics/Day 1 - Standard Deviation.py: -------------------------------------------------------------------------------- 1 | def standard_deviation(values: list) -> float: 2 | length = len(values) 3 | mean = sum(values) / length 4 | result = 0 5 | for value in values: 6 | result += (value - mean)**2 7 | result = (result / length)**0.5 8 | return result 9 | 10 | 11 | n = int(input()) 12 | x = [int(token) for token in input().split()] 13 | print(round(standard_deviation(x), 1)) 14 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/10 Days of Statistics/Day 2 - Basic Probability.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | # In a single toss of 2 fair (evenly-weighted) six-sided dice, 4 | # find the probability that their sum will be at most 9. 5 | from fractions import Fraction 6 | 7 | dice_max = 6 8 | dice_min = 1 9 | dice_range = range(dice_min, dice_max + 1) 10 | count = 0 11 | for d1 in dice_range: 12 | for d2 in dice_range: 13 | if (d1 + d2) <= 9: 14 | count += 1 15 | possibilities = dice_max**2 16 | print(Fraction(count, possibilities)) -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/10 Days of Statistics/Day 2 - Compound Event Probability.py: -------------------------------------------------------------------------------- 1 | # There are 3 urns labeled X, Y, and Z. 2 | # Urn X contains 4 red balls and 3 black balls. 3 | # Urn Y contains 5 red balls and 4 black balls. 4 | # Urn Z contains 4 red balls and 4 black balls. 5 | 6 | # One ball is drawn from each of the 3 urns. 7 | # What is the probability that, of the 3 balls drawn, 2 are red and 1 is black? 8 | from fractions import Fraction 9 | 10 | ux_red_count = 4 11 | ux_black_count = 3 12 | ux_count = ux_red_count + ux_black_count 13 | 14 | uy_red_count = 5 15 | uy_black_count = 4 16 | uy_count = uy_red_count + uy_black_count 17 | 18 | uz_red_count = 4 19 | uz_black_count = 4 20 | uz_count = uz_red_count + uz_black_count 21 | 22 | px_red = Fraction(ux_red_count, ux_count) 23 | px_black = Fraction(ux_black_count, ux_count) 24 | 25 | py_red = Fraction(uy_red_count, uy_count) 26 | py_black = Fraction(uy_black_count, uy_count) 27 | 28 | pz_red = Fraction(uz_red_count, uz_count) 29 | pz_black = Fraction(uz_black_count, uz_count) 30 | 31 | result = px_red * py_red * pz_black + \ 32 | px_red * py_black * pz_red + \ 33 | px_black * py_red * pz_red 34 | print(result) -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/10 Days of Statistics/Day 2 - More Dice.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | # In a single toss of 2 fair (evenly-weighted) six-sided dice, 4 | # find the probability that the values rolled by each die will be different and the two dice have a sum of 6. 5 | from fractions import Fraction 6 | 7 | dice_max = 6 8 | dice_min = 1 9 | dice_range = range(dice_min, dice_max + 1) 10 | count = 0 11 | for d1 in dice_range: 12 | for d2 in dice_range: 13 | if (d1 != d2) and ((d1 + d2) == 6): 14 | count += 1 15 | possibilities = dice_max ** 2 16 | print(Fraction(count, possibilities)) 17 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 0 - Hello, World.py: -------------------------------------------------------------------------------- 1 | """ 2 | Objective 3 | In this challenge, we review some basic concepts that will get you started with this series. 4 | You will need to use the same (or similar) syntax to read input and write output in challenges throughout HackerRank. 5 | Check out the Tutorial tab for learning materials and an instructional video! 6 | 7 | Task 8 | To complete this challenge, you must save a line of input from stdin (standard input) to a variable, 9 | print "Hello, World." on a single line, and finally print the value of your variable on a second line. 10 | """ 11 | 12 | # Get a line of input from stdin and save it to our variable 13 | inputString = input() 14 | 15 | # Your first line of output goes here 16 | print('Hello, World.') 17 | 18 | # Write the second line of output 19 | print(inputString) 20 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 1 - Data Types.py: -------------------------------------------------------------------------------- 1 | """ 2 | Objective 3 | Today, we're discussing data types. 4 | 5 | Task 6 | Complete the code in the editor below. The variables i, d, and s are already declared and initialized for you. 7 | You must declare variables: one of type int, one of type double, and one of type String. 8 | Then you must read lines of input from stdin and initialize your variables. 9 | Finally, you must use the operator to perform the following operations: 10 | Print the sum of i plus your int variable on a new line. 11 | Print the sum of d plus your double variable to a scale of one decimal place on a new line. 12 | Concatenate s with the string you read as input and print the result on a new line. 13 | """ 14 | 15 | # Declare second integer, double, and String variables. 16 | i = 4 17 | d = 4.0 18 | s = 'HackerRank ' 19 | 20 | # Read and save an integer, double, and String to your variables. 21 | ii = int(input()) 22 | dd = float(input()) 23 | ss = input() 24 | 25 | # Print the sum of both integer variables on a new line. 26 | print(i + ii) 27 | 28 | # Print the sum of the double variables on a new line. 29 | print(d + dd) 30 | 31 | # Concatenate and print the String variables on a new line 32 | # The 's' variable above should be printed first. 33 | print(s + ss) 34 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 10 - Binary Numbers.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | 3 | max_one_count = 0 4 | one_count = 0 5 | 6 | while n != 0: 7 | factor = n // 2 8 | remainder = n - 2 * factor 9 | n = factor 10 | if remainder == 1: 11 | one_count += 1 12 | max_one_count = max(max_one_count, one_count) 13 | else: 14 | one_count = 0 15 | 16 | print(max_one_count) 17 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 11- 2D Arrays.py: -------------------------------------------------------------------------------- 1 | arr = [] 2 | for arr_i in range(6): 3 | arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')] 4 | arr.append(arr_t) 5 | 6 | smax = -9 * 7 7 | 8 | for row in range(len(arr) - 2): 9 | for column in range(len(arr[row]) - 2): 10 | tl = arr[row][column] 11 | tc = arr[row][column + 1] 12 | tr = arr[row][column + 2] 13 | mc = arr[row + 1][column + 1] 14 | bl = arr[row + 2][column] 15 | bc = arr[row + 2][column + 1] 16 | br = arr[row + 2][column + 2] 17 | s = tl + tc + tr + mc + bl + bc + br 18 | smax = max(s, smax) 19 | 20 | print(smax) 21 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 12 - Inheritance.py: -------------------------------------------------------------------------------- 1 | class Person: 2 | def __init__(self, firstName, lastName, idNumber): 3 | self.firstName = firstName 4 | self.lastName = lastName 5 | self.idNumber = idNumber 6 | 7 | def printPerson(self): 8 | print("Name:", self.lastName + ",", self.firstName) 9 | print("ID:", self.idNumber) 10 | 11 | 12 | class Student(Person): 13 | def __init__(self, firstName, lastName, idNumber, scores): 14 | super().__init__(firstName, lastName, idNumber) 15 | self.scores = scores 16 | 17 | def calculate(self): 18 | a = sum(self.scores) / len(self.scores) 19 | if a < 40: 20 | return "T" 21 | elif (40 <= a) and (a < 55): 22 | return "D" 23 | elif (55 <= a) and (a < 70): 24 | return "P" 25 | elif (70 <= a) and (a < 80): 26 | return "A" 27 | elif (80 <= a) and (a < 90): 28 | return "E" 29 | elif (90 <= a) and (a <= 100): 30 | return "O" 31 | else: 32 | return "" 33 | 34 | 35 | line = input().split() 36 | firstName = line[0] 37 | lastName = line[1] 38 | idNum = line[2] 39 | numScores = int(input()) # not needed for Python 40 | scores = list(map(int, input().split())) 41 | s = Student(firstName, lastName, idNum, scores) 42 | s.printPerson() 43 | print("Grade:", s.calculate()) 44 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 13 - Abstract Classes.py: -------------------------------------------------------------------------------- 1 | from abc import ABCMeta, abstractmethod 2 | 3 | 4 | class Book(object, metaclass=ABCMeta): 5 | def __init__(self, title, author): 6 | self.title = title 7 | self.author = author 8 | 9 | @abstractmethod 10 | def display(self): 11 | pass 12 | 13 | 14 | # Write MyBook class 15 | class MyBook(Book): 16 | def __init__(self, title, author, price): 17 | super().__init__(title, author) 18 | self.price = price 19 | 20 | def display(self): 21 | print("Title:", self.title) 22 | print("Author:", self.author) 23 | print("Price:", self.price) 24 | 25 | 26 | title = input() 27 | author = input() 28 | price = int(input()) 29 | new_novel = MyBook(title, author, price) 30 | new_novel.display() 31 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 14 - Scope.py: -------------------------------------------------------------------------------- 1 | class Difference: 2 | def __init__(self, a): 3 | self.__elements = a 4 | self.maximumDifference = 0 5 | 6 | # Add your code here 7 | def computeDifference(self): 8 | l = len(a) 9 | for i in range(0, l): 10 | for j in range(i + 1, l): 11 | difference = abs(a[i] - a[j]) 12 | self.maximumDifference = max(difference, self.maximumDifference) 13 | # End of Difference class 14 | 15 | a = [int(e) for e in "1 2 5".split(' ')] 16 | 17 | d = Difference(a) 18 | d.computeDifference() 19 | 20 | print(d.maximumDifference) 21 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 15 - Linked List.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, data): 3 | self.data = data 4 | self.next = None 5 | 6 | 7 | class Solution: 8 | def display(self, head): 9 | current = head 10 | while current: 11 | print(current.data, end=' ') 12 | current = current.next 13 | 14 | #Complete this method 15 | def insert(self, head, data): 16 | node = Node(data) 17 | if head is None: 18 | head = node 19 | else: 20 | current = head 21 | while(current.next is not None): 22 | current = current.next 23 | current.next = node 24 | return head 25 | 26 | mylist= Solution() 27 | T = int(input()) 28 | head = None 29 | for i in range(T): 30 | data = int(input()) 31 | head = mylist.insert(head, data) 32 | mylist.display(head); -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 16 - Exceptions String To Integer.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | S = input().strip() 6 | 7 | try: 8 | i = int(S) 9 | print(i) 10 | except ValueError: 11 | print("Bad String") 12 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 17 - More Exceptions.py: -------------------------------------------------------------------------------- 1 | class Calculator(object): 2 | def power(self, n, p): 3 | if (n < 0) or (p < 0): 4 | raise Exception("n and p should be non-negative") 5 | else: 6 | return n ** p 7 | 8 | 9 | myCalculator = Calculator() 10 | T = int(input()) 11 | for i in range(T): 12 | n, p = map(int, input().split()) 13 | try: 14 | ans = myCalculator.power(n, p) 15 | print(ans) 16 | except Exception as e: 17 | print(e) 18 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 18 - Queues and Stacks.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | # Write your code here 3 | def __init__(self): 4 | self.__stack = [] 5 | self.__queue = [] 6 | 7 | def pushCharacter(self, ch): 8 | self.__stack.append(ch) 9 | 10 | def enqueueCharacter(self, ch): 11 | self.__queue.insert(0, ch) 12 | 13 | def popCharacter(self): 14 | return self.__stack.pop() 15 | 16 | def dequeueCharacter(self): 17 | return self.__queue.pop() 18 | 19 | 20 | # Read the string s 21 | s = input() 22 | # Create the Solution class object 23 | obj = Solution() 24 | 25 | l = len(s) 26 | # Push / Enqueue all the characters of string s to stack 27 | for i in range(l): 28 | obj.pushCharacter(s[i]) 29 | obj.enqueueCharacter(s[i]) 30 | 31 | isPalindrome = True 32 | ''' 33 | pop the top character from stack 34 | dequeue the first character from queue 35 | compare both the characters 36 | ''' 37 | for i in range(l // 2): 38 | if obj.popCharacter() != obj.dequeueCharacter(): 39 | isPalindrome=False 40 | break 41 | 42 | # Finally print whether string s is palindrome or not. 43 | if isPalindrome: 44 | print("The word,", s, ", is a palindrome.") 45 | else: 46 | print("The word,", s, ", is not a palindrome.") 47 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 2 - Operators.py: -------------------------------------------------------------------------------- 1 | """ 2 | Objective 3 | In this challenge, you'll work with arithmetic operators. 4 | 5 | Task 6 | Given: 7 | - the meal price (base cost of a meal), 8 | - tip percent (the percentage of the meal price being added as tip), 9 | - tax percent (the percentage of the meal price being added as tax) for a meal 10 | Find and print the meal's total cost. 11 | 12 | Note: Be sure to use precise values for your calculations, 13 | or you may end up with an incorrectly rounded result! 14 | """ 15 | 16 | mealCost = float(input()) 17 | tipPercent = int(input()) 18 | taxPercent = int(input()) 19 | tip = mealCost * tipPercent / 100 20 | tax = mealCost * taxPercent / 100 21 | totalCost = mealCost + tip + tax 22 | print("The total meal cost is " + str(round(totalCost)) + " dollars.") 23 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 20 - Sorting.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | def swap(a, x, y): 6 | tmp = a[x] 7 | a[x] = a[y] 8 | a[y] = tmp 9 | 10 | def bubblesort(a): 11 | n = len(a) 12 | allSwapCount = 0 13 | for i in range(0, n): 14 | swapCount = 0 15 | for j in range(0, n - 1): 16 | if a[j] > a[j + 1]: 17 | swap(a, j, j + 1) 18 | swapCount += 1 19 | if swapCount == 0: 20 | break 21 | else: 22 | allSwapCount += swapCount 23 | return (a[0], a[n - 1], allSwapCount) 24 | 25 | n = int(input().strip()) 26 | a = [int(a_temp) for a_temp in input().strip().split(' ')] 27 | first, last, swaps = bubblesort(a) 28 | print("Array is sorted in", swaps, "swaps.") 29 | print("First Element:", first) 30 | print("Last Element:", last) 31 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 22 - Binary Search Trees.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, data): 3 | self.right =self.left = None 4 | self.data = data 5 | 6 | 7 | class Solution: 8 | def insert(self, root, data): 9 | if root == None: 10 | return Node(data) 11 | else: 12 | if data <= root.data: 13 | current = self.insert(root.left, data) 14 | root.left = current 15 | else: 16 | current = self.insert(root.right, data) 17 | root.right = current 18 | return root 19 | 20 | def getHeight(self, root): 21 | #Write your code here 22 | if root: 23 | left = 0 24 | right = 0 25 | if root.left: 26 | left = 1 + self.getHeight(root.left) 27 | if root.right: 28 | right = 1 + self.getHeight(root.right) 29 | return max(left, right) 30 | else: 31 | return 0 32 | 33 | T = int(input()) 34 | myTree = Solution() 35 | root = None 36 | for i in range(T): 37 | data = int(input()) 38 | root = myTree.insert(root, data) 39 | height = myTree.getHeight(root) 40 | print(height) 41 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 23 - BST Level-Order Traversal.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self, data): 3 | self.right = self.left = None 4 | self.data = data 5 | 6 | 7 | class Solution: 8 | def insert(self, root, data): 9 | if not root: 10 | return Node(data) 11 | else: 12 | if data <= root.data: 13 | current = self.insert(root.left, data) 14 | root.left = current 15 | else: 16 | current = self.insert(root.right, data) 17 | root.right = current 18 | return root 19 | 20 | def level_order_traverse(self, root): 21 | #Write your code here 22 | if root: 23 | queue = [root] 24 | while queue: 25 | node = queue.pop() 26 | print(node.data) 27 | if node.left: 28 | queue.insert(0, node.left) 29 | if node.right: 30 | queue.insert(0, node.right) 31 | 32 | T = int(input()) 33 | myTree = Solution() 34 | root = None 35 | for i in range(T): 36 | data = int(input()) 37 | root = myTree.insert(root, data) 38 | myTree.level_order_traverse(root) 39 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 24 - More Linked Lists.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | def __init__(self,data): 3 | self.data = data 4 | self.next = None 5 | 6 | 7 | class Solution: 8 | def insert(self, head, data): 9 | p = Node(data) 10 | if not head: 11 | head = p 12 | elif not head.next: 13 | head.next=p 14 | else: 15 | start = head 16 | while(not start.next): 17 | start = start.next 18 | start.next = p 19 | return head 20 | 21 | def display(self, head): 22 | current = head 23 | while current: 24 | print(current.data, end=' ') 25 | current = current.next 26 | 27 | def remove_duplicates(self, head): 28 | # Write your code here 29 | previous = head 30 | s = set() 31 | s.add(previous.data) 32 | current = previous.next 33 | while current: 34 | if current.data in s: 35 | previous.next = current.next 36 | else: 37 | s.add(current.data) 38 | previous = current 39 | current = current.next 40 | return head 41 | 42 | 43 | mylist = Solution() 44 | T = int(input()) 45 | head = None 46 | for i in range(T): 47 | data = int(input()) 48 | head = mylist.insert(head,data) 49 | head = mylist.remove_duplicates(head) 50 | mylist.display(head) 51 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 25 - Running Time and Complexity.py: -------------------------------------------------------------------------------- 1 | def is_prime(n): 2 | if n == 1: 3 | return False 4 | else: 5 | square_root = int(n**0.5) 6 | for i in range(2, square_root + 1): 7 | if ((n % i) == 0) and (i != n): 8 | return False 9 | return True 10 | 11 | 12 | t = int(input()) 13 | for _ in range(t): 14 | n = int(input()) 15 | if is_prime(n): 16 | print("Prime") 17 | else: 18 | print("Not prime") 19 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 26 - Nested Logic.py: -------------------------------------------------------------------------------- 1 | from datetime import date 2 | 3 | 4 | actual = map(int, input().split()) 5 | expected = map(int, input().split()) 6 | 7 | actual = list(actual) 8 | expected = list(expected) 9 | 10 | actual = date(day=actual[0], month=actual[1], year=actual[2]) 11 | expected = date(day=expected[0], month=expected[1], year=expected[2]) 12 | 13 | fine = 0 14 | 15 | if actual > expected: 16 | if actual.year == expected.year: 17 | if actual.month == expected.month: 18 | fine = 15 * (actual.day - expected.day) 19 | else: 20 | fine = 500 * (actual.month - expected.month) 21 | else: 22 | fine = 10000 23 | 24 | print(fine) 25 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 27 - Testing.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | T = random.randrange(5, 20, 1) 5 | print(T) 6 | for t in range(T): 7 | N = 3 + t 8 | K = 3 9 | if (t % 2) == 0: 10 | a = [-1] + [0] + [1] * (N - 2) 11 | else: 12 | a = [-1] + [0] * 2 + [1] * (N - 3) 13 | print(N, K) 14 | print(*a, sep=" ") 15 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 28 - RegEx, Patterns, and Intro to Databases.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | gmail_regex = re.compile("^[a-z\.]+@gmail.com$") 5 | gmail_accounts = dict() 6 | N = int(input().strip()) 7 | for _ in range(N): 8 | firstName, email = input().strip().split(' ') 9 | if gmail_regex.match(email): 10 | gmail_accounts[email] = firstName 11 | 12 | sorted_names = sorted(gmail_accounts.values()) 13 | print(*sorted_names, sep="\n") 14 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 29 - Bitwise AND.py: -------------------------------------------------------------------------------- 1 | t = int(input()) 2 | for a0 in range(t): 3 | n, k = map(int, input().split()) 4 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 3 - Introduction to Conditional Statements.py: -------------------------------------------------------------------------------- 1 | """ 2 | Objective 3 | In this challenge, we're getting started with conditional statements. 4 | 5 | Task 6 | Given an integer, n, perform the following conditional actions: 7 | If n is odd, print Weird 8 | If n is even and in the inclusive range of 2 to 5, print Not Weird 9 | If n is even and in the inclusive range of 6 to 20, print Weird 10 | If n is even and greater than 20, print Not Weird 11 | 12 | Complete the stub code provided in your editor to print whether or not n is weird. 13 | """ 14 | 15 | n = int(input().strip()) 16 | 17 | if (n % 2) != 0: 18 | print("Weird") 19 | else: 20 | if (2 <= n) and (n <= 5): 21 | print("Not Weird") 22 | elif (6 <= n) and (n <= 20): 23 | print("Weird") 24 | else: 25 | print("Not Weird") 26 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 4 - Class vs. Instance.py: -------------------------------------------------------------------------------- 1 | """ 2 | In this challenge, we're going to learn about the difference between a class and an instance; 3 | because this is an Object Oriented concept, it's only enabled in certain languages. 4 | 5 | Task 6 | Write a Person class with an instance variable, age, and a constructor that takes an integer, initial_age, as a parameter. 7 | The constructor must assign initial_age to _age after confirming the argument passed as _initial_age is not negative. 8 | If a negative argument is passed as initial_age, the constructor should set to and print "Age is not valid, setting age to 0." 9 | 10 | In addition, you must write the following instance methods: 11 | age_1_year() should increase the instance variable _age by 1. 12 | is_old() should perform the following conditional actions: 13 | If age < 13, print "You are young.". 14 | If age >= 13 and age < 18, print "You are a teenager.". 15 | Otherwise, print "You are old.". 16 | """ 17 | 18 | 19 | class Person: 20 | # Add some more code to run some checks on initial_age 21 | def __init__(self, initial_age): 22 | if initial_age < 0: 23 | print("Age is not valid, setting age to 0.") 24 | self._age = 0 25 | else: 26 | self._age = initial_age 27 | 28 | # Do some computations in here and print out the correct statement to the console 29 | def is_old(self): 30 | if self._age < 13: 31 | print("You are young.") 32 | elif (13 <= self._age) and (self._age < 18): 33 | print("You are a teenager.") 34 | else: 35 | print("You are old.") 36 | 37 | # Increment the age of the person in here 38 | def age_1_year(self): 39 | self._age += 1 40 | 41 | 42 | T = int(input()) 43 | 44 | for i in range(0, T): 45 | age = int(input()) 46 | p = Person(age) 47 | p.is_old() 48 | for j in range(0, 3): 49 | p.age_1_year() 50 | p.is_old() 51 | print("") 52 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 5 - Loops.py: -------------------------------------------------------------------------------- 1 | """ 2 | Objective 3 | In this challenge, we're going to use loops to help us do some simple math. Check out the Tutorial tab to learn more. 4 | 5 | Task 6 | Given an integer, N, print its first 10 multiples. 7 | Each multiple N * i (where 1 <= i <= 10) should be printed on a new line in the form: 8 | N x i = result. 9 | """ 10 | 11 | 12 | N = int(input().strip()) 13 | 14 | for i in range(1, 11): 15 | print('{0} x {1} = {2}'.format(N, i, N * i)) 16 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 6 - Let's Review.py: -------------------------------------------------------------------------------- 1 | """ 2 | Objective 3 | Today we're expanding our knowledge of Strings and combining it with what we've already learned about loops. 4 | 5 | Task 6 | Given a string, S, of length N that is indexed from 0 to N-1, 7 | print its even-indexed and odd-indexed characters 8 | as 2 space-separated strings on a single line. 9 | 10 | Note: 0 is considered to be an even index. 11 | """ 12 | 13 | T = int(input().strip()) 14 | 15 | for i in range(0, T): 16 | S = input() 17 | even, odd = S[::2], S[1::2] 18 | print(even + " " + odd) 19 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 7 - Arrays.py: -------------------------------------------------------------------------------- 1 | """ 2 | Objective 3 | Today, we're learning about the Array data structure. 4 | 5 | Task 6 | Given an array, A, of N integers, print A's elements in reverse order 7 | as a single line of space-separated numbers. 8 | """ 9 | 10 | 11 | n = int(input().strip()) 12 | arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] 13 | 14 | # Reverse arr and convert integer to string 15 | rarr = map(str, arr[::-1]) 16 | print(" ".join(rarr)) 17 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 8 - Dictionaries and Maps.py: -------------------------------------------------------------------------------- 1 | """ 2 | Objective 3 | Today, we're learning about Key-Value pair mappings using a Map or Dictionary data structure. 4 | 5 | Task 6 | Given N names and phone numbers, assemble a phone book that maps friends' names 7 | to their respective phone numbers. You will then be given an unknown number of names 8 | to query your phone book for; for each name queried, print the associated entry from 9 | your phone book (in the form name=number) or Not found if there is no entry for name. 10 | 11 | Note: Your phone book should be a Dictionary/Map/HashMap data structure. 12 | """ 13 | 14 | N = int(input()) 15 | d = dict() 16 | 17 | for _ in range(0, N): 18 | name, number = input().split() 19 | d[name] = number 20 | 21 | for _ in range(0, N): 22 | name = input() 23 | if name in d: 24 | print("{}={}".format(name, d[name])) 25 | else: 26 | print("Not found") 27 | -------------------------------------------------------------------------------- /HackerRank/0 - Tutorials/30 Days of Code/Day 9 - Recursion.py: -------------------------------------------------------------------------------- 1 | def factorial(n): 2 | if n == 0: 3 | return 1 4 | else: 5 | return n * factorial(n - 1) 6 | 7 | 8 | n = int(input()) 9 | print(factorial(n)) 10 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/0 - Warmup/1 - Solve Me First.py: -------------------------------------------------------------------------------- 1 | def solve_me_first(a, b): 2 | return a + b 3 | 4 | 5 | num1 = int(input()) 6 | num2 = int(input()) 7 | res = solve_me_first(num1, num2) 8 | print(res) 9 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/0 - Warmup/2 - Simple Array Sum.py: -------------------------------------------------------------------------------- 1 | n = int(input().strip()) 2 | arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] 3 | res = sum(arr) 4 | print(res) -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/0 - Warmup/3 - Compare the Triplets.py: -------------------------------------------------------------------------------- 1 | a = list(map(int, input().split())) 2 | b = list(map(int, input().split())) 3 | 4 | a_score = b_score = 0 5 | 6 | for i in range(len(a)): 7 | if a[i] > b[i]: 8 | a_score += 1 9 | elif a[i] < b[i]: 10 | b_score +=1 11 | else: 12 | pass 13 | 14 | print(a_score, b_score) 15 | 16 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/0 - Warmup/4 - A Very Big Sum.py: -------------------------------------------------------------------------------- 1 | n = int(input().strip()) 2 | arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] 3 | res = sum(arr) 4 | print(res) -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/0 - Warmup/5 - Diagonal Difference.py: -------------------------------------------------------------------------------- 1 | sum_diag1 = 0 2 | sum_diag2 = 0 3 | n = int(input().strip()) 4 | a = [] 5 | for a_i in range(n): 6 | a_t = [int(a_temp) for a_temp in input().strip().split(' ')] 7 | sum_diag1 += a_t[a_i] 8 | sum_diag2 += a_t[(n - 1) - a_i] 9 | # a.append(a_t) 10 | # not really useful... 11 | res = abs(sum_diag1 - sum_diag2) 12 | print(res) 13 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/0 - Warmup/6 - Plus Minus.py: -------------------------------------------------------------------------------- 1 | positive_count = 0 2 | zero_count = 0 3 | negative_count = 0 4 | 5 | n = int(input().strip()) 6 | arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] 7 | for num in arr: 8 | if num > 0: 9 | positive_count += 1 10 | elif num == 0: 11 | zero_count += 1 12 | else: 13 | negative_count += 1 14 | 15 | print(positive_count / n) 16 | print(negative_count / n) 17 | print(zero_count / n) 18 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/0 - Warmup/7 - Staircase.py: -------------------------------------------------------------------------------- 1 | n = int(input().strip()) 2 | s = '#' 3 | for i in range(1, n + 1): 4 | print (" " * (n - i) + s * i) -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/0 - Warmup/8 - Time Conversion.py: -------------------------------------------------------------------------------- 1 | # input e.g. 07:05:45PM 2 | time_string = input().strip() 3 | is_pm = (time_string[8:10] == "PM") 4 | if is_pm: 5 | hours = int(time_string[0:2]) 6 | if hours != 12: 7 | hours += 12 8 | res = format(hours, "02") + time_string[2:8] 9 | print(res) 10 | # then am... 11 | elif time_string[0:2] == "12": 12 | print("00" + time_string[2:8]) 13 | else: 14 | print(time_string[0:8]) 15 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/0 - Warmup/9 - Circular Array Rotation.py: -------------------------------------------------------------------------------- 1 | n, k, q = map(int, input().split()) 2 | a = list(map(int, input().split())) 3 | 4 | for _ in range (q): 5 | m = int(input()) 6 | i = (m - k) % n 7 | print(a[i]) 8 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/0 - Kangaroo.py: -------------------------------------------------------------------------------- 1 | x1, v1, x2, v2 = map(int, input().split()) 2 | 3 | # Note: 0 <= x1 < x2 <= 10000 4 | # x1 + k.v1 = x2 + k.v2 5 | 6 | 7 | if (v2 < v1) and ((x2 - x1) % (v2 - v1)) == 0: 8 | print("YES") 9 | else: 10 | print("NO") 11 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/1 - Divisible Sum Pairs.py: -------------------------------------------------------------------------------- 1 | n, k = map(int, input().split()) 2 | a = list(map(int, input().split())) 3 | 4 | count = 0 5 | counts = [0] * k 6 | 7 | for aj in a: 8 | # ai and aj evenly divisible by k 9 | # => (ai + aj) % k == 0 10 | # => ([ai % k] + [aj % k]) == k or 0 11 | bucket = aj % k 12 | # since i < j 13 | # => ai % k complements aj % k 14 | # => complement: (k - aj % k) % k 15 | complement = (k - bucket) % k 16 | count += counts[complement] 17 | counts[bucket] += 1 18 | 19 | print(count) 20 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/10 - Strange Counter.py: -------------------------------------------------------------------------------- 1 | t = 22#int(input()) 2 | 3 | # 1st cycle: (1, 3), (2, 2), (3, 1) 4 | # 2nd cycle: (4, 6), (5, 5), (6, 4), (7, 3), (8, 2), (9 , 1) 5 | # 3rd cycle: (10, 12), (11, 11), (12, 10), (13, 9), (14, 8)...(21, 1) 6 | 7 | # 3, 6, 12 => 1st cycle item value = 3 * 2 ** cycle (0-based) 8 | # if t is within cycle starting at: 3 * 2 ** cycle 9 | 10 | 11 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/2 - Utopian Tree.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | t = int(input().strip()) 7 | for a0 in range(t): 8 | n = int(input().strip()) 9 | h = 1 10 | e = (n // 2) + 1 11 | s = 1 12 | if (n % 2) == 1: 13 | s = 2 14 | e += 1 15 | h = 2**e - s 16 | print(h) -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/3 - Angry Professor.py: -------------------------------------------------------------------------------- 1 | t = int(input().strip()) 2 | for a0 in range(t): 3 | n, k = map(int, input().strip().split(' ')) 4 | a = input().strip().split(' ') 5 | on_time_count = [int(a_temp) for a_temp in a if int(a_temp) <= 0] 6 | if len(on_time_count) < k: 7 | print("YES") 8 | else: 9 | print("NO") 10 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/4 - Cut The Sticks.py: -------------------------------------------------------------------------------- 1 | n = int(input().strip()) 2 | arr = [int(arr_temp) for arr_temp in input().strip().split(' ')] 3 | arr.sort() 4 | while len(arr) > 0: 5 | print(len(arr)) 6 | m = arr[0] 7 | arr = [a - m for a in arr if ((a - m) > 0)] -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/5 - Encryption.py: -------------------------------------------------------------------------------- 1 | s = input().strip() 2 | s = s.replace(" ", "") 3 | l = len(s) 4 | sl = math.sqrt(l) 5 | r = math.floor(sl) 6 | c = math.ceil(sl) 7 | 8 | if (r * c) < l: 9 | r = c 10 | 11 | for i in range(0, c): 12 | print(s[i : l : c], end = " ") 13 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/6 - Repeated String.py: -------------------------------------------------------------------------------- 1 | s = input() 2 | n = int(input()) 3 | segment_length = len(s) 4 | segment_count = s.count("a") 5 | ratio = n // segment_length 6 | remainder = segment_length - n % segment_length 7 | first_segments_count = ratio * segment_count 8 | last_partial_segment_count = s.count("a", 0, segment_length - remainder) 9 | result = first_segments_count + last_partial_segment_count 10 | print(result) 11 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/7 - Jumping on the Clouds.py: -------------------------------------------------------------------------------- 1 | n = int(input().strip()) 2 | clouds = [int(tmp) for tmp in input().strip().split(' ')] 3 | current = 0 4 | end = n - 1 5 | jumps = 0 6 | while current < end: 7 | if ((current + 2) <= end) and (clouds[current + 2] == 0): 8 | current += 2 9 | jumps += 1 10 | elif clouds[current + 1] == 0: 11 | current += 1 12 | jumps += 1 13 | print(jumps) 14 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/8 - Bigger is Greater.py: -------------------------------------------------------------------------------- 1 | def next_lex_permutation(array): 2 | n = len(array) 3 | i = n - 1 4 | while (i > 0) and array[i - 1] >= array[i]: 5 | i -= 1 6 | 7 | # i is the head index of the suffix 8 | # Are we at the last permutation already? 9 | if i <= 0: 10 | return False 11 | 12 | # Let string[i - 1] be the pivot 13 | # Find the rightmost element that exceeed the pivot 14 | j = n - 1 15 | while array[j] <= array[i - 1]: 16 | j -= 1 17 | # Now the value string[j] will become the new pivot 18 | # Assertion: j >= i 19 | 20 | # Swap the pivot with j 21 | tmp = array[i - 1] 22 | array[i - 1] = array[j] 23 | array[j] = tmp 24 | 25 | # Reverse the suffix 26 | j = n - 1 27 | while i < j: 28 | tmp = array[i] 29 | array[i] = array[j] 30 | array[j] = tmp 31 | i += 1 32 | j -= 1 33 | 34 | # Successfully computed the next permutation 35 | return True 36 | 37 | 38 | ss = bytearray("Hello") 39 | 40 | t = int(input()) 41 | for _ in range(t): 42 | w = input() 43 | a = bytearray(w, "ascii") 44 | if next_lex_permutation(a): 45 | print(a.decode()) 46 | else: 47 | print("no answer") 48 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/9 - Save the Prisoner!.py: -------------------------------------------------------------------------------- 1 | t = int(input()) 2 | 3 | for _ in range(t): 4 | n, m, s = map(int, input().split()) 5 | l = (s - 1 + m) % n 6 | # Cannot be 0, this is 1-base 7 | # Could go with another modulo difference 8 | if l == 0: 9 | l = n 10 | print(l) 11 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/Non-Divisible Subset.py: -------------------------------------------------------------------------------- 1 | n, k = map(int, input().split()) 2 | a = list(map(int, input().split())) 3 | 4 | 5 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/X - Caesar Cypher.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | def is_between(value, min, max): 7 | if (min <= value) and (value <= max): 8 | return True 9 | else: 10 | return False 11 | 12 | 13 | def shift(value, offset, min, max): 14 | return ((value + offset - min) % (max - min + 1)) + min 15 | 16 | 17 | n = int(input().strip()) 18 | s = input().strip() 19 | k = int(input().strip()) 20 | 21 | barr = bytearray(s, "ascii") 22 | 23 | for i in range(0, len(barr)): 24 | b = barr[i] 25 | print(i, barr[i], end=" ") 26 | if is_between(b, 97, 122): 27 | barr[i] = shift(b, k, 97, 122) 28 | elif is_between(b, 65, 90): 29 | barr[i] = shift(b, k, 65, 90) 30 | 31 | print(str(barr, "ascii")) 32 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/X - Chocolate Feast.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | t = int(input().strip()) 7 | for a0 in range(t): 8 | n, c, m = input().strip().split(' ') 9 | n, c, m = [int(n), int(c), int(m)] 10 | nc = n // c 11 | w = nc 12 | while (w >= m): 13 | nc = nc + w // m 14 | w = w % m + w // m 15 | print(nc) -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/X - Find Digits.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | 6 | def finddigits(n): 7 | c = 0 8 | for sd in list(str(n)): 9 | d = int(sd) 10 | if (d != 0) and ((n % d) == 0): 11 | c += 1 12 | return c 13 | 14 | 15 | t = int(input().strip()) 16 | for a0 in range(t): 17 | n = int(input().strip()) 18 | c = finddigits(n) 19 | print(c) 20 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/X - Kaprekar - Numbers.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | def digits(n): 5 | return int(math.log10(n)) + 1 6 | 7 | 8 | # lower bound 9 | p = int(input().strip()) 10 | # upper bound 11 | q = int(input().strip()) 12 | 13 | count = 0 14 | 15 | for n in range(p, q + 1): 16 | n2 = n ** 2 17 | powdig = pow(10, digits(n)) 18 | l = (n2 % powdig) 19 | r = (n2 // powdig) 20 | if (l + r) == n: 21 | print(n, end=" ") 22 | count += 1 23 | if count == 0: 24 | print("INVALID RANGE") 25 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/X - Matrix Rotation.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | import sys 4 | 5 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/X - Service Lane.py: -------------------------------------------------------------------------------- 1 | #!/bin/python3 2 | 3 | n, t = input().strip().split(' ') 4 | n, t = [int(n), int(t)] 5 | width = [int(width_temp) for width_temp in input().strip().split(' ')] 6 | for a0 in range(t): 7 | i, j = input().strip().split(' ') 8 | i, j = [int(i), int(j)] 9 | segment = width[i:j + 1] 10 | print(min(segment)) 11 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/1 - Implementation/X - Sherlock And Squares.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | def sqrt_count(a, b): 5 | sqrt_a = math.sqrt(a) 6 | sqrt_b = math.sqrt(b) 7 | return math.floor(sqrt_b) - math.ceil(sqrt_a) + 1 8 | 9 | 10 | t = int(input().strip()) 11 | for a0 in range(t): 12 | a, b = map(int, input().split()) 13 | c = sqrt_count(a, b) 14 | print(c) 15 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/2 - Strings/1 - Pangrams.py: -------------------------------------------------------------------------------- 1 | import string 2 | 3 | 4 | def is_pangram(s): 5 | occurences = dict() 6 | alphabet = set(string.ascii_lowercase) 7 | for letter in s: 8 | letter = letter.lower() 9 | if letter in alphabet: 10 | if letter in occurences: 11 | occurences[letter] += 1 12 | else: 13 | occurences[letter] = 1 14 | return len(occurences) == len(string.ascii_lowercase) 15 | 16 | 17 | s = input() 18 | if is_pangram(s): 19 | print("pangram") 20 | else: 21 | print("not pangram") 22 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/2 - Strings/2 - Alternating Characters.py: -------------------------------------------------------------------------------- 1 | def minimum_reductions(s): 2 | count = 0 3 | previous = s[0] 4 | for current in s[1::]: 5 | if previous == current: 6 | count += 1 7 | else: 8 | previous = current 9 | return count 10 | 11 | 12 | T = int(input()) 13 | for _ in range(T): 14 | s = input() 15 | print(minimum_reductions(s)) 16 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/2 - Strings/3 - The Love-Letter Mystery.py: -------------------------------------------------------------------------------- 1 | def minimum_reductions(s): 2 | n = len(s) 3 | count = 0 4 | for i in range(n // 2): 5 | left = ord(s[i]) 6 | right = ord(s[(n - 1) - i]) 7 | if left != right: 8 | if left > right: 9 | count += left - right 10 | else: 11 | count += right - left 12 | return count 13 | 14 | 15 | T = int(input()) 16 | for _ in range(T): 17 | s = input() 18 | print(minimum_reductions(s)) 19 | 20 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/2 - Strings/4 - Gemstones.py: -------------------------------------------------------------------------------- 1 | def count_gem_elements(gems): 2 | gem_sets = map(set, gems) 3 | common_gem_elements = intersection(gem_sets) 4 | return len(common_gem_elements) 5 | 6 | 7 | N = int(input()) 8 | gems = [input() for i in range(N)] 9 | print(count_gem_elements(gems)) 10 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/2 - Strings/5 - Funny String.py: -------------------------------------------------------------------------------- 1 | def is_funny(S): 2 | N = len(S) 3 | for i in range(1, N): 4 | Si = ord(S[i]) 5 | Si_1 = ord(S[i - 1]) 6 | Ri_1 = ord(S[(N - 1) - i]) 7 | Ri = ord(S[(N - 1) - (i - 1)]) 8 | Sdiff = abs(Si - Si_1) 9 | Rdiff = abs(Ri - Ri_1) 10 | if Sdiff != Rdiff: 11 | return False 12 | return True 13 | 14 | 15 | T = int(input()) 16 | for _ in range(T): 17 | S = input() 18 | if is_funny(S): 19 | print("Funny") 20 | else: 21 | print("Not Funny") 22 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/2 - Strings/6 - Anagram.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | 4 | def minimum_changes(S): 5 | length = len(S) 6 | if (length % 2) != 0: 7 | return -1 8 | else: 9 | half_length = length // 2 10 | s1_counter = Counter(S[:half_length]) 11 | s2_counter = Counter(S[half_length:]) 12 | difference_counter = s1_counter - s2_counter 13 | return sum(difference_counter.values()) 14 | 15 | 16 | T = int(input()) 17 | for _ in range(T): 18 | S = input() 19 | print(minimum_changes(S)) 20 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/2 - Strings/7 - Palindrome Index.py: -------------------------------------------------------------------------------- 1 | def minimum_palindrome(s): 2 | length = len(s) 3 | count = 0 4 | for i in range(length): 5 | if s[i] != s[(length - 1) - i]: 6 | count += 1 7 | return True 8 | 9 | 10 | T = int(input()) 11 | for i in range(T): 12 | S = input() 13 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/2 - Strings/Super Reduced String.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | import re 3 | 4 | 5 | 6 | prev, curr = "", "aaabccddd" 7 | 8 | while prev != curr: 9 | prev, curr = curr, re.sub("(.)\1", "", curr) 10 | 11 | print (curr) 12 | 13 | 14 | def reduce(s): 15 | d = deque() 16 | for c in s: 17 | if d and d[-1] == c: 18 | d.pop() 19 | else: 20 | d.append() 21 | print(*d if d else "Empty String", sep="") 22 | 23 | 24 | 25 | 26 | 27 | 28 | sa = ["aaabccddd", "abd", "baab"] 29 | 30 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/3 - Sorting/0 - Intro to Tutorial Challenges.py: -------------------------------------------------------------------------------- 1 | # This is a simple challenge to get things started. 2 | # Given a sorted array (a) and a number (v), can you print the index location of V in the array? 3 | def index_of(values, target): 4 | for i in range(len(values)): 5 | if a[i] == v: 6 | return i 7 | return -1 8 | 9 | 10 | v = int(input()) 11 | n = int(input()) 12 | a = [int(token) for token in input().split()] 13 | result = index_of(a, v) 14 | print(result) 15 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/3 - Sorting/1 - Insertion Sort - Part 1.py: -------------------------------------------------------------------------------- 1 | # Given a sorted list with an unsorted number e in the rightmost cell, 2 | # can you write some simple code to insert e into the list so that it remains sorted? 3 | def last_insertion_sort(sorted_array, value): 4 | item = a[-1] 5 | i = n - 1 6 | while (item >= value) and (i > 0): 7 | i -= 1 8 | item = a[i] 9 | if item < value: 10 | a[i + 1] = value 11 | else: 12 | a[i + 1] = a[i] 13 | print(*a, sep=" ") 14 | if item >= value: 15 | a[0] = value 16 | print(*a, sep=" ") 17 | 18 | 19 | n = int(input()) 20 | a = [int(token) for token in input().split()] 21 | e = a.pop() 22 | a.append(a[-1]) 23 | last_insertion_sort(a, e) 24 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/6 - Greedy/1 - Grid Challenge.py: -------------------------------------------------------------------------------- 1 | t = int(input()) 2 | 3 | for _ in range(t): 4 | n = int(input()) 5 | g = [] 6 | for __ in range(n): 7 | l = input() 8 | g.append(l) 9 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/6 - Greedy/2 - Luck Challenge.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/natalie-o-perret/coding-challenges/bd024b82d7c410067f0cdb217e9613d62a9ce783/HackerRank/1 - Algorithms/6 - Greedy/2 - Luck Challenge.py -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/6 - Greedy/3 - Beautiful Pairs.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/natalie-o-perret/coding-challenges/bd024b82d7c410067f0cdb217e9613d62a9ce783/HackerRank/1 - Algorithms/6 - Greedy/3 - Beautiful Pairs.py -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/6 - Greedy/4 - Sherlock And The Beast.py: -------------------------------------------------------------------------------- 1 | def biggest_decent_number(n): 2 | if not (n % 3) != 0: 3 | return n * "5" 4 | else: 5 | if n % 3: 6 | pass 7 | 8 | 9 | t = int(input().strip()) 10 | for a0 in range(t): 11 | n = int(input().strip()) 12 | print(biggest_decent_number(n)) 13 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/6 - Greedy/5 - Jim and the Orders.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/natalie-o-perret/coding-challenges/bd024b82d7c410067f0cdb217e9613d62a9ce783/HackerRank/1 - Algorithms/6 - Greedy/5 - Jim and the Orders.py -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/8 - Bit Manipulation/1 - Lonely Integer.py: -------------------------------------------------------------------------------- 1 | def lonely_integer(m): 2 | answer = 0 3 | for x in m: 4 | answer = answer ^ x 5 | return answer 6 | 7 | 8 | a = int(input()) 9 | b = map(int, input().strip().split(" ")) 10 | print(lonely_integer(b)) 11 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/8 - Bit Manipulation/2 - Maximize XOR.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | def max_xor(left, right): 5 | # First bit to 1 is where left and right start to differ. 6 | # e.g. 4 ^ 2 = 100 ^ 010 = 111 7 | result = left ^ right 8 | # Let's take the bits representation length associated to the result 9 | # e.g. = len(111) = 3 10 | bit_length = math.floor(math.log(result, 2) + 1) 11 | # Then we get the number related number to this 1 bits long representation 12 | # aka the maxmimum, e.g. 2 ** 3 - 1 = 8 - 1 = 7 13 | maximum = int(2 ** bit_length) - 1 14 | return maximum 15 | 16 | 17 | left = int(input()) 18 | right = int(input()) 19 | print(max_xor(left, right)) 20 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/8 - Bit Manipulation/3 - Counter Game.py: -------------------------------------------------------------------------------- 1 | def counter_game(n): 2 | #return "Richard" 3 | #return "Louise" 4 | pass 5 | 6 | 7 | t = int(input().strip()) 8 | for a0 in range(t): 9 | n = int(input().strip()) 10 | winner = counter_game(n) 11 | print(winner) 12 | 13 | -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/8 - Bit Manipulation/4 - Sansa and XOR.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/natalie-o-perret/coding-challenges/bd024b82d7c410067f0cdb217e9613d62a9ce783/HackerRank/1 - Algorithms/8 - Bit Manipulation/4 - Sansa and XOR.py -------------------------------------------------------------------------------- /HackerRank/1 - Algorithms/8 - Bit Manipulation/5 - Flipping Bits.py: -------------------------------------------------------------------------------- 1 | def flip_bits(n): 2 | return ~n + 2 ** 32 3 | 4 | 5 | t = int(input().strip()) 6 | for a0 in range(t): 7 | n = int(input().strip()) 8 | flippedn = flip_bits(n) 9 | print(flippedn) 10 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/1 - Arrays/1 - Arrays - DS.py: -------------------------------------------------------------------------------- 1 | """ 2 | An array is a type of data structure that stores elements of the same type 3 | in a contiguous block of memory. 4 | 5 | In an array, A, of size N, each memory location has some unique index, i (where 0 <= i < N), 6 | that can be referenced as A[i] (you may also see it written as Ai). 7 | 8 | Given an array A, of size N, of integers: 9 | print each element in reverse order as a single line of space-separated integers. 10 | """ 11 | 12 | N = int(input().strip()) 13 | A = input().split(' ') 14 | print(" ".join(A[::-1])) 15 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/1 - Arrays/2 - 2D Array - DS.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given a 2D Array, A, we define an hourglass in to be a subset of values 3 | with indices falling in this pattern in A's graphical representation: 4 | a b c 5 | d 6 | e f g 7 | There are hourglasses in A, and an hourglass sum is the sum of an hourglass' values. 8 | """ 9 | 10 | A = [] 11 | for arr_i in range(6): 12 | arr_t = [int(arr_temp) for arr_temp in input().strip().split(' ')] 13 | A.append(arr_t) 14 | 15 | smax = -9 * 7 16 | 17 | for row in range(len(A) - 2): 18 | for column in range(len(A[row]) - 2): 19 | tl = A[row][column] 20 | tc = A[row][column + 1] 21 | tr = A[row][column + 2] 22 | mc = A[row + 1][column + 1] 23 | bl = A[row + 2][column] 24 | bc = A[row + 2][column + 1] 25 | br = A[row + 2][column + 2] 26 | s = tl + tc + tr + mc + bl + bc + br 27 | smax = max(s, smax) 28 | 29 | print(smax) 30 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/1 - Arrays/3 - Dynamic Array.py: -------------------------------------------------------------------------------- 1 | """ 2 | Create a list, seqList, of N empty sequences, where each sequence is indexed from 0 to N-1. 3 | The elements within each of the N sequences also use 0-indexing. 4 | Create an integer, lastAns, and initialize it to 0. 5 | The types of queries that can be performed on your list of sequences (seqList) are described below: 6 | 1] Query: 1 . y 7 | 1] Find the sequence, seq, at index ((x xor lastAns) % N) in seqList. 8 | 2] Append integer y to sequence seq 9 | 2] Query: 2 . y 10 | 1] Find the sequence, seq, at index ((x xor lastAns) % N) in seqList. 11 | 2] Find the value of element y % size in seq (where size is the size of seq) and assign it to lastAns. 12 | 3] Print the new value of lastAns on a new line 13 | """ 14 | 15 | N, Q = map(int, input().split()) 16 | lastAns = 0 17 | seqList = [[] for _ in range(N)] 18 | 19 | for __ in range(Q): 20 | q, x, y = map(int, input().split()) 21 | index = (x ^ lastAns) % N 22 | seq = seqList[index] 23 | if q == 1: 24 | seq.append(y) 25 | elif q == 2: 26 | size = len(seq) 27 | lastAns = seq[y % size] 28 | print(lastAns) 29 | else: 30 | raise ValueError() 31 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/1 - Arrays/4 - Array Left Rotation.py: -------------------------------------------------------------------------------- 1 | """ 2 | Given an array of size N and a number d, rotate the array to the left by d 3 | i.e. shift the array elements to the left by d. 4 | Ex: The array [1, 2, 3, 4, 5] after rotating by 2 gives [3, 4, 5, 1, 2]. 5 | """ 6 | 7 | N, d = map(int, input().split()) 8 | a = list(input().split()) 9 | r = a[d % N : N] + a[0 : d % N] 10 | print(*r, sep=" ") 11 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/1 - Arrays/5 - Sparse Arrays.py: -------------------------------------------------------------------------------- 1 | """ 2 | There are N strings. 3 | Each string's length is no more than 20 characters. 4 | There are also Q queries. 5 | For each query, you are given a string. 6 | You need to find out how many times this string occurred previously. 7 | """ 8 | 9 | 10 | def count(target, source): 11 | counter = 0 12 | for item in source: 13 | if item == target: 14 | counter += 1 15 | return counter 16 | 17 | 18 | N = int(input()) 19 | strings = [] 20 | for _ in range(N): 21 | string = input() 22 | strings.append(string) 23 | 24 | Q = int(input()) 25 | for __ in range(Q): 26 | query = input() 27 | occurrences = count(query, strings) 28 | print(occurrences) 29 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/2 - Linked Lists/1 - Print the Elements of a Linked List.py: -------------------------------------------------------------------------------- 1 | """ 2 | Print elements of a linked list on console. 3 | Head input could be None as well for empty list 4 | """ 5 | from . import Node 6 | 7 | 8 | def print_list_iterative(head): 9 | if head: 10 | current = head 11 | while current: 12 | print(current.data) 13 | current = current.next 14 | 15 | 16 | def print_list_recursive(head): 17 | if head: 18 | print(head.data) 19 | print_list_recursive(head.next) 20 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/2 - Linked Lists/10 - Get Node Value.py: -------------------------------------------------------------------------------- 1 | """ 2 | You’re given the pointer to the head node of a linked list and a specific position. 3 | Counting backwards from the tail node of the linked list, get the value of the node at the given position. 4 | A position of 0 corresponds to the tail, 1 corresponds to the node before the tail and so on. 5 | """ 6 | from . import Node 7 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/2 - Linked Lists/2 - Insert a Node at the Tail of a Linked List.py: -------------------------------------------------------------------------------- 1 | """ 2 | Insert Node at the end of a linked list. 3 | Head pointer input could be None as well for empty list 4 | """ 5 | from . import Node 6 | 7 | 8 | def tail_insert_iterative(head, data): 9 | node = Node(data) 10 | if head: 11 | current = head 12 | while current.next: 13 | current = current.next 14 | current.next = node 15 | else: 16 | head = node 17 | return head 18 | 19 | 20 | def tail_insert_recursive(head, data): 21 | if not head: 22 | return Node(data) 23 | else: 24 | if head.next: 25 | tail_insert_recursive(head.next, data) 26 | else: 27 | head.next = Node(data, None) 28 | return head 29 | 30 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/2 - Linked Lists/3 - Insert a node at the head of a linked list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Insert Node at the beginning of a linked list head input could be None as well for empty list. 3 | """ 4 | from . import Node 5 | 6 | 7 | def insert(head, data): 8 | node = Node(data) 9 | node.next = head 10 | return node 11 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/2 - Linked Lists/4 - Delete a Node.py: -------------------------------------------------------------------------------- 1 | """ 2 | Delete Node at a given position in a linked list. 3 | """ 4 | from . import Node 5 | 6 | 7 | def delete_iterative(head, position): 8 | if head: 9 | if position == 0: 10 | head = head.next 11 | else: 12 | previous = None 13 | current = head 14 | current_position = 0 15 | while (current_position < position) and (current.next is not None): 16 | previous = current 17 | current = current.next 18 | current_position += 1 19 | previous.next = current.next 20 | return head 21 | 22 | 23 | def delete_recursive(head, position): 24 | if position == 0: 25 | return head.next 26 | else: 27 | head.next = delete_recursive(head.next, position - 1) 28 | return head 29 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/2 - Linked Lists/5 - Insert a node at a specific position in a linked list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Insert Node at the end of a linked list head input could be None as well for empty list 3 | """ 4 | from . import Node 5 | 6 | 7 | # This is a "method-only" submission. 8 | # You only need to complete this method. 9 | def insert(head, data, position): 10 | node = Node(data) 11 | if not head: 12 | head = node 13 | elif position == 0: 14 | node.next = head 15 | head = node 16 | else: 17 | previous = None 18 | current = head 19 | current_position = 0 20 | while (current_position < position) and current.next: 21 | previous = current 22 | current = current.next 23 | current_position += 1 24 | previous.next = node 25 | node.next = current 26 | return head 27 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/2 - Linked Lists/6 - Print in Reverse.py: -------------------------------------------------------------------------------- 1 | """ 2 | Print elements of a linked list in reverse order as standard output. 3 | Head could be None as well for empty list. 4 | """ 5 | from . import Node 6 | 7 | 8 | def print_reverse_iterative(head): 9 | if head: 10 | stack = [head] 11 | while stack[-1].next: 12 | node = stack[-1] 13 | stack.append(node.next) 14 | while stack: 15 | node = stack.pop() 16 | print(node.data) 17 | 18 | 19 | def print_reverse_recursive(head): 20 | if head: 21 | print_reverse_iterative(head.next) 22 | print(head.data) 23 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/2 - Linked Lists/7 - Reverse a linked list.py: -------------------------------------------------------------------------------- 1 | """ 2 | Reverse a linked list, head could be None as well for empty list 3 | Return back the head of the linked list in the below method. 4 | """ 5 | from . import Node 6 | 7 | 8 | def reverse_iterative(head): 9 | # e.g. A > B > C > D 10 | if head: 11 | current_node = head # current = A 12 | next_node = current_node.next # next = A.next = B 13 | current_node.next = None # A > None 14 | while next_node: 15 | tmp = next_node.next # tmp = B.next = C 16 | next_node.next = current_node # B.next = current = A 17 | head = current_node = next_node # head = current = B 18 | next_node = tmp # next = tmp = C 19 | return head 20 | 21 | 22 | def reverse_stack(head): 23 | # e.g. A > B > C > D 24 | if head: 25 | stack = [head] 26 | while stack[-1].next: 27 | node = stack[-1] 28 | stack.append(node.next) 29 | # stack = [D, C, B, A] 30 | head = stack.pop() # head = D 31 | current = head # current = head = D 32 | while stack: 33 | node = stack.pop() # 34 | current.next = node 35 | current = current.next 36 | current.next = None 37 | return head 38 | 39 | 40 | def reverse_recursive(head): 41 | if not head: 42 | return head 43 | else: 44 | head = reverse_recursive(head.next) 45 | return head 46 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/2 - Linked Lists/8 - Compare two linked lists.py: -------------------------------------------------------------------------------- 1 | """ 2 | Merge two linked list head could be None as well for empty list. 3 | Return back the head of the linked list in the below method. 4 | """ 5 | from . import Node 6 | 7 | 8 | def compare_recursive(head_a, head_b): 9 | if not head_a and not head_b: 10 | # return True 11 | return 1 12 | elif (head_a and head_b) and (head_a.data == head_b.data): 13 | return compare_recursive(head_a.next, head_b.next) 14 | else: 15 | # return False 16 | return 0 17 | 18 | 19 | def compare_iterative(head_a, head_b): 20 | node_a = head_a 21 | node_b = head_b 22 | while True: 23 | if not node_a and not node_b: 24 | # return True 25 | return 1 26 | elif (node_a and node_b) and (node_a.data == node_b.data): 27 | node_a = node_a.next 28 | node_b = node_b.next 29 | else: 30 | # return False 31 | return 0 32 | 33 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/2 - Linked Lists/9 - Merge two sorted linked lists.py: -------------------------------------------------------------------------------- 1 | """ 2 | Merge two sorted linked lists. 3 | Head could be None as well for empty list 4 | """ 5 | from . import Node 6 | 7 | 8 | def merge_lists_iterative(head_a, head_b): 9 | node_a = head_a 10 | node_b = head_b 11 | pass 12 | 13 | 14 | def merge_lists_recursive(head_a, head_b): 15 | if not head_a and not head_b: 16 | pass 17 | 18 | 19 | # 1 -> 3 -> 5 -> 6 -> NULL 20 | # 2 -> 4 -> 7 -> NULL 21 | 22 | head_a = Node(1) 23 | head_a.next = Node(3) 24 | head_a.next.next = Node(5) 25 | head_a.next.next.next = Node(6) 26 | 27 | head_b = Node(2) 28 | head_b.next = Node(4) 29 | head_b.next.next = Node(7) 30 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/2 - Linked Lists/Node.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | def __init__(self, data=None, next_node=None): 3 | self.data = data 4 | self.next = next_node 5 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/3 - Trees/1 - Preorder Traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Complete the preOrder function in your editor below, which has parameter: a pointer to the root of a binary tree. 3 | It must print the values in the tree's preorder traversal as a single line of space-separated values. 4 | """ 5 | from . import Node 6 | 7 | 8 | def traverse_pre_order_recursive(root, action=print): 9 | if root: 10 | action(root.data, end=" ") 11 | traverse_pre_order_recursive(root.left, action) 12 | traverse_pre_order_recursive(root.right, action) 13 | 14 | 15 | def traverse_pre_order_iterative(root, action=print): 16 | if root: 17 | stack = [root] 18 | while stack: 19 | node = stack.pop() 20 | action(node.data, end=" ") 21 | if node.right: 22 | stack.append(node.right) 23 | if node.left: 24 | stack.append(node.left) 25 | 26 | 27 | root = Node("A") 28 | root.left = Node("B") 29 | root.left.left = Node("C") 30 | root.left.right = Node("D") 31 | root.right = Node("E") 32 | root.right.left = Node("G") 33 | root.right.right = Node("F") 34 | 35 | traverse_pre_order_iterative(root) 36 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/3 - Trees/2 - Inorder Traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Complete the preOrder function in your editor below, which has parameter: a pointer to the root of a binary tree. 3 | It must print the values in the tree's inorder traversal as a single line of space-separated values. 4 | """ 5 | from . import Node 6 | 7 | 8 | class BinaryTreeNode(object): 9 | def __init__(self, data=None, left=None, right=None): 10 | self.data = data 11 | self.left = left 12 | self.right = right 13 | 14 | 15 | def traverse_in_order_recursive(root, action=print): 16 | if root: 17 | traverse_in_order_recursive(root.left, action) 18 | print(root.data, end=" ") 19 | traverse_in_order_recursive(root.right, action) 20 | 21 | 22 | def traverse_in_order_iterative(root, action=print): 23 | if root: 24 | stack = [root] 25 | node = root 26 | while node: 27 | if node.left: 28 | stack.append(node) 29 | node = node.left 30 | else: 31 | action(node.data) 32 | node = stack.pop() 33 | 34 | 35 | root = BinaryTreeNode("A") 36 | root.left = BinaryTreeNode("B") 37 | root.left.left = BinaryTreeNode("C") 38 | root.left.right = BinaryTreeNode("D") 39 | root.right = BinaryTreeNode("E") 40 | root.right.left = BinaryTreeNode("G") 41 | root.right.right = BinaryTreeNode("F") 42 | 43 | traverse_in_order_iterative(root) 44 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/3 - Trees/3 - Postorder Traversal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Complete the preOrder function in your editor below, which has parameter: a pointer to the root of a binary tree. 3 | It must print the values in the tree's postorder traversal as a single line of space-separated values. 4 | """ 5 | 6 | 7 | def traverse_in_order_recursive(root): 8 | if root: 9 | traverse_in_order_recursive(root.left) 10 | traverse_in_order_recursive(root.right) 11 | print(root.data, end=" ") 12 | 13 | 14 | def traverse_in_order_iterative(root): 15 | if root: 16 | stack = [root] 17 | node = root 18 | while node: 19 | if node.left: 20 | stack.append(node) 21 | node = node.left 22 | else: 23 | print(node.data) 24 | node = stack.pop() 25 | 26 | 27 | root = Node("A") 28 | root.left = Node("B") 29 | root.left.left = Node("C") 30 | root.left.right = Node("D") 31 | root.right = Node("E") 32 | root.right.left = Node("G") 33 | root.right.right = Node("F") 34 | 35 | traverse_in_order_iterative(root) 36 | -------------------------------------------------------------------------------- /HackerRank/2 - Data Structures/3 - Trees/Node.py: -------------------------------------------------------------------------------- 1 | class Node(object): 2 | def __init__(self, data=None, left=None, right=None): 3 | self.data = data 4 | self.left = left 5 | self.right = right -------------------------------------------------------------------------------- /HackerRank/3 - Mathematics/Fundamentals/0 - Find Point.py: -------------------------------------------------------------------------------- 1 | # Compute S point coordinates such as being the symmetry point of P via Q 2 | 3 | t = int(input()) 4 | for _ in range(t): 5 | px, py, qx, qy = map(int, input().split()) 6 | sx = qx + (qx - px) 7 | sy = qy + (qy - py) 8 | print(sx, sy) 9 | -------------------------------------------------------------------------------- /HackerRank/3 - Mathematics/Fundamentals/1 - Maximum Draws.py: -------------------------------------------------------------------------------- 1 | # Maximum (worst case) sock draws to get a first pair of socks (i.e. same colors) 2 | 3 | t = int(input()) 4 | for _ in range(t): 5 | n = int(input()) 6 | # e.g. a1, b1, c1, a2, b2, c2 7 | # In the worst case scenario: 8 | # => a1, b1, c1, a2 => (a1, a2) is a pair after 4 draws 9 | # Comes from: 2 * n // 2 + 1 = n + 1 10 | print(n + 1) 11 | -------------------------------------------------------------------------------- /HackerRank/3 - Mathematics/Fundamentals/2 - Handshake.py: -------------------------------------------------------------------------------- 1 | # Number of distinguisble handshake between 2 differents person among n individuals 2 | # Please note that (a handshake b) == (b handshake a) 3 | # => considered as only 1 handshake 4 | import math 5 | 6 | 7 | def combination(n, r): 8 | result = int(math.factorial(n) / (math.factorial(r) * math.factorial(n - r))) 9 | return result 10 | 11 | 12 | t = int(input()) 13 | for _ in range(t): 14 | n = int(input()) 15 | if n >= 2: 16 | print(combination(n, 2)) 17 | else: 18 | print(0) 19 | -------------------------------------------------------------------------------- /HackerRank/3 - Mathematics/Fundamentals/3 - Possible Path.py: -------------------------------------------------------------------------------- 1 | def gcd(u, v): 2 | while v > 0: 3 | tmp = v 4 | v = u % v 5 | u = tmp 6 | return u 7 | 8 | 9 | t = int(input()) 10 | for _ in range(t): 11 | a, b, x, y = map(int, input().split()) 12 | # gcd definitions says: 13 | # gcd (a + m * b, b) = gcd(a, b) 14 | # such as m being an integer 15 | # hence: 16 | # gcd (a + b, b) 17 | # gcd (a - b, b) 18 | # gcd (a, a + b) 19 | # gcd (a, a - b) 20 | # must all be equal to gcd(a, b) 21 | # thus it means it's possible to 22 | # move from (a,b) point to (x, y) point 23 | # iff gcd(a, b) == gcd(x, y) 24 | if gcd(a, b) == gcd(x, y): 25 | print("YES") 26 | else: 27 | print("NO") 28 | -------------------------------------------------------------------------------- /HackerRank/3 - Mathematics/Fundamentals/4 - Leonardos Prime Factors.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | def is_prime(x): 5 | if x < 2: 6 | return False 7 | if x == 2: 8 | return True 9 | elif x == 3: 10 | return True 11 | else: # x > 3: 12 | if x % 2 == 0: 13 | return False 14 | if x % 3 == 0: 15 | return False 16 | # We can now avoid multiples of 2 and 3 17 | # Starting at 5 and incrementing by 2 and 4 18 | # e.g. 5, 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37, etc. 19 | max_divisor = int(math.sqrt(x)) + 1 20 | increment = 2 21 | divisor = 5 22 | while divisor <= max_divisor: 23 | if x % divisor == 0: 24 | return False 25 | divisor += increment 26 | # Change 2 into 4 and vice-versa 27 | increment = 6 - increment 28 | return True 29 | 30 | 31 | # The trick lies if that a smaller number than n 32 | # can have bigger number of unique prime factors 33 | # So it's all about fetching all the prime numbers 34 | # then multiply them to check whether their product 35 | # is greater or equal to n 36 | def count_unique_primes_count_for_product_lesser_or_equal_to(n): 37 | product = 1 38 | count = 0 39 | for i in range(2, n + 1): 40 | if is_prime(i): 41 | if (product * i) <= n: 42 | product *= i 43 | count += 1 44 | else: 45 | break 46 | return count 47 | 48 | 49 | q = int(input()) 50 | for _ in range(q): 51 | n = int(input()) 52 | result = count_unique_primes_count_for_product_lesser_or_equal_to(n) 53 | print(result) 54 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Built-Ins/0 - Zipped!.py: -------------------------------------------------------------------------------- 1 | N, X = map(int, input().split()) 2 | [print(sum(marks) / len(marks)) for marks in zip(*[list(map(float, input().split())) for _ in range(X)])] 3 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Built-Ins/1 - Input().py: -------------------------------------------------------------------------------- 1 | 2 | # Python 2.x: x, k = map(int, raw_input().split()) 3 | x, k = map(int, input().split()) 4 | result = input() 5 | print(result == k) 6 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Built-Ins/2 - Python Evaluation.py: -------------------------------------------------------------------------------- 1 | eval(input()) 2 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Built-Ins/3 - Sort Data.py: -------------------------------------------------------------------------------- 1 | N, M = map(int, input().split()) 2 | rows, k = [list(map(int, input().split())) for _ in range(N)], int(input()) 3 | [print(*row) for row in sorted(rows, key = lambda x: x[k])] 4 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Built-Ins/4 - Any Or All..py: -------------------------------------------------------------------------------- 1 | N, X = int(input()), input().split() 2 | print(all(map(lambda x: int(x) >= 0, X)) and any(map(lambda x: x == "".join(reversed(x)), X))) 3 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Built-Ins/5 - ginortS.py: -------------------------------------------------------------------------------- 1 | # order = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1357902468' 2 | # print(*sorted(input(), key = order.index), sep = "") 3 | sort = lambda x: (x.isdigit(), x.isdigit() and int(x) % 2 == 0, x.isupper(), x.islower(), x) 4 | print(*(sorted(input(), key = sort)), sep = "") 5 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Classes/0 - Dealing With Complex Numbers.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | class Complex: 5 | def __init__(self, x = 0, y = 0): 6 | self.x = x 7 | self.y = y 8 | 9 | def __str__(self): 10 | if self.y >= 0: 11 | return "{:.2f}+{:.2f}i".format(self.x, self.y) 12 | else: 13 | return "{:.2f}{:.2f}i".format(self.x, self.y) 14 | 15 | def __add__(self, o): 16 | x = self.x + o.x 17 | y = self.y + o.y 18 | r = Complex(x, y) 19 | return r 20 | 21 | def __sub__(self, o): 22 | x = self.x - o.x 23 | y = self.y - o.y 24 | r = Complex(x, y) 25 | return r 26 | 27 | def __mul__(self, o): 28 | x = self.x * o.x - self.y * o.y 29 | y = self.x * o.y + self.y * o.x 30 | r = Complex(x, y) 31 | return r 32 | 33 | def __truediv__(self, o): 34 | x = (self.x * o.x + self.y * o.y) / (o.x**2 + o.y**2) 35 | y = (self.y * o.x - self.x * o.y) / (o.x**2 + o.y**2) 36 | r = Complex(x, y) 37 | return r 38 | 39 | def __abs__(self): 40 | x = math.sqrt(self.x**2 + self.y**2) 41 | r = Complex(x) 42 | return r 43 | 44 | 45 | Cr, Ci = map(float, input().split()) 46 | Dr, Di = map(float, input().split()) 47 | C = Complex(Cr, Ci) 48 | D = Complex(Dr, Di) 49 | 50 | print(C + D) 51 | print(C - D) 52 | print(C * D) 53 | print(C / D) 54 | print(abs(C)) 55 | print(abs(D)) 56 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Classes/1 - Find The Torsional Angle.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | class Point3D(object): 5 | def __init__(self, x=0, y=0, z=0): 6 | self.x = x 7 | self.y = y 8 | self.z = z 9 | 10 | def __repr__(self): 11 | return self.__str__() 12 | 13 | def __str__(self): 14 | return "{:.2f}".format(self.x, self.y, self.y) 15 | 16 | 17 | class Vector3D(object): 18 | def __init__(self, start_point=Point3D(), stop_point=Point3D()): 19 | self.x = stop_point.x - start_point.x 20 | self.y = stop_point.y - start_point.y 21 | self.z = stop_point.z - start_point.z 22 | 23 | def dot_product(self, other): 24 | r = (self.x * other.x) + (self.y * other.y) + (self.z * other.z) 25 | return r 26 | 27 | def cross_product(self, other): 28 | r = Vector3D() 29 | r.x = self.y * other.z - self.z * other.y 30 | r.y = self.z * other.x - self.x * other.z 31 | r.z = self.x * other.y - self.y * other.x 32 | return r 33 | 34 | def distance_to(self, other): 35 | r = math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2 + (self.z - other.z) ** 2) 36 | return r 37 | 38 | def norm(self): 39 | r = self.distance_to(Vector3D()) 40 | return r 41 | 42 | def __add__(self, other): 43 | r = Vector3D() 44 | r.x = self.x + other.x 45 | r.y = self.y + other.y 46 | r.z = self.z + other.z 47 | return r 48 | 49 | def __sub__(self, other): 50 | r = Vector3D() 51 | r.x = self.x - other.x 52 | r.y = self.y - other.y 53 | r.z = self.z - other.z 54 | return r 55 | 56 | def __mul__(self, other): 57 | return self.cross_product(other) 58 | 59 | def __abs__(self): 60 | return self.norm() 61 | 62 | 63 | # Points 64 | A = Point3D(*list(map(float, input().split()))) 65 | B = Point3D(*list(map(float, input().split()))) 66 | C = Point3D(*list(map(float, input().split()))) 67 | D = Point3D(*list(map(float, input().split()))) 68 | 69 | # Vectors 70 | AB = Vector3D(A, B) 71 | BC = Vector3D(B, C) 72 | CD = Vector3D(C, D) 73 | 74 | # Planes: ABC and BCD 75 | X = AB * BC 76 | Y = BC * CD 77 | 78 | # Angle 79 | PHIrad = math.acos(X.dot_product(Y) / (abs(X) * abs(Y))) 80 | PHIdeg = math.degrees(PHIrad) 81 | 82 | print("{:.2f}".format(PHIdeg)) 83 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Collections/1 - Collections.Counter.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | X = int(input()) 4 | sizes = Counter(map(int, input().split())) 5 | N = int(input()) 6 | money = 0 7 | for i in range(N): 8 | size, price = map(int, input().split()) 9 | if sizes[size] > 0: 10 | sizes[size] -= 1 11 | money += price 12 | print(money) -------------------------------------------------------------------------------- /HackerRank/6 - Python/Collections/2 - DefaultDict Tutorial.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | n, m = map(int, input().split()) 4 | A = defaultdict(list) 5 | for i in range(1, n + 1): 6 | A[input()].append(i) 7 | for _ in range(m): 8 | key = input() 9 | if key in A: 10 | print(*A[key], sep=" ") 11 | else: 12 | print(-1) 13 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Collections/3 - Collections.NamedTuple.py: -------------------------------------------------------------------------------- 1 | import statistics 2 | 3 | # N = int(input()) 4 | # columns = input().split() 5 | # Student = namedtuple("Student", columns) 6 | # students = [] 7 | # for i in range(N): 8 | # students.append(Student(*input().split())) 9 | # average = statistics.mean([float(student.MARKS) for student in students]) 10 | # print(average) 11 | 12 | # 2 lines version below... 13 | N, marks_index = int(input()), input().split().index("MARKS") 14 | print(statistics.mean([float(input().split()[marks_index]) for i in range(N)])) 15 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Collections/4 - Collections.OrderedDict.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | 3 | items = OrderedDict() 4 | N = int(input()) 5 | for _ in range(N): 6 | line = input().rpartition(" ") 7 | price = int(line[2]) 8 | name = line[0] 9 | # if (name in items): 10 | # items[name] += price 11 | # else: 12 | # items[name] = price 13 | # Same as above... in one line 14 | items[name] = items.get(name, 0) + price 15 | print (*[" ".join((key, str(items[key]))) for key in items], sep = "\n") 16 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Collections/5 - Word Order.py: -------------------------------------------------------------------------------- 1 | from collections import OrderedDict 2 | 3 | words = OrderedDict() 4 | n = int(input()) 5 | for _ in range(n): 6 | key = input() 7 | words[key] = words.get(key, 0) + 1 8 | print (len(words)) 9 | print (*[str(words[key]) for key in words], sep = " ") 10 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Collections/6 - Collections.Deque.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | d = deque() 4 | N = int(input()) 5 | for _ in range(N): 6 | cmd, *args = input().split() 7 | getattr(d, cmd)(*args) 8 | print (*[item for item in d], sep = " ") 9 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Collections/7 - Piling Up!.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | T = int(input()) 4 | for t in range(T): 5 | n = int(input()) 6 | lengths = deque(map(int, input().split())) 7 | top = max(lengths) 8 | while len(lengths) > 0: 9 | left = lengths[0] 10 | right = lengths[-1] 11 | if (right >= left) and (right <= top): 12 | top = right 13 | lengths.pop() 14 | elif (left >= right) and (left <= top): 15 | top = left 16 | lengths.popleft() 17 | else: 18 | break 19 | if len(lengths) == 0: 20 | print("YES") 21 | else: 22 | print("NO") 23 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Collections/8 - Most Common.py: -------------------------------------------------------------------------------- 1 | from collections import Counter 2 | 3 | counter = Counter(input()) 4 | most_common = sorted(counter.items(), key = lambda x: (-x[1], x[0]))[:3] 5 | print (*[common[0] + " " + str(common[1]) for common in most_common], sep = "\n") 6 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Data Types/1 - Lists.py: -------------------------------------------------------------------------------- 1 | l = [] 2 | n = int(input()) 3 | for _ in range(n): 4 | cmd, *args = input().strip() 5 | if cmd == 'print': 6 | print(l) 7 | else: 8 | getattr(l, cmd)(*args) 9 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Data Types/2 - Tuples.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | v = map(int, input().strip().split(" ")) 3 | t = tuple(v) 4 | print(hash(t)) -------------------------------------------------------------------------------- /HackerRank/6 - Python/Data Types/3 - Set - Symmetric Difference.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | sn = set(map(int, input().split())) 3 | m = int(input()) 4 | sm = set(map(int, input().split())) 5 | sdiff = sn.symmetric_difference(sm) 6 | for i in sorted(sdiff): 7 | print (i) 8 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Data Types/4 - List Comprehensions.py: -------------------------------------------------------------------------------- 1 | x, y, z, n = (int(input()) for _ in range(4)) 2 | l = [x for x in [x, y, z, n]] 3 | print ([[a, b, c] for a in range(x + 1) for b in range(y + 1) for c in range (z + 1) 4 | if ((a + b + c) != n)]) 5 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Data Types/5 - Find The Second Largest Number.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | m = (map(int, input().split())) 3 | s = set(m) 4 | print (sorted(s)[-2]) 5 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Data Types/6 - Nested Lists.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | marksheet = [(input(), float(input())) for _ in range(n)] 3 | marks = [mark for name, mark in marksheet] 4 | second_highest = sorted(set(marks))[1] 5 | names = [name for [name, grade] in marksheet if grade == second_highest] 6 | print("\n".join(sorted(names))) 7 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Date AndTime/1 - Calendar Module.py: -------------------------------------------------------------------------------- 1 | import calendar 2 | 3 | m, d, y = map(int, input().split()) 4 | print(calendar.day_name[calendar.weekday(y, m, d)].upper()) 5 | # print (datetime(y, m, d).strftime("%A").upper()) 6 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Date AndTime/2 - Time Delta.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime 2 | 3 | fmt = "%a %d %b %Y %H:%M:%S %z" 4 | T = int(input()) 5 | for _ in range(T): 6 | dt1 = datetime.strptime(input(), fmt) 7 | dt2 = datetime.strptime(input(), fmt) 8 | print(abs(int((dt1 - dt2).total_seconds()))) 9 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Errors And Exceptions/1 - Exceptions.py: -------------------------------------------------------------------------------- 1 | T = int(input()) 2 | for _ in range(T): 3 | a, b = input().split() 4 | try: 5 | print(int(a) // int(b)) 6 | except (ZeroDivisionError, ValueError) as e: 7 | print("Error Code:", e) 8 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Errors And Exceptions/2 - Incorrect Regex.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | T = int(input()) 4 | for _ in range(T): 5 | try: 6 | re.compile(pattern) 7 | print("True") 8 | except Exception as e: 9 | print("False") 10 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Functionals/1 - Map And Lambda Function.py: -------------------------------------------------------------------------------- 1 | N = int(input()) 2 | fib = lambda x: x if (x < 2) else (fib (x - 1) + fib (x - 2)) 3 | # print (map(lambda x: x**3, map(fib, range(N)))) 4 | print ([fib(x)**3 for x in range(N)]) 5 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Functionals/2 - Validating Email Addresses With a Filter.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | N = int(input()) 4 | regex = re.compile("^[\w-]+@[A-Za-z0-9]+\.[A-Za-z]{1,3}$") 5 | emails = [input() for _ in range(N)] 6 | valid_emails = filter(regex.match, emails) 7 | print (sorted(valid_emails)) 8 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Introduction/1 - Hello World.py: -------------------------------------------------------------------------------- 1 | print("Hello World!") -------------------------------------------------------------------------------- /HackerRank/6 - Python/Introduction/10 - Interchange Two Numbers.py: -------------------------------------------------------------------------------- 1 | t = input(), input() 2 | print t[1] 3 | print t[0] 4 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Introduction/11 - Finding The Percentage.py: -------------------------------------------------------------------------------- 1 | n = int(raw_input()) 2 | scores = dict() 3 | for i in range(0, n): 4 | line = raw_input().split(" ") 5 | name = line[0] 6 | marks = map(float, line[1:]) 7 | score = sum(marks) / len(marks) 8 | scores[name] = score 9 | name = raw_input() 10 | print("{0:.2f}".format(scores[name])) -------------------------------------------------------------------------------- /HackerRank/6 - Python/Introduction/12 - Print Function.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | n = int(raw_input()) 4 | r = range(1, n + 1) 5 | print (*r, sep='', end = '\n') -------------------------------------------------------------------------------- /HackerRank/6 - Python/Introduction/2 - Raw Input.py: -------------------------------------------------------------------------------- 1 | line = input() 2 | print(line) -------------------------------------------------------------------------------- /HackerRank/6 - Python/Introduction/3 - Arithmetic Operators.py: -------------------------------------------------------------------------------- 1 | a = int(raw_input()) 2 | b = int(raw_input()) 3 | 4 | print(a + b) 5 | print(a - b) 6 | print(a * b) -------------------------------------------------------------------------------- /HackerRank/6 - Python/Introduction/4 - Python Division.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | 3 | a = int(raw_input()) 4 | b = int(raw_input()) 5 | 6 | print (a/b) 7 | print (a//b) -------------------------------------------------------------------------------- /HackerRank/6 - Python/Introduction/5 - Mod Divmod.py: -------------------------------------------------------------------------------- 1 | from __future__ import division 2 | 3 | a = int(raw_input()) 4 | b = int(raw_input()) 5 | 6 | r = divmod(a, b) 7 | print(r[0]) 8 | print(r[1]) 9 | print(r) 10 | 11 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Introduction/6 - Power - Mod Power.py: -------------------------------------------------------------------------------- 1 | a = int(raw_input()) 2 | b = int(raw_input()) 3 | m = int(raw_input()) 4 | 5 | # a ** b 6 | print (pow(a, b)) 7 | print (pow(a, b, m)) -------------------------------------------------------------------------------- /HackerRank/6 - Python/Introduction/7 - Integers Come In All Sizes.py: -------------------------------------------------------------------------------- 1 | a = int(raw_input()) 2 | b = int(raw_input()) 3 | c = int(raw_input()) 4 | d = int(raw_input()) 5 | 6 | print(a ** b + c ** d) -------------------------------------------------------------------------------- /HackerRank/6 - Python/Introduction/8 - Loops.py: -------------------------------------------------------------------------------- 1 | n = int(raw_input()) 2 | 3 | for i in range(0, n): 4 | print(i ** 2) 5 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Introduction/9 - What's Your Name.py: -------------------------------------------------------------------------------- 1 | fn = raw_input() 2 | ln = raw_input() 3 | 4 | print ("Hello {} {}! You just delved into python.".format(fn, ln)) -------------------------------------------------------------------------------- /HackerRank/6 - Python/Itertools/1 - Itertools.Product.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | A = map(int, input().split()) 4 | B = map(int, input().split()) 5 | print(*itertools.product(A, B)) -------------------------------------------------------------------------------- /HackerRank/6 - Python/Itertools/2 - Itertools.Permutations.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | line = input().split() 4 | S = ''.join(sorted(line[0])) 5 | k = int(line[1]) 6 | print(*[''.join(p) for p in itertools.permutations(S, k)], sep = "\n") 7 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Itertools/3 - Itertools.Combinations.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | line = input().split() 4 | S = ''.join(sorted(line[0])) 5 | k = int(line[1]) 6 | for i in range(1, k + 1): 7 | print(*[''.join(p) for p in itertools.combinations(S, i)], sep = "\n") 8 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Itertools/4 - Itertools.Combinations With Replacement.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | line = input().split() 4 | S = ''.join(sorted(line[0])) 5 | k = int(line[1]) 6 | print(*[''.join(p) for p in itertools.combinations_with_replacement(S, k)], sep = "\n") 7 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Itertools/5 - Compress The String.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | S = input() 4 | print (*[(len(list(group)), int(key)) for key, group in itertools.groupby(S)], sep = " ") 5 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Itertools/6 - Iteratables And Iterators.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | N = int(input()) 4 | letters = input().split() 5 | K = int(input()) 6 | combinations = list(itertools.combinations(letters, K)) 7 | asum = sum("a" in combination for combination in combinations) 8 | print (asum / len(combinations)) 9 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Itertools/7 - Maximize It.py: -------------------------------------------------------------------------------- 1 | import itertools 2 | 3 | K, M = map(int, input().split()) 4 | l = [] 5 | for i in range(K): 6 | ts = input().split()[1 : ] 7 | xs = [int(x) ** 2 for x in ts] 8 | l.append(xs) 9 | ps = map(sum, itertools.product(*l)) 10 | mps = max(map(lambda p: p % M, ps)) 11 | print(mps) 12 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Math/1 - Polar Coordinates.py: -------------------------------------------------------------------------------- 1 | import cmath 2 | 3 | z = complex(input()) 4 | print (abs(z)) 5 | print (cmath.phase(z)) 6 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Math/2 - Find Angle.py: -------------------------------------------------------------------------------- 1 | import cmath 2 | 3 | z = complex(input()) 4 | AB = int(input()) 5 | BC = int(input()) 6 | A = complex(0, AB) 7 | B = complex(0, 0) 8 | C = complex(BC, 0) 9 | print(phase(B + C + A)) 10 | 11 | 12 | MBC = cmath.atan(BC/AC) 13 | print(MBC) 14 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Math/3 - Triangle Quest 2.py: -------------------------------------------------------------------------------- 1 | for i in range(1, int(input())): #More than 2 lines will result in 0 score. Do not leave a blank line also 2 | print (sum(map(lambda x: 1 * 10**x, range(i - 1))) ** 2) 3 | 4 | # Or... 5 | # for i in range(1, int(input()) + 1): #More than 2 lines will result in 0 score. Do not leave a blank line also 6 | # print(((10**i - 1) // 9)**2) 7 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Math/4 - Triangle Quest.py: -------------------------------------------------------------------------------- 1 | for i in range(1, int(input())): #More than 2 lines will result in 0 score. Do not leave a blank line also 2 | print (sum(map(lambda x: i * 10**x, range(i)))) 3 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Regex And Patterns/1 - Introduction To Regex Module.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | T = int(input()) 4 | for _ in range(T): 5 | N = input() 6 | float_regex = re.compile("^[+-]?\d*\.\d+$") 7 | print(bool(float_regex.match(N))) 8 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Regex And Patterns/10 - Hex Color Code.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | N = int(input()) 4 | r = re.compile("(?", arg0, ">", arg1) 10 | 11 | def handle_endtag(self, tag): 12 | print("End :", tag) 13 | 14 | def handle_startendtag(self, tag, attrs): 15 | print("Empty :", tag) 16 | for arg0, arg1 in attrs: 17 | print("->", arg0, ">", arg1) 18 | 19 | 20 | N = int(input()) 21 | S = "" 22 | for _ in range(N): 23 | S += input() 24 | 25 | parser = MyHTMLParser() 26 | parser.feed(S) 27 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Regex And Patterns/12 - HTML Parser - Part 2.py: -------------------------------------------------------------------------------- 1 | from html.parser import HTMLParser 2 | 3 | 4 | class MyHTMLParser(HTMLParser): 5 | def handle_comment(self, data): 6 | if data.strip(): 7 | lines = str(data).split("\n") 8 | print(">>> ", "Multi" if len(lines) > 1 else "Single", "-line Comment", sep="") 9 | print(*lines, sep="\n") 10 | 11 | def handle_data(self, data): 12 | if data.strip(): 13 | print(">>> Data") 14 | print(data) 15 | 16 | html = "" 17 | for i in range(int(input())): 18 | html += input().rstrip() 19 | html += '\n' 20 | 21 | parser = MyHTMLParser() 22 | parser.feed(html) 23 | parser.close() 24 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Regex And Patterns/13 - Detect HTML Tags, Attributes and Attribute Values.py: -------------------------------------------------------------------------------- 1 | from html.parser import HTMLParser 2 | 3 | 4 | # create a subclass and override the handler methods 5 | class MyHTMLParser(HTMLParser): 6 | def handle_starttag(self, tag, attrs): 7 | print(tag) 8 | for arg0, arg1 in attrs: 9 | print("->", arg0, ">", arg1) 10 | 11 | N = int(input()) 12 | S = "" 13 | for _ in range(N): 14 | S += input() 15 | 16 | parser = MyHTMLParser() 17 | parser.feed(S) 18 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Regex And Patterns/14 - Validating UID.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | for uid in [raw_input().strip() for _ in xrange(int(raw_input()))]: 4 | # Perform the regex match. 5 | # Groups 1 and 2 ((.).*\2) match repeating characters (this test must be 6 | # first because any prior matching test would consume the characters). 7 | # Group 3 ([^\da-zA-Z]) matches non-alphanumeric characters. 8 | # Group 4 ([A-Z]) matches capital leters. 9 | # Group 5 (\d) matches digits. 10 | match_iter = re.finditer(r'((.).*\2)|([^\da-zA-Z])|([A-Z])|(\d)', uid) 11 | 12 | # Get a list of matches, including which group each match belongs to. 13 | # matches is a list of 5-tuples. For each 5-tuple, the only element that 14 | # is not None is the one corresponding to the group that caused the match 15 | # (except that groups 1 and 2 (tuple indices 0 and 1) will either both be 16 | # None or both be non-None). 17 | matches = [y.groups() for y in match_iter] 18 | 19 | # Transform from a match-oriented list to a group-oriented list. 20 | # zipped_matches is a 5 element long list of tuples. Each tuple corresponds to 21 | # one group from the regex match. Within each tuple, any value that is not None 22 | # corresponds to a match. 23 | zipped_matches = zip(*matches) 24 | 25 | # Count the non-None values within each tuple. 26 | # result is a list of 5 integers. 27 | # result[0] is the number of repetitions found, and it must be 0 for a valid 28 | # UID. This may not be accurate for non-zero values, but result[0] == 0 IF 29 | # AND ONLY IF there are no repetitions, and that's all we care about. If this 30 | # is non-zero, then result[2:] will be inaccurate, but those values won't 31 | # matter in that case because we already know the UID is invalid. 32 | # result[1] is identical to result[0]. 33 | # result[2] is the number of non-alphanumeric characters and must be 0. 34 | # result[3] is the number of capital letters and must be greater than or equal 35 | # to 2. 36 | # result[4] is the number of digits and must be greater than or equal to 3. 37 | result = [reduce(lambda a, b: a + int(bool(b)), x, 0) for x in zipped_matches] 38 | 39 | # Test for validity 40 | if len(uid) == 10 and result[0] == 0 and result[2] == 0 and result[3] >= 2 and result[4] >= 3: 41 | print 'Valid' 42 | else: 43 | print 'Invalid' 44 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Regex And Patterns/2 - Re.split().py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | S = input() 4 | print("\n".join(filter(None, re.split("[\.,]*", S)))) 5 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Regex And Patterns/3 - Group(), Groups() & Groupdict().py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | S = input() 4 | m = re.search("(\w(?!_))\\1+", S) 5 | print(m.group(1) if m else "-1") 6 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Regex And Patterns/4 - Re.findall() & Re.finditer().py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | S = input() 4 | c = "qwrtypsdfghjklzxcvbnm" 5 | v = "aeiou" 6 | m = re.findall("(?<=[%s])([%s]{2,})[%s]" % (c, v, c), S, flags=re.I) 7 | print(*(m or ['-1']), sep="\n") 8 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Regex And Patterns/5 - Re.start() & Re.end().py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | S = input() 4 | k = input() 5 | r = re.compile("(?=(%s))" % k) 6 | 7 | if r.search(S): 8 | print(*[(g.start(1), g.end(1) - 1) for g in r.finditer(S)], sep="\n") 9 | else: 10 | print((-1, -1)) 11 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Regex And Patterns/6 - Regex Substitution.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | r = re.compile("(?<= )(&&|\|\|)(?= )") 4 | N = int(input()) 5 | for _ in range(N): 6 | t = input() 7 | t = r.sub(lambda x: "and" if x.group() == "&&" else "or", t) 8 | print (t) 9 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Regex And Patterns/7 - Validating A Roman Number.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | S = input() 4 | r = re.compile("^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$") 5 | print(True if r.search(S) else False) 6 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Regex And Patterns/8 - Validating Phone Numbers.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | N = int(input()) 4 | r = re.compile("^[789]\d{9}$") 5 | 6 | for _ in range(N): 7 | t = input() 8 | print("YES" if r.search(t) else "NO") 9 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Regex And Patterns/9 - Validating & Parsing Email Address.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | N = int(input()) 4 | r = re.compile("^<([a-zA-Z][a-zA-Z0-9\._-]+)@([a-zA-Z]+)\.([a-zA-Z]{1,3})>$") 5 | 6 | for _ in range(N): 7 | name, email = input().split() 8 | if r.search(email): 9 | print(name, email) 10 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Sets/1 - Introduction To Sets.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | s = set(map(int, input().split())) 3 | print (sum(s) / len(s)) 4 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Sets/10 - The Captain's Room.py: -------------------------------------------------------------------------------- 1 | # Enter your code here. Read input from STDIN. Print output to STDOUTK = int(input()) 2 | K = int(input()) 3 | a = map(int, input().split()) 4 | c = (K * sum(set(a)) - sum(a)) // (K - 1) 5 | print(c) 6 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Sets/11 - Check Subset.py: -------------------------------------------------------------------------------- 1 | for i in range(int(input())): #More than 4 lines will result in 0 score. Blank lines won't be counted. 2 | a = int(input()); A = set(input().split()) 3 | b = int(input()); B = set(input().split()) 4 | print (A.issubset(B)) # print (A <= B) -------------------------------------------------------------------------------- /HackerRank/6 - Python/Sets/12 - Check Strict Superset.py: -------------------------------------------------------------------------------- 1 | A = set(input().split()) 2 | N = int(input()) 3 | is_strict_superset = True 4 | for x in range(N): 5 | S = set(input().split()) 6 | # (A > S) 7 | is_strict_superset &= (A.issuperset(S) and A.isdisjoint(S)) 8 | print (is_strict_superset) -------------------------------------------------------------------------------- /HackerRank/6 - Python/Sets/2 - No Idea.py: -------------------------------------------------------------------------------- 1 | n, m = map(int, input().split()) 2 | s = map(int, input().split()) 3 | a = set(map(int, input().split())) 4 | b = set(map(int, input().split())) 5 | happiness = 0 6 | for x in s: 7 | if (x in a): 8 | happiness += 1 9 | if (x in b): 10 | happiness -= 1 11 | print(happiness) 12 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Sets/3 - Set Add.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | s = set() 3 | [s.add(input()) for i in range(n)] 4 | print (len(s)) 5 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Sets/4 - Set Discard Remove And Pop.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | s = set(map(int, input().split())) 3 | N = int(input()) 4 | for i in range(N): 5 | cmd, *args = input().strip().split(" ") 6 | getattr(s, cmd)(*(int(a) for a in args)) 7 | print(sum(s)) -------------------------------------------------------------------------------- /HackerRank/6 - Python/Sets/5 - Set Union.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | english = set(map(int, input().split())) 3 | b = int(input()) 4 | french = set(map(int, input().split())) 5 | print(len(english.union(french))) 6 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Sets/6 - Set Intersection.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | english = set(map(int, input().split())) 3 | b = int(input()) 4 | french = set(map(int, input().split())) 5 | print(len(english.intersection(french))) 6 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Sets/7 - Set Difference.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | english = set(map(int, input().split())) 3 | b = int(input()) 4 | french = set(map(int, input().split())) 5 | print(len(english.difference(french))) 6 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Sets/8 - Set Symmetric Difference.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | english = set(map(int, input().split())) 3 | b = int(input()) 4 | french = set(map(int, input().split())) 5 | print(len(english.symmetric_difference(french))) 6 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Sets/9 - Set Mutations.py: -------------------------------------------------------------------------------- 1 | an = int(input()) 2 | a = set(map(int, input().split())) 3 | N = int(input()) 4 | for i in range(N): 5 | cmd, n = input().split(" ") 6 | s = set(map(int, input().split(" "))) 7 | getattr(a, cmd)(s) 8 | print(sum(a)) 9 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Strings/1 - sWAP cASE.py: -------------------------------------------------------------------------------- 1 | l = input() 2 | print (l.swapcase()) -------------------------------------------------------------------------------- /HackerRank/6 - Python/Strings/10 - Alphabet Rangoli.py: -------------------------------------------------------------------------------- 1 | import string 2 | 3 | n, alphabet = int(input()), string.ascii_lowercase 4 | pattern = [("-".join(alphabet[n - 1 : n - i - 1 : -1] + alphabet[n - i - 1 : n])).center(4 * n - 3, "-") for i in range(n)] 5 | print('\n'.join(pattern[ : -1] + pattern[ : : -1])) 6 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Strings/11 - Capitalize.py: -------------------------------------------------------------------------------- 1 | print(" ".join((s.capitalize() for s in input().strip().split(" ")))) 2 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Strings/12 - The Minion Game.py: -------------------------------------------------------------------------------- 1 | s = input() 2 | 3 | vowels = "AEIOU" 4 | 5 | kevin, stuart = 0, 0 6 | 7 | for i in range(len(s)): 8 | if s[i] in vowels: 9 | kevin += len(s) - i 10 | else: 11 | stuart += len(s) - i 12 | 13 | if kevin > stuart: 14 | print("Kevin " + str(kevin)) 15 | elif stuart > kevin: 16 | print("Stuart " + str(stuart)) 17 | else: 18 | print("Draw") 19 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Strings/2 - String Split And Join.py: -------------------------------------------------------------------------------- 1 | l = input() 2 | print('-'.join(input().split())) 3 | # print(l.replace(" ", "-")) -------------------------------------------------------------------------------- /HackerRank/6 - Python/Strings/3 - Mutations.py: -------------------------------------------------------------------------------- 1 | l = input() 2 | s = input().split() 3 | i = int(s[0]) 4 | c = s[1] 5 | print(s[ : i] + c + s[i + 1 : ]) -------------------------------------------------------------------------------- /HackerRank/6 - Python/Strings/4 - Find A String.py: -------------------------------------------------------------------------------- 1 | l = input() 2 | s = input() 3 | c = 0 4 | for i in range(len(l)): 5 | if l[i : i + len(s)] == s: 6 | c += 1 7 | print (c) 8 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Strings/5 - String Validators.py: -------------------------------------------------------------------------------- 1 | s = input() 2 | meths = ["isalnum", "isalpha", "isdigit", "islower", "isupper"] 3 | [print(any(getattr(c, meth)() for c in s)) for meth in meths] 4 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Strings/6 - Text Alignment.py: -------------------------------------------------------------------------------- 1 | # Replace all ______ with rjust, ljust or center. 2 | # This must be an odd number 3 | thickness = int(input()) 4 | c = 'H' 5 | 6 | # Top Cone 7 | for i in range(thickness): 8 | print((c * i).rjust(thickness - 1) + c + (c * i).ljust(thickness - 1)) 9 | 10 | # Top Pillars 11 | for i in range(thickness + 1): 12 | print((c * thickness).center(thickness * 2) + (c * thickness).center(thickness * 6)) 13 | 14 | # Middle Belt 15 | for i in range((thickness + 1) // 2): 16 | print((c * thickness * 5).center(thickness * 6)) 17 | 18 | # Bottom Pillars 19 | for i in range(thickness + 1): 20 | print((c * thickness).center(thickness * 2) + (c * thickness).center(thickness * 6)) 21 | 22 | # Bottom Cone 23 | for i in range(thickness): 24 | print(((c * (thickness - i - 1)).rjust(thickness) + c + (c * (thickness - i - 1)).ljust(thickness)).rjust( 25 | thickness * 6)) 26 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Strings/7 - Text Wrap.py: -------------------------------------------------------------------------------- 1 | import textwrap 2 | 3 | l = input() 4 | w = int(input()) 5 | print(*textwrap.wrap(l, w), sep="\n") 6 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Strings/8 - Desginer Door Mat.py: -------------------------------------------------------------------------------- 1 | n, m = map(int,input().split()) # More than 6 lines of code will result in 0 score. Blank lines are not counted. 2 | for i in range(1, n, 2): 3 | print ((".|." * i).center(m, '-')) 4 | print ("WELCOME".center(m, '-')) 5 | for i in range(n - 2, -1, -2): 6 | print ((".|." * i).center(m, '-')) 7 | -------------------------------------------------------------------------------- /HackerRank/6 - Python/Strings/9 - String Formatting.py: -------------------------------------------------------------------------------- 1 | n = int(input()) 2 | width = len("{0:b}".format(n)) 3 | [print ("{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}".format(i, width = width)) for i in range(1, n + 1)] 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Kerry Perret 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CodingChallenges 2 | My coding challenges solution(s) =] 3 | 4 | --------------------------------------------------------------------------------