From f0146bfb21dd7e6acfc4a5aa3e36ffa56f7b457a Mon Sep 17 00:00:00 2001 From: Dan Anderson Date: Sun, 18 Oct 2020 18:15:03 -0500 Subject: [PATCH 1/4] mass commit --- .DS_Store | Bin 0 -> 8196 bytes CountingValleys/countingvalleys.py | 65 +++++++++++++++++++ JumpingOnTheClouds/main.go | 98 +++++++++++++++++++++++++++++ RepeatedString/repeatedstring.py | 38 +++++++++++ SalesByMatch/salesbymatch.py | 44 +++++++++++++ TwoSum/twosum.py | 54 ++++++++++++++++ 6 files changed, 299 insertions(+) create mode 100644 .DS_Store create mode 100644 CountingValleys/countingvalleys.py create mode 100644 JumpingOnTheClouds/main.go create mode 100644 RepeatedString/repeatedstring.py create mode 100644 SalesByMatch/salesbymatch.py create mode 100644 TwoSum/twosum.py diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..103f60e72bf28aebf679f5df0c4ddf54b0f6016d GIT binary patch literal 8196 zcmeHMU2GIp6h5bvGBbc3{yPne3x�!7W&6fx>pXwUp9;>_W@$GP^Uh6K7|Zo!MQW z)YOPSF-C)$_`pvL@eLB6G)jE(7lWD*iGNWa^uHt8X%%nV>irXZnXL&-Z@_S~IMDhpdgDzMDSxIeydt@-r(qvzl2n0(xqnZx!_ARM8#N*=BO{`)U|Dl}&*ALx6T>G*9zVnJMF0HRHO;9`iPvF<$Q! zJ2?zhua;r>dJG0>y3(_)S4zpVi}Z9ma;{-p&K^DQkW9(74k6N$v8|nXo$32Cwpqwp zPD-AYQO!)jR9(HpG!w=N-5GH8V=k-hbL_m^=@||f|x}ONQnS?IS=f*EnM6c~P8& z=aQD1)vwQAP$w((%EGc2x4r2r$PL0kA#EHj818XChZ0^a3i6u=G+ITUt+5d`PopT| zWrDDu^>^lVDtWi0tXN47YSN(x@t3*gK~a>Qh`({yN>t_cm% z<(v~90u9j!Z;5oXD)dz@3R~d-o!A_m*yrH|coELP>u?F)f_LF#xB{QRr*I9vg&*N( z_!WMG-{B9qfdYys;S5x82{zzTj9?pXz>V0BG3>?d*oQkXi3jlzrclK}%;8bYql+i; zDSR5A!RPR0Jd5Y>Jidl+;M@2PUd9jbL;M`S!0-41tICw_Z-&3uo^5mLM(LcFW zhi*sNP}d{f{}E-snZbBEYxbPE^ABnv|nKQf0b9owLk-!+D+#gyTk{Nw?b7`nCBv%o`d2>Z*l_XCg{)(RQ z8YvQzrxI1UcAeBB$<@SVu5Fbzgyb4xE!Vb7TO=9SY2#`!)F=t!oip$PT!hQ;5nLta zeF;CnPw)%;NvspG78elb>M?|i@Bv(bE3pYzNcf7cbz&TbS2V<{X!J=~m`d-dCS(p5Of_ zzpuuzv+|aj%;xXzreY#*nYJ}Z^OsM>_@&*=))YQi9gF|FCjb6_H>V873J?eoxW^E{ z>Ubg^qeV^j%3-l~nDSxDEHS%LEYS(0sqWT R*5LjR?*ED?_1?e#{{rhRoFo7M literal 0 HcmV?d00001 diff --git a/CountingValleys/countingvalleys.py b/CountingValleys/countingvalleys.py new file mode 100644 index 00000000..2468381d --- /dev/null +++ b/CountingValleys/countingvalleys.py @@ -0,0 +1,65 @@ +#!/bin/python3 +# https://www.hackerrank.com/challenges/counting-valleys/problem + +import math +import os +import random +import re +import sys + +# +# Complete the 'countingValleys' function below. +# +# The function is expected to return an INTEGER. +# The function accepts following parameters: +# 1. INTEGER steps +# 2. STRING path +# + +def countingValleys(steps, path): + elev = 0 + ctr_val = 0 + flg_start = True + flg_inval = False + + # Iterate through the path string + for stp in path: + # What kind of step are we taking? + if stp == "U": + adj = 1 + if stp == "D": + adj = -1 + + # Are we at sea level? + if elev == 0: + # Have just started? + if flg_start: + # yes: adjust the elevation + elev = elev + adj + flg_start = False + continue + + # Are we coming out of a valley? + if adj == 1 and elev == -1: # stepping up to sea level + ctr_val = ctr_val + 1 + elev = elev + adj + continue + + # Adjust the elevation given the step type ("up" or "down") + elev = elev + adj + + return ctr_val + + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + steps = int(input().strip()) + + path = input() + + result = countingValleys(steps, path) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/JumpingOnTheClouds/main.go b/JumpingOnTheClouds/main.go new file mode 100644 index 00000000..2f67d851 --- /dev/null +++ b/JumpingOnTheClouds/main.go @@ -0,0 +1,98 @@ +// https://www.hackerrank.com/challenges/jumping-on-the-clouds/problem +package main + +import ( + "bufio" + "fmt" + "io" + "os" + "strconv" + "strings" +) + +// Complete the jumpingOnClouds function below. +func jumpingOnClouds(c []int32) int32 { + cntHops := 0 + cldNextNext := 0 + idx := 0 + + // Iterate through the + for idx < len(c) { + fmt.Println("Hop:", idx) + + // Are we on the last cloud? + if idx == len(c)-1 { + // yes: done processing + break + } + + // Determine next two cloud indexes (numbers) + cldNextNext = -999 + if idx < len(c)-2 { + // Determine the next-next cloud if it exists + cldNextNext = idx + 2 + } + + // Is next-next cloud a cumulus cloud? + if cldNextNext != -999 && c[cldNextNext] == 0 { + // yes: the next-next cloud exists and is "safe" + cntHops = cntHops + 1 // increase cloud hop by 1 + idx = cldNextNext + continue + } + + // Only option is to jump on the next cloud (assume "safe") + cntHops = cntHops + 1 // increase cloud hop by 1 + idx = idx + 1 // shift to the next-next cloud + } + + // return the number of hops + return int32(cntHops) +} + +func main() { + reader := bufio.NewReaderSize(os.Stdin, 1024*1024) + + stdout, err := os.Create(os.Getenv("OUTPUT_PATH")) + checkError(err) + + defer stdout.Close() + + writer := bufio.NewWriterSize(stdout, 1024*1024) + + nTemp, err := strconv.ParseInt(readLine(reader), 10, 64) + checkError(err) + n := int32(nTemp) + + cTemp := strings.Split(readLine(reader), " ") + + var c []int32 + + for i := 0; i < int(n); i++ { + cItemTemp, err := strconv.ParseInt(cTemp[i], 10, 64) + checkError(err) + cItem := int32(cItemTemp) + c = append(c, cItem) + } + + result := jumpingOnClouds(c) + + fmt.Fprintf(writer, "%d\n", result) + + writer.Flush() +} + +func readLine(reader *bufio.Reader) string { + str, _, err := reader.ReadLine() + if err == io.EOF { + return "" + } + + return strings.TrimRight(string(str), "\r\n") +} + +func checkError(err error) { + if err != nil { + panic(err) + } +} diff --git a/RepeatedString/repeatedstring.py b/RepeatedString/repeatedstring.py new file mode 100644 index 00000000..ad12313d --- /dev/null +++ b/RepeatedString/repeatedstring.py @@ -0,0 +1,38 @@ +#!/bin/python3 +# https://www.hackerrank.com/challenges/repeated-string/problem + +import math +import os +import random +import re +import sys + +# Complete the repeatedString function below. +def repeatedString(s, n): + num_a_str = s.count("a") # of times "a" is found in s + num_whole_str = int(n/len(s)) # of times s is repeated in a repeating + # string of length n + + num_rem_chrs = int(n%len(s)) # of characters in the string "remander" + num_a_rem = s[:num_rem_chrs].count("a") # of times "a" is found in remainder + # substring of s + + # Return the total number of "a"'s found which is equal to: + # 1. # of a's in the set of repeating strings + # 2. # of a's in the remainder substring + total_num_a = num_a_str*num_whole_str + num_a_rem + + return total_num_a + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + s = input() + + n = int(input()) + + result = repeatedString(s, n) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/SalesByMatch/salesbymatch.py b/SalesByMatch/salesbymatch.py new file mode 100644 index 00000000..42d0cc72 --- /dev/null +++ b/SalesByMatch/salesbymatch.py @@ -0,0 +1,44 @@ +#!/bin/python3 +# https://www.hackerrank.com/challenges/sock-merchant/problem + +import math +import os +import random +import re +import sys + +# Complete the sockMerchant function below. +def sockMerchant(n, ar): + mp_sock = {} + ctr_pair = 0 + + # Iterate through the passed array + for clr in ar: + # Is this sock color in our working map? + if clr not in mp_sock.keys(): + # No: add the sock color as a key + mp_sock[clr] = 1 + continue + + # Color is already in the map - we have now found a sock pair + # Increase the pair count + ctr_pair = ctr_pair + 1 + + # Delete the current color key - so we can identify the next pair + del mp_sock[clr] + + # Done iterating... return the current counter value + return ctr_pair + +if __name__ == '__main__': + fptr = open(os.environ['OUTPUT_PATH'], 'w') + + n = int(input()) + + ar = list(map(int, input().rstrip().split())) + + result = sockMerchant(n, ar) + + fptr.write(str(result) + '\n') + + fptr.close() diff --git a/TwoSum/twosum.py b/TwoSum/twosum.py new file mode 100644 index 00000000..100c193c --- /dev/null +++ b/TwoSum/twosum.py @@ -0,0 +1,54 @@ +# https://leetcode.com/problems/two-sum +class Solution: + def twoSum(self, nums, target): + # Create working variables + wrk_dict = {} + + # Iterate through the list of integers + for idx, val in enumerate(nums): + # Insert value into the working dict + + # Is the current value already in our dict? + if val not in wrk_dict: + # no: insert the value associate with a list + # containing the value's index in the list + wrk_dict[val] = [idx] + continue + + # Current value already exists, append this index + wrk_dict[val].append(idx) + + # Iterate through the dictionary's keys + for ky in wrk_dict.keys(): + # Calculate the difference between the target and current key + diff = target - ky + + # Is the difference equal to the key (e.g. ky + ky = target)? + if diff == ky: + # yes: must have dupes, return multiple indices associated with + # this list value + if len(wrk_dict[ky]) == 1: + # the difference is equal to the key but only value found... keep processing + continue + + # return first two index values + return wrk_dict[ky][0:2] + + # Is the diff in the dict? + if diff in wrk_dict: + # yes: return a list that includes the indices of the + # two keys + ret_lst = [wrk_dict[ky][0]] + ret_lst.append(wrk_dict[diff][0]) + return ret_lst + + # Finished iterating: no solution found + return [] + + +my_solv = Solution() + +rslt = my_solv.twoSum([3,2,4], 6) +print(rslt) + + \ No newline at end of file From 3a30f139317d6fc2cabb453b26ef00f4cdfc97db Mon Sep 17 00:00:00 2001 From: Dan Anderson Date: Sun, 18 Oct 2020 21:23:08 -0500 Subject: [PATCH 2/4] Create implement-queue-using-stacks.py --- .../implement-queue-using-stacks.py | 163 ++++++++++++++++++ 1 file changed, 163 insertions(+) create mode 100644 ImplementQueueUsingStacks/implement-queue-using-stacks.py diff --git a/ImplementQueueUsingStacks/implement-queue-using-stacks.py b/ImplementQueueUsingStacks/implement-queue-using-stacks.py new file mode 100644 index 00000000..6bd9c0ab --- /dev/null +++ b/ImplementQueueUsingStacks/implement-queue-using-stacks.py @@ -0,0 +1,163 @@ +from collections import deque + +class MyQueue: + + def __init__(self): + """ + Initialize your data structure here. + """ + self.stack_A = deque() + self.stack_B = deque() + + def stack_A_push(self, val): + """ + push value onto stack A + """ + if val != None: + self.stack_A.append(val) + + def stack_A_pop(self): + """ + pop and return value from stack A + """ + if len(self.stack_A) == 0: + return None + + return self.stack_A.pop() + + def stack_A_ret_last(self): + """ + This functions essentially pops the next queue value + by returning the last value in the stack + """ + lst_elm = self.stack_A_pop() + while lst_elm != None: + # Is lst_elm the actual last element? + if len(self.stack_A) <= 1: + # yes: don't push to Stack B, break out + break + + # Not the last element in the list + # Push value to Stack B + self.stack_B_push(lst_elm) + # Pop the next value from Stack A + lst_elm = self.stack_A_pop() + + # Done popping from Stack A + # Push all the values back from Stack B to Stack A + self.stack_B2stack_A() + + return lst_elm + + def stack_A_peek_last(self): + """ + This functions essentially peeks the next queue value + by returning the last value in the stack but keepin the + value in the strack + """ + lst_elm = self.stack_A_pop() + while lst_elm != None: + # Push value to Stack B + self.stack_B_push(lst_elm) + + # Is lst_elm the actual last element? + if len(self.stack_A) <= 1: + # yes: break out of the loop + break + + # Pop the next value from Stack A + lst_elm = self.stack_A_pop() + + # Done popping from Stack A + # Push all the values back from Stack B to Stack A + self.stack_B2stack_A() + + return lst_elm + + def stack_B_push(self, val): + """ + push value onto stack B + """ + if val != None: + self.stack_B.append(val) + + def stack_B_pop(self): + """ + pop and return value from stack A + """ + if len(self.stack_B) == 0: + return None + + return self.stack_B.pop() + + def stack_A2stack_B(self): + """ + pops all stack A elements and + pushes them onto stack B + """ + tmp = self.stack_A_pop() + while tmp != None: + self.stack_B_push(tmp) + tmp = self.stack_A_pop() + + return + + def stack_B2stack_A(self): + """ + pops all stack B elements and + pushes them onto stack A + """ + tmp = self.stack_B_pop() + while tmp != None: + self.stack_A_push(tmp) + tmp = self.stack_B_pop() + + return + + def push(self, x): + """ + Push element x to the back of queue. + """ + # Push all Stack A elements onto Stack B + self.stack_A2stack_B() + # Push x onto Stack A + self.stack_A_push(x) + # Push all Stack B elements onto Stack A + self.stack_B2stack_A() + + return + + def pop(self): + """ + Removes the element from in front of queue and returns that element. + """ + return self.stack_A_ret_last() + + def peek(self): + """ + Get the front element. + """ + return self.stack_A_peek_last() + + + def empty(self): + """ + Returns whether the queue is empty. + """ + if len(self.stack_A) == 0: + return True + + return False + + +my_queue = MyQueue() +my_queue.push(1) +my_queue.push(2) +my_queue.push(3) +my_queue.push(4) +my_queue.pop() +my_queue.push(5) +my_queue.pop() +my_queue.pop() +my_queue.pop() +my_queue.pop() From e2009e1d286d3110a7fbbc72e5cb4f0bd0a50c0e Mon Sep 17 00:00:00 2001 From: Dan Anderson Date: Sun, 18 Oct 2020 22:13:01 -0500 Subject: [PATCH 3/4] Update implement-queue-using-stacks.py --- .../implement-queue-using-stacks.py | 50 +++++++++++-------- 1 file changed, 30 insertions(+), 20 deletions(-) diff --git a/ImplementQueueUsingStacks/implement-queue-using-stacks.py b/ImplementQueueUsingStacks/implement-queue-using-stacks.py index 6bd9c0ab..8c683329 100644 --- a/ImplementQueueUsingStacks/implement-queue-using-stacks.py +++ b/ImplementQueueUsingStacks/implement-queue-using-stacks.py @@ -1,20 +1,18 @@ -from collections import deque - class MyQueue: def __init__(self): """ Initialize your data structure here. """ - self.stack_A = deque() - self.stack_B = deque() + self.stack_A = list() + self.stack_B = list() def stack_A_push(self, val): """ push value onto stack A """ if val != None: - self.stack_A.append(val) + self.stack_A.insert(0, val) def stack_A_pop(self): """ @@ -23,25 +21,32 @@ def stack_A_pop(self): if len(self.stack_A) == 0: return None - return self.stack_A.pop() + ret_elm = self.stack_A[0] + del self.stack_A[0] + return ret_elm def stack_A_ret_last(self): """ This functions essentially pops the next queue value by returning the last value in the stack """ + # Does Stack A only have on 1 element? + if len(self.stack_A) == 1: + # yes: return the last element now + # Pop the first element in the stack (last element in the queue) + return self.stack_A_pop() + + # Stack A has more than one element lst_elm = self.stack_A_pop() - while lst_elm != None: - # Is lst_elm the actual last element? - if len(self.stack_A) <= 1: - # yes: don't push to Stack B, break out - break - - # Not the last element in the list + while True: # Push value to Stack B self.stack_B_push(lst_elm) # Pop the next value from Stack A lst_elm = self.stack_A_pop() + # Is this the last element in the stack + if len(self.stack_A) == 0: + # yes: have last element; break without pushing to Stack B + break # Done popping from Stack A # Push all the values back from Stack B to Stack A @@ -79,7 +84,7 @@ def stack_B_push(self, val): push value onto stack B """ if val != None: - self.stack_B.append(val) + self.stack_B.insert(0, val) def stack_B_pop(self): """ @@ -88,7 +93,9 @@ def stack_B_pop(self): if len(self.stack_B) == 0: return None - return self.stack_B.pop() + ret_elm = self.stack_B[0] + del self.stack_B[0] + return ret_elm def stack_A2stack_B(self): """ @@ -154,10 +161,13 @@ def empty(self): my_queue.push(1) my_queue.push(2) my_queue.push(3) +my_pop = my_queue.pop() +quit() +my_queue.push(3) my_queue.push(4) -my_queue.pop() my_queue.push(5) -my_queue.pop() -my_queue.pop() -my_queue.pop() -my_queue.pop() +my_pop = my_queue.pop() +my_pop = my_queue.pop() +my_pop = my_queue.pop() +my_pop = my_queue.pop() +quit() From c46764c59671b873167f25f7e57539ecc23a67cd Mon Sep 17 00:00:00 2001 From: Dan Anderson Date: Sun, 18 Oct 2020 22:48:58 -0500 Subject: [PATCH 4/4] submission --- .DS_Store | Bin 8196 -> 10244 bytes .gitignore | 2 + .../implement-queue-using-stacks.py | 87 +++++------------- 3 files changed, 24 insertions(+), 65 deletions(-) create mode 100644 .gitignore diff --git a/.DS_Store b/.DS_Store index 103f60e72bf28aebf679f5df0c4ddf54b0f6016d..f54aedbaf3a9f97293b40a54bde20de703744e2b 100644 GIT binary patch delta 426 zcmZp1XbF&DU|?W$DortDU{C-uIe-{M3-C-V6q~50$jHAjU^hP_|70EkQ&k>@V1`77 z9EMbeVg@IMN(NsbuY@6)AtR~0xF9JfKMAPu>tsP85kpRHK5p*V;Eeq8;F83W(qgB? zqIdzB;LMcNq{O1|%#@OhkkmZaoYb<^JpUq}#FEs>R)U`O(I5>0i6t38MI6cwnGQhn z7#KJ?IO7E*s;fGr2@S6@|YDjekKv5qFrB1sCPzt~7i0#S3