1.31.2019 | Accept a string and return middle characters

1.30.2019 | Search for a substring within a given string

1.29.2019 | Process people entering/exiting at different bus stops

1.28.2019 | Array processing based on occurrences

1.27.2019 | Accept a string and convert to its opposite case

1.26.2019 | Accept numbers in string and print them based on value

1.25.2019 | Arrange array so all 0s are at the end

1.24.2019 | Comparing two lists and remove mismatched elements

1.23.2019 | Accept 2 integers A,B and return sum of multiples of A below B

1.22.2019 | Accept a sequence of letters and return missing letter

1.21.2019 | Take number and print sorted version, descending

1.20.2019 | Accept sentence and N. Return top N words in sentence.

1.19.2019 | Accept number range and print all palindromic primes

1.18.2019 | Convert human age to cat and dog year equivalents

1.17.2019 | Program to check pangram (sentence with a-z in it)

1.16.2019 | Accept 2 numbers and print running sum between them (R)

1.15.2019 | Accept string and organize words based on number in them

1.14.2019

1.13.2019

1.12.2019

1.11.2019

1.10.2019

1.9.2019

1.8.2019

1.7.2019

1.6.2019

1.5.2019

1.4.2019

1.3.2019

1.2.2019

1.1.2019


1.31.2019 | Accept a string and return middle characters

#1.31.2019 - Shashi
#program that accepts a string and returns the middle character(s).

def extractMid(string):
   
   
if not string:
       
return "N/A"
   
   strLen = len(string)
#to hold the length of the string
   output =
""
   
if strLen == 1: #if the string only contains one character
       
return string #return the same back
   
elif strLen % 2 == 0: #if string contains even number of characters - ex: 6
       output = string[int(strLen/
2) - 1] + string[int(strLen/2)]
       
#join middle characters - ex: 3rd and 4th character
       
return output #return final output
   
else: #if string not 1 and not even count
       
return string[int(strLen/2)]
       
#return middle character. So, if length is 5, then mid is 5/2 = 3 which is [2] character.
   

print(extractMid(
"tested")) #6 characters,so mid should be "st"
print(extractMid(
"s")) #1 character so returns 's' back
print(extractMid(
"")) #nothing sent, so N/A returned
print(extractMid(
"seven")) #5 characters, so 5/2 = 3rd character returned - v


1.30.2019 | Search for a substring within a given string

#1.30.2019 - shashi
#search for a substring pattern within a given string

def substrCount(string, searchText):
 loop =
0  #controls the looping within the string
 counter =
0 #counter to hold how many matches were found

 
if string and searchText:  #valid values
        
while loop < len(string): #loop until string length maxes out
         
if string.startswith(searchText, loop): #check for portion of string with search text
           counter = counter +
1 #if true then increment counter
         loop = loop+
1 #loop progression
         
        
return counter #once loop is done, return final value back


print(substrCount(
'abracadabra is absolute magic', 'br'))
print(substrCount(
'hocus pocus focus ', 'us'))
print(substrCount(
'hello world', 'xy'))


1.29.2019 | Process people entering/exiting at different bus stops

#1.29.2019 - Shashi
#Program that processes people entering and exiting a bus at different bus stops.

def number(bus_stops): #function starts here
   onBusStill =
0 #to hold remaining count
   
   
for stops in bus_stops: #process each item pair in list [col1,col2]
       onBusStill = onBusStill + stops[
0] - stops[1]  #remaining count + people entering - people leaving
   
#end of loop
   
   
return onBusStill #return value back


print(number([[
10,0],[3,5],[5,8]]))  
#Stop 1: 10 in, 0 out (10) | Stop 2: 3 in, 5 out (8) | Stop 3: 5 in, 8 out (5 remain)
print(number([[
3,0],[9,1],[4,10],[12,2],[6,1],[7,10]]))
#3 in, 0 out (3) | 9 in, 1 out (11) | 4 in, 10 out (5) | 12 in, 2 out (15)
#6 in, 1 out (20) | 7 in, 10 out (17 remain)    
print(number([[
3,0],[9,4],[4,8],[12,4],[6,5]]))
#3 in, 0 out (3)|9 in, 4 out (8)| 4 in, 8 out (4)| 12 in, 4 out (12)| 6 in, 5 out (13)


1.28.2019 | Array processing based on occurrences

#1.28.2019 - Shashi
#Write a function that accepts a list and N. Return a list that contains elements of original list at most N number of times. Delete the rest.
#The order of the list elements should be unchanged.
#Example: [1,2,3,1,2,1,2,3] and N = 2.
#Output is [1, 2, 3, 1, 2, 3] because 1,2,3 should appear in list at MOST 2 times only.

def nOccurences(list,nMax):
        appearances = {}
#dictionary that holds values and associated # of times it appears. Example: {25: 3}
        finalList = []
#array to  hold final array data
   
        
for number in list: #for every number in the original list
           
if number not in appearances:   #does that number appear in occurrences?
               appearances[number] =
0  #if it doesn't then make appearances[that number] = 0 (as in no appearances)
               
           
if appearances[number] < nMax:   #now check if appearance count for that number is < max allowed
               appearances[number] = appearances[number] +
1  #if it is then add 1 to that count
               finalList.append(number)
#add that number to finalList
               
   
        
#loop continues for other numbers in original list            
        
return finalList #return the updated final list back
   
   
#end of function

print(nOccurences([
1,2,3,1,2,1,2,3],2))  #print numbers for up to 2 occurrences only. ignore the rest.
print(nOccurences([
101,201,113,123,201,101,222,34],1))  #print numbers for up to 1 occurrence only. ignore the rest.
#end of program


1.27.2019 | Accept a string and convert to its opposite case

#1.27.2019 - Shashi
#Accept a string and convert it its opposite case.
#example: "hello world" would become "HELLO WORLD"


def swapCase(string):  #function starts here
        finalString =
"" #string to hold final output
   
        
for letter in string: #loop through each letter in the original string
           
if letter.isupper(): # if the letter is upper case
               finalString = finalString + letter.lower()  
#add its lower case equivalent to the final output
           
else:  
               finalString = finalString + letter.upper()  
#else do the opposite
   
   
        
return finalString #final output will be the swapped cases for each case type.
   
#testing function
print(swapCase(
"Hello World"))
print(swapCase(
"hello WORLD"))
print(swapCase(
"hElLo WoRlD"))
#program ends here



1.26.2019 | Accept numbers in string and print them based on value

#1.26.2019 - Shashi
#program that accepts a number in a string and returns the string where each digit is repeated N number of times.
#example: 312 = 333122 (3 repeated 3 times, 1 repeated once, 2 repeated twice)

def expandNumber(num): #function starts here
   
        
if not num or int(num)<=0: #if number is empty or <=0
           
return "N/A"        #return N/A
   
        finalOutput =
'' #else prepare string var for final output
   
        
for digit in num: #for each digit in number
           finalOutput = finalOutput +  digit*int(digit)
#append "digit x (number of times it appears)"
   
   
        
return finalOutput #once loop is done return final output back

#testing the function
print(expandNumber(
"312")) #333122
print(expandNumber(
"4172")) #44441777777722
print(expandNumber(
"3241")) #3332244441
print(expandNumber(
"-3434")) #N/A
print(expandNumber(
"")) #N/A
#program ends here


1.25.2019 | Arrange array so all 0s are at the end

#1.25.2019
#Program that accepts an array of different elements
#And moves all the integer 0s to the end of it. String 0s like "0" or "0.0" remain untouched.


def shiftZeroesToEnd(myArray): #function starts here
   zeroCounter =
0 #counter to keep track of how many 0s exist.
   shiftedArray = []
#array to hold final output
 
   
for item in myArray: #loop through each item in array
       
if (str(item) == "0" or str(item) == "0.0") and type(item) is not str:
           zeroCounter +=
1 #if numeric string found, incremenet zero counter
       
else:
           shiftedArray.append(item)
#else add item from original list as is (same position)
   
#end of loop        
   zeroStore = [
0 for i in range(zeroCounter)] #declare an array of 0s of the size of zeroCounter
   shiftedArray.extend(zeroStore)
#append it to final output list (adds it to the end)
   
   
return shiftedArray #return final output back

#testing function
print(shiftZeroesToEnd([
True, 3, 3, 0, 23, 0, 112, "b", "a"]))
print(shiftZeroesToEnd([
0.0, 23, -3, False, "xxx", 0, 112, True , 9]))


1.24.2019 | Comparing two lists and remove mismatched elements

#1.24.2019 - Shashi
#program that accepts 2 lists and removes all values from list 1 that match list 2.
#so, if the lists are: 1,2,3,3,3,4,5  and list 2 is 3,4
#it should remove 3,4 from list 1 and return 1,2,5

def removeItems(list1, list2): #function starts here
   
for value in list2: #loop through each value in list 2
       
while(value in list1): #for each while as long as that value exists in list 1
           list1.remove(value)
#remove it from list 1
       
#loops end    
       
   
return list1 #return updated list1

#test function
print(removeItems([
1,2,2,2,3,3,4,5],[3,4])) #removes 3,4 from list
print(removeItems([
3,3,4,6,6,6,7,8,9,10],[3,6,10])) #removes 3,6,10 from list
print(removeItems([
101,87,23,23,244,109,-2],[-2,4])) #removes -2 but not 4 since it doesnt exist
#end of program


1.23.2019 | Accept 2 integers A,B and return sum of multiples of A below B

#1.23.2019 - Shashi
#program that accepts 2 integers A, B and returns the sum of all multiples of A below B.
#B is excluded from the multiples
#ex: 2,9 = 2 + 4 + 6 + 8 = 20
#ex: 3,10 = 3 + 6 + 9  = 18

def sumOfMultiples(a, b):  #function starts here
   
if a<=0 or b<=0:
       
return('INVALID')   #take care of invalid values
   
else:
       finalTotal=
0    #else default is 0

       
for number in range(a,b,a): #loop from A to B, incrementing by A values each time
           finalTotal+=number  
#add on to the subtotal

       
return(finalTotal)  #loop done, return final value back

#testing function
print(sumOfMultiples(
2,10))
print(sumOfMultiples(
2,9))
print(sumOfMultiples(
-3,6))
#end of program


1.22.2019 | Accept a sequence of letters and return missing letter

#1.22.2019
#Program that accepts a sequence of letters and returns the missing letter

def missingLetter(seq):
   alphabetSet = list(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
   startingLetter = alphabetSet.index(seq[
0]) #index searches for position of first letter in input and returns it
   
   
for letter in range(len(seq)): #loop through the length of sequence given
       
if not seq[letter] == alphabetSet[startingLetter+letter]: #for each letter check if next letter matches whats in alphabetSet
           
return alphabetSet[startingLetter+letter] #if not then return that value back
   
#loop ends
   
#testing out function
print(missingLetter([
'e', 'f', 'g', 'i', 'j']))
print(missingLetter([
'A', 'B', 'C', 'E']))
print(missingLetter([
'z', 'A', 'C', 'D']))
#end of program


1.21.2019 | Take number and print sorted version, descending

#1.21.2019 - Shashi
#Take a number and print its sorted version in descending order
#Example: 1234 should become 4321
#Or 1734 should become 7431

def descendingSort(num):
 digitList = []
 
for index in range(len(str(num))): #loop through the range of digits in original number
   digitList.append(str(num)[index])
#add them as strings into digitList

   digitList_sorted = sorted(digitList, reverse=
True)  #create a sorted version of the string variable
   digitList_sorted_final =
''.join(digitList_sorted) #convert it back to integer with a "join"

 
return int(digitList_sorted_final) #return final output back
 
#testing out the function with different values  
print(descendingSort(
1734))
print(descendingSort(
19784))
print(descendingSort(
134))


1.20.2019 | Accept sentence and N. Return top N words in sentence.

#1.20.2019 - Shashi
#Program that accepts a string/sentence and a number N.
#Function should return the the TOP N words occurring in the sentence.

import collections #high performance data type module

def top5_words(text, topNum): #function starts here
   counts = collections.Counter(text.split())
#splits the sentence, implements count numbers as object
   
return counts.most_common(topNum)  #counts.most_common built in to return N top words from sentence.
   
#testing function for different strings and N
print(top5_words(
"It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout.",5))
print(top5_words(
"There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour.",3))


1.19.2019 | Accept number range and print all palindromic primes

#1.19.2019 - Shashi
#write a function that takes starting and stopping numbers
#print out all the prime numbers who remain prime on reversing them too. Like 31. or

def backwardsPrimeRange(startNum, stopNum): #function starts here
   primeList = []
#make an empty list to load up every prime number found
   
for value in range(startNum, stopNum): #loop from starting to ending value
       
if isPrimeNum(value): #if number in range is a prime number
           primeList.append(value)
#add it to the primeList array
   
#end of for loop
   
   reversePrimeList =[]
#make an empty list to hold those values that are prime even when reversed
   
for value in primeList: #check each value in prime numbers list
       
if isPrimeNum(int(str(value)[::-1])): #if reverse version of the number is also prime
           
if value!=int(str(value)[::-1]): #and if reversed value is NOT EQUAL to its original number (example: 11)
               reversePrimeList.append(value)
#add it to reverse prime number list
   
#end of second loop
   
   
return reversePrimeList   #return final list to calling function

#function that is used to check if a number is prime
#divisible only by itself and 1.
def isPrimeNum(num):
   
for value in range(2,num-1): #loop from 2 ... until num -1
       
if num%value==0:    #if any of those values divide the number
           
return False    #not prime. so return false.
   
#end of loop        
   
return True #if loop reaches here then it is prime. return true.
   

print(backwardsPrimeRange(
3,300)) #print all prime numbers between 3 and 300 that are prime on reversed too.
print(backwardsPrimeRange(
1000,1100)) #testing for other large values
print(backwardsPrimeRange(
90,190)) #testing for smaller values.


1.18.2019 | Convert human age to cat and dog year equivalents

#1.18.2019 - Shashi
#Take age of human and convert it to Cat and Dog years based on the following conditions:
#humanYears >= 1
#humanYears are whole numbers only
#Cat Years...
#15 cat years for first year
#+9 cat years for second year
#+4 cat years for each year after that
#Dog Years...
#15 dog years for first year
#+9 dog years for second year
#+5 dog years for each year after that

def humanCatDog(humanAge): #function begins
   catAge,dogAge=
0,0 #base values for cat/dog years
   
if humanAge == 1:           #if human age is 1
       catAge,dogAge=
15,15     #both animal ages are 15
   
elif humanAge>=2:           #if human age >=2
       catAge,dogAge=
24,24     #both animal ages are 24
       
for value in range(humanAge-2,0,-1):    #If human years after the 2nd year (such as 5)
        catAge +=
4                                     #keep adding 4 for every cat year and 5 for every dog year
        dogAge +=
5       
       
#end of loop
   
return [humanAge,catAge,dogAge] #return all values back.


print(
"Years > [Human, Cat, Dog]",humanCatDog(5))
print(
"Years > [Human, Cat, Dog]",humanCatDog(3))
print(
"Years > [Human, Cat, Dog]",humanCatDog(7))
print(
"Years > [Human, Cat, Dog]",humanCatDog(-2))
print(
"Years > [Human, Cat, Dog]",humanCatDog(1))


1.17.2019 | Program to check pangram (sentence with a-z in it)

#1.17.2019 - Shashi
import string #import the string module

def is_pangram(sentence): #function starts here
   
if not sentence: #if blank string
       
return "N/A"
   sentence = sentence.lower()
#convert string to lower case  
   alphabet =
"abcdefghijklmnopqrstuvwxyz" #load up all letters in the alphabet
   
   
for letter in alphabet: #loop through each letter in the alphabet
       
if letter not in sentence: #if any letter from alphabet is not in sentence
           
return False #return FALSE and end loop

   
return True #if loop completes and reaches here, return TRUE


print(is_pangram(
"Cwm fjord bank glyphs vext quiz")) #true
print(is_pangram(
"The quick brown fox jumps over the lazy dog.")) #true since it contains a-z
print(is_pangram(
"")) #test for empty string
print(is_pangram(
"hello world")) #false


1.16.2019 | Accept 2 numbers and print running sum between them (R)

#1.16.2019 - Shashi
#My first program in R programming language.
#Uses a function that accepts 2 numbers and outputs the running sum betwen the two.

sum_between <- function(n1, n2){
 total <-
0  #to hold the final value
 
if (n1 == n2) #if both values are the same
 {  
return (n1)  }  #return the same value back
 
 
if (n1 < n2) #if first value lesser than second
 {
for (value in n1:n2) #loop from n1 to n2  
   { total = total+value }  
#total up all the values
   
return (total)  # return total after loop ends
 }
#end if
 
 
if (n2 < n1) #if second value lesser than first
 {
for (value in n2:n1) #move from lesser value to greater
   { total = total+ value }
#total up the values
   
return (total) #return total after loop ends
 }
#end if
}
#end of functon sum_between()


sum_between(
1,5)  #1+2+3+4+5 = 15
sum_between(
10,5) #10+9+8+7+6+5 = 45
sum_between(
6,6)  #6
sum_between(
-5,5)  #0


1.15.2019 | Accept string and organize words based on number in them

#1.15.2019 - Shashi
#Program that accepts a string with a number in each word.
#Output should organize the words according to the number in the words.

def order(sentence):
   print(sentence)
   words = sentence.split()
#split up the word based on spaces

   finalSequence = []
#array to hold the final sorted sequence
   finalSequenceWithoutDigit = []  
#array to hold final sorted sequence without the original digit in it.
   
   
for word in words: #loop through each of the words
       
for letter in word: #check each letter in each word
           
if letter.isdigit(): #if a digit is found
               finalSequence.append([int(letter), word])
#add a number and the word associated with it
               finalSequenceWithoutDigit.append([int(letter),word.replace(letter,
'')])
               
#this loops until all words are done.

   
   finalSequence = sorted(finalSequence, key=
lambda x : x[0]) #sort the final sequence by first column key
   finalSequenceWithoutDigit = sorted(finalSequenceWithoutDigit, key=
lambda x : x[0]) #sort the final sequence by first column key
   
   print(
" ".join([x[1] for x in finalSequenceWithoutDigit]))
   
return " ".join([x[1] for x in finalSequence]) #join elements in second column [1] with a space and return.


print(order(
"3brown The1 fo4x qu2ick"))
print(
"\n")
print(order(
"world2. hello1 Th3is tes6t. a5"))


1.14.2019

#1.14.2019
#Program to generate a random password based on number of characters requested.
import random
import string
#import built in libraries to use specific functions

def genpwd(length): #function starts here
   password =
""  #to hold final value
   count =
0      #to keep track of length required
   
   
if length<=0:   #to handle error values
       
return "N/A" 

   
while count != length: #as long count does not become equal to requested length
       dig = [random.choice(string.digits)]
#get a randomly selected digit
       upper = [random.choice(string.ascii_uppercase)]  
#get a randomly selected uppercase letter
       lower = [random.choice(string.ascii_lowercase)]
#get a randomly selected lowercase letter
       spec = [random.choice(string.punctuation)]
#get a randomly selected symbol/special character
       
       combo = upper + lower + dig + spec  
#combine all elements into one string
   
       password = password + random.choice(combo)  
#select a random character from the combined sequence and add to password string
       count = count +
1 #increment count
       
continue #continue with loop
   
   
if count == length: #if count matches length (requested by user)
       
return password #return the final password back

#testing function
print(genpwd(
8))    
print(genpwd(
10))    
print(genpwd(
15))    
print(genpwd(
-1))
#end of program


1.13.2019

#1.13.2019 - Shashi
#Domain name extractor

def extractDomain(url): #function starts here
   
   
if(not url):    #if invalid or empty string sent
       
return False    #return False (or an error message)
   
else:
       URLparts = url.split(
'.')   #split string based on period symbol (.) and store in URLparts[]
   
       
if 'www' in url: #if the original string has 'www' in it
           
return URLparts[1]  #return the 2nd item in URLParts[]
       
elif '://' in url: #if string has "://" in the url
           
return URLparts[0].split('://')[1]  #split array[1] element by :// and return 2nd element from resulting data
       
else:
           
return URLparts[0] #if no www or :// then return the very first element in the URL
       
#test function with diff. types of inputs.
print(extractDomain(
"https://example.com/addition/actor.php"))
print(extractDomain(
"https://brother.example.org/?bells=back&authority=afterthough"))
print(extractDomain(
"https://www.example.com/"))
print(extractDomain(
"stackoverflow.com/questions/112121/coderhelp"))
print(extractDomain(
""))
#program ends here


1.12.2019

#1.12.2019
#program that accepts a string and increments the number that is part of it.
#the number has no specific format and can appear however. So an example would be:
# "Member001" that is incremented to "Member002"
#Another example is "hello1" which is incremented to "hello2".
#the only standard is that the number is at the END of the string.

def stringIncrease(s): #function starts here
   
if not s: #if string empty
       
return "N/A" #return N/A
   
   
#else the rest    
   output=
"" #for final output
   digExtract =
"" #for processing the number part of the string
   
   
for i in range(5,0,-1): #loop starts at 5, ends at 1, decremented by 1.
       
if len(s) > i-1 and s[-i].isdigit():  #check for digits at the end of the string
           digExtract = str(int(s[-i:])+
1).zfill(i) #add 1 to the int() portion of the string
           
#zfill pads the string's width and helps process values like "0003" without losing 0s.
           output = s[:-i] + digExtract
#add the incremented portion to rest of the string
           
return output #return the final output back
   
#end of loop            
   
return s+'1' #this part executed if string has no digits at the end.
   
#So "hello" returns "hello1"

#testing diff. kinds of inputs to see how output differ
print(stringIncrease(
"Member002")) #mixed values with leading 0s (use of zfill())
print(stringIncrease(
"hello1")) #mixed values withiut leading 0s
print(stringIncrease(
"justAString")) #no numbers in string
print(stringIncrease(
"")) #empty string
print(stringIncrease(
"32")) #only numbers in string
#end of program


1.11.2019

#1.11.2019 - Shashi
#Program to print permutations of diff. words in a string array

from itertools import permutations  #to user permutations() function for a list

def sloganGen(array):
   list1=array
#the array that came in
   list2=[]
#new blank array to hold unique values and generate permutation combos

   
for eachword in list1: #every word in original list
       
if eachword not in list2: #if word doesn't exist in blank array
           list2+=[eachword]
#add it
   
   list3=list(permutations(list2))
#generate all permutations of list2 and return to list3
   list3=[
" ".join(x) for x in list3] #add new versions of list3 with each looping
   
   
return list3 #return final list back to calling function
   
combos = sloganGen([
"world", "coding"]) #send words via an array
print(*combos, sep=
'\n') #print it so that each array element is on a new line for better readability
print(
"\n") # new line for spacing
combos = sloganGen([
"daily", "coding", "challenge"])
print(*combos, sep=
'\n')
#end of program


1.10.2019

#1.10.2019 - Shashi
#program to accept binary value as an array and return its decimal equivalent.
#Binary code can be of any length but should only comprise of 1s and 0s.

def bin_dec(binArr): #function starts here
   result =
0 #variable to hold final answer
   
for i in range(len(binArr)): #loop through each digit in the array
       
if binArr[i] == 1:  #only 1 position elements have a power
           result = result + pow(
2,len(binArr)-1-i) #total calculated by squaring arrpos(length-1-i)
           
#We do this because digit powers start from right but array is being navigated from the left.
           
#So for 1100, the first 1 is [0] in array but in position 3 as a number.
           
#Hence, len(binArr)-1-i for that position gives u : len(binArr) = 4 -1-0 (since i is 0 at this point)
           
#4-1-0 = 4 - 1 = 3. 2 power 3 is what we want for first 1.
           
           
#continue loop for all elements in array
   
return result #return output

print(bin_dec([
1,0,0,1,1,1,1])) #79
print(bin_dec([
1,1,1,1,0])) #30
print(bin_dec([
1,0,0])) #4
print(bin_dec([
1,0,1,0,0,1])) #41
#end of program


1.9.2019

#1.9.2019 - Shashi
#accept a string of text and a key value. cipher the original text based on key value.
#mapping only for lower case letters from a-z.

def cipher(text,key): #function starts here
   arr =
"abcdefghijklmnopqrstuwxyz" #lookup variable for all letters.
   text = text.lower()
#convert original text to lower
   ctext =
"" #variable to hold final output
   
for c in text: #loop through every character in string
       
#if c is part of alphabet, look up index of c in arr, add key value and mod the whole value by 26
       #(for high value keys) and look up its equivalent in arr

       
if c.isalpha() : ctext += arr[(arr.index(c)+key)%26]  
       
else: ctext += c
       
#if c is not in the alphabet, then add it in as is. Example digits, special characters.
   
return ctext #return final output back

#testing function with same message but diff. cipher keys.
print(cipher(
"Hello World 123",3))
print(cipher(
"Hello World 123",13))
print(cipher(
"Hello World 123",9))
#end of program


1.8.2019

#1.8.2019 - Shashi
#program to autogenerate hashtags based on string inputs
#conditions : no spaces, first letter of each word uppercase, length <=140 and non-empty.

def gen_hash(s):
   
if not s:
       
return False #check for empty string
   
else:
       s= s.title()    
#capitalize first letter of every word
       s = s.replace(
" ","") #get rid of all size spaces
       
       
if len(s) < 140: #if length of final output is <140 characters
           
return '#'+s #return hashtag
       
else:
           
return False #else return false
   
print (gen_hash("coding   total rox")) #regular string with diff. size spacing
print (gen_hash(" o n e ")) #single character check
print (gen_hash("cs education chat a")) #combination check
print (gen_hash("")) #empty string check
print (gen_hash("sO2a7fTQx7Ls0Ca5RJj1CnTWxVyQtQWm0BVfAFtPtLqL8HflVsTIYos3OILHAzXqEDDNrTBVXawrs7xmh1cDdRRKda6JlNmU0yPvXOLE2z6QruByD0F3bUiCueK3WZ5zUhpZGN4XCzg2")) #long text
#end of program


1.7.2019

#1.7.2019
#Program that accepts a string and returns the first non repeating letter from it. Case insensitive.

def first_non_repeating_letter(string): #function starts here
    sLower = string.lower()
#convert original word/sentence into lower case so both cases can be included
   
   
for char in string: #loop through each character/letter in the string
       
if sLower.count(char.lower()) == 1: #if lower count of this character in this string is only 1/non-repeating
           
return char #return that character back
   
return "N/A" #if none found then return N/A
 
#test calls
print(first_non_repeating_letter(
'Hi there!')) #i
print(first_non_repeating_letter(
'abracadabra')) #c
print(first_non_repeating_letter(
'Happy New Year!')) #H
print(first_non_repeating_letter(
'aAbBcCDd')) #N/A


1.6.2019

#1.6.2019
#Return highest scoring word with a=1, b=2, c=3, ... z=26.
#all input is lower case and valid.

def highestScore(sentence): #function starts here
   words=sentence.split(
' ') #split the sentence based on space and make an array
   scoreslist = []
#create list for holding scores for each word
   
for word in words: #loop through each word in the sentence
       score = [sum([ord(char) -
96 for char in word])] # critical line : each character of each word's value is loaded and total added via sum()
       scoreslist.append(score)
#final score for that word added to scoreslist
       
#loop continues until all words are processed.
   
return words[scoreslist.index(max(scoreslist))] #max(scoresList[]) returns the highest value which is sent to .index() that pulls out its position
                                                   
#words[positon] then is the specific word that has highest score.    

print(highestScore(
"hakuna matata. what a wonderful phrase!"))
print(highestScore(
"wishing everyone a happy new year with a lot of zzzzz"))


1.5.2019

#1.5.2019 - Shashi
#Convert improper fractions to mixed numbers.
#Example: 14/4 = 3 2/4.

def convert(s):
   numbers = s.split(
"/") #split the string based on / symbol to separate numbers
   numbers = list(map(int, numbers))
#convert string array to integer for the math
   whole = numbers[
0]//numbers[1] #whole number is first number/second number
   remainder = (numbers[
0]%numbers[1]) #capture remainder of the division
   converted = str(whole) +
" " + str(remainder) + "/" + str(numbers[1]) #format final solution
   
return converted #return final solution for print
   

print(convert(
"14/4")) #prints 3 2/4
print(convert(
"48/7")) #prints 6 6/7
print(convert(
"9/4")) #prints 2 1/4
#end of program


1.4.2019

#1.4.2019
#Program to count how many ways a number can be added from 1 to N.
#Example : sum_ways(3) > 1+1+1, 2+1, 3+0 > 3 ways
#sum_ways(5) > 1+1+1+1+1, 1+4, 2+3, 0+5, 1+1+3, 1+1+1+2, 1+2+2 > 7 ways

def sum_ways(n): #function accepts the initial number
 
return recur_sum(n, 0, 1) #recursive call to function that does the counting
 
def recur_sum(n, current, index): #params: initial number, 0 and 1.
   
if current == n: #if n already current value, return 1
       
return 1
   
if current > n: #if current value greater than initial number, return 0
       
return 0
   
   count =
0 #else we start counting
   
for i in range(index, n+1): #first pass: loop from 1 until (n+1)
       count += recur_sum(n, current+i, i)
#recursive call that incrementally adds to counts value as long as loop is true
       
   
return count #return count when loop done.
   
#test function with diff. values
num =
10
print(
"There are",sum_ways(num), "ways to add", num)
num=
15
print(
"There are",sum_ways(num), "ways to add", num)
num=
5
print(
"There are",sum_ways(num), "ways to add", num)


1.3.2019

#1.3.2019 - Shashi
#Write a program to find the sum of intervals of ranges in an array.
#overlapping intervals should only be counted once.

def sum_of_intervals(ranges): #function starts here
   sum = set()
#to create a collection of items
   
for x,y in ranges: #loop through all data sets
       
for i in range(x,y): #loop within each data set
           sum.add(i)
#add every number that is in that range.
   
   
return(len(sum)) #every element added is contributing to sum. so size of final set returned.


print(sum_of_intervals([[
1,2],[6,10],[11,15]])) #1+4+4 = 9
print(sum_of_intervals([[
1,5],[3,6],[8,10]])) #1-5 and 3-6 have overlapping numbers. So, 1-6 = 5 and 8-10 = 2 = 5+2 =7
print(sum_of_intervals([[
11,22],[6,10],[11,15]])) #11-22 covers 11-15 so 11. 6-10 = 4. So, 11+4 = 15.
#end of program


1.2.2019

#2.1.2019 - Given a 3x3 array for a Tic-Tac-Toe game, check the state of the board via a function.
#Assume that the board comes in the form of a 3x3 array, where the value is 0 if a spot is empty,
#1 if it is an "X", or 2 if it is an "O", like so:
#-1 if the board is not yet finished (there are empty spots),
#1 if "X" won,
#2 if "O" won,
#0 if it's a cat's game (i.e. a draw).

def checkState(board): #2d array sent in
 
for i in range(0,3): #loop from 0 until 3 for i
   
if board[i][0] == board[i][1] == board[i][2] != 0: #if none of the rows contain 0s, return what exists in entire row aka winner
     
return board[i][0]
   
elif board[0][i] == board[1][i] == board[2][i] != 0: #if none of the columns contains 0s, return what exists in entire col aka winner
     
return board[0][i]
     
 
if board[0][0] == board[1][1] == board[2][2] != 0: #if left diagonal doesn't contains 0s, return what exists in diagonal, aka winner
   
return board[0][0]
 
elif board[0][2] == board[1][1] == board[2][0] != 0: #same for right diagonal
   
return board[0][0]

 
elif 0 not in board[0] and 0 not in board[1] and 0 not in board[2]:
   
return 0 #for a draw, aka no one won
 
else:
   
return -1 #0s exist, aka game not finished yet.

   


#check function
board = [[
0, 0, 1],
        [
0, 1, 2],
        [
2, 1, 0]]
print(checkState(board))
#0s exist so it will return -1
board = [[
0, 0, 2],
        [
0, 1, 2],
        [
2, 1, 2]]
print(checkState(board))
#O has won so it will return 2


1.1.2019

#1.1.2019 - Shashi
#Write a program that accepts values via multiple function arguments
#and returns the sum of them back.

def add(num): #function call
   
return SelfFunction(num) #call to SelfFunction() that holds retained and new value sums
   
class SelfFunction(int): #called as return function from within add()
   
def __call__(self, num): #__call__ is a built in that returns a new instance of itself
       
return SelfFunction(self + num) #returns last retained  + new number

#function calls for different sets of values
print(add(
1)(4)(6))
print(add(
13)(-5))
print(add(
10)(6)(2)(9))
#end of program