Sunday, March 26, 2017

Flatten a list

# Paste your function here
def flatten(aList):
    '''
    aList: a list
    Returns a copy of aList, which is a flattened version of aList
    '''
    flattened_list = []
    for item in aList:
        if type(item) == type([]):
            flattened_list.extend(flatten(item))
        else:
            flattened_list.append(item)
    return flattened_list

1. Two Sum

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        a_dict = {}
        for i in range (0, len(nums)):
            x = nums[i]
            y = target - nums[i]
            if y in a_dict:
                return (a_dict[y], i)
            else:
                a_dict[x] = i 

Thursday, March 16, 2017

Guess a word from a list of words

# Hangman game
#

# -----------------------------------
# Helper code
# You don't need to understand this helper code,
# but you will have to know how to use the functions
# (so be sure to read the docstrings!)

import random
import string

WORDLIST_FILENAME = "words.txt"

def loadWords():
    """
    Returns a list of valid words. Words are strings of lowercase letters.
   
    Depending on the size of the word list, this function may
    take a while to finish.
    """
    print("Loading word list from file...")
    # inFile: file
    inFile = open(WORDLIST_FILENAME, 'r')
    # line: string
    line = inFile.readline()
    # wordlist: list of strings
    wordlist = line.split()
    print("  ", len(wordlist), "words loaded.")
    return wordlist

def chooseWord(wordlist):
    """
    wordlist (list): list of words (strings)

    Returns a word from wordlist at random
    """
    return random.choice(wordlist)

# end of helper code
# -----------------------------------

# Load the list of words into the variable wordlist
# so that it can be accessed from anywhere in the program
wordlist = loadWords()

def isWordGuessed(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: boolean, True if all the letters of secretWord are in lettersGuessed;
      False otherwise
    '''
    for i in secretWord:
        if i not in lettersGuessed:
            return False
    return True



def getGuessedWord(secretWord, lettersGuessed):
    '''
    secretWord: string, the word the user is guessing
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters and underscores that represents
      what letters in secretWord have been guessed so far.
    '''
    wordguessed=""
    for i in secretWord:
        if i not in lettersGuessed:
            wordguessed += "_ "
        else:
            wordguessed += i
    return wordguessed



def getAvailableLetters(lettersGuessed):
    '''
    lettersGuessed: list, what letters have been guessed so far
    returns: string, comprised of letters that represents what letters have not
      yet been guessed.
    '''
    allletters=string.ascii_lowercase
    availableletters=""
    for i in allletters:
        if i not in lettersGuessed:
            availableletters += i
    return availableletters
   

def hangman(secretWord):
    '''
    secretWord: string, the secret word to guess.

    Starts up an interactive game of Hangman.

    * At the start of the game, let the user know how many
      letters the secretWord contains.

    * Ask the user to supply one guess (i.e. letter) per round.

    * The user should receive feedback immediately after each guess
      about whether their guess appears in the computers word.

    * After each round, you should also display to the user the
      partially guessed word so far, as well as letters that the
      user has not yet guessed.

    Follows the other limitations detailed in the problem write-up.
    '''
    n=8
    lettersGuessed = []
    while n >= 1:
        if isWordGuessed(secretWord, lettersGuessed):
            print ("Congratulations, you won!")
        else:
            print ("Welcome to the game, Hangman!")
            print ("You have "+ str(n) + " guesses left.")
            print ("Available letters: " + getAvailableLetters(lettersGuessed))
            guess = input ("Please think of a letter: ")
            guessInLowerCase = guess.lower()
            lettersGuessed.append (guessInLowerCase)
            print ("Good guess: " + getGuessedWord(secretWord, lettersGuessed))
        n-=1
    print ("Sorry, you ran out of guesses. The word was else.")
      






# When you've completed your hangman function, uncomment these two lines
# and run this file to test! (hint: you might want to pick your own
# secretWord while you're testing)

# secretWord = chooseWord(wordlist).lower()
# hangman(secretWord)

Wednesday, March 15, 2017

Dictionary in Python

Find the value with the maximum length in a dictionary:

def biggest(aDict):
    '''
    aDict: A dictionary, where all the values are lists.

    returns: The key with the largest number of values associated with it
    '''
    # Your Code Here
    result = None
    maximum = 0
    for key in aDict.keys():
        if len(aDict[key]) >= maximum:
            result=key
            maximum = len(aDict[key])
    return result

Returns the sum of the number of values associated with a dictionary

def how_many(aDict):
    '''
    aDict: A dictionary, where all the values are lists.

    returns: int, how many values are in the dictionary.
    '''
    # Your Code Here
    result=0
    for key in aDict.keys():
        result+=len(aDict[key])
    return result

Sunday, March 12, 2017

Binary search to find a character in a str

def isIn(char, aStr):
    '''
    char: a single character
    aStr: an alphabetized string
   
    returns: True if char is in aStr; False otherwise
    '''
    # Your code here
    if aStr == '':
        return False
    if len (aStr) == 1:
        return char == aStr
    midindex = len(aStr)//2
    midchar = aStr [midindex]
    if char == midchar:
        return True
    elif char < midchar:
        return isIn (char, aStr[:midindex])
    else:
        return isIn (char, aStr[midindex+1:])

Saturday, March 11, 2017

guess my number

newnumber=int(input ("Please think of a number between 0 and 100!"))
begin=0
end=100
answer=str()
while answer!='c':
    guessnumber=int((begin+end)/2)
    print ("Is your secret number ", guessnumber)
    answer=str(input ("Enter 'h' to indicate the guess is too high. Enter 'l' \
    to indicate the guess is too low. \
    Enter 'c' to indicate I guessed correctly."))
    if answer=='h':
        end=guessnumber
    elif answer=='l':
        begin=guessnumber
    elif answer=='c':
        print ("Game over. Your secret number was:", guessnumber)
    else:
        print ("Sorry, I did not understand your input.")

***************************************************************************

print("Please think of a number between 0 and 100!")

# At the start the highest the number could be is 100 and the lowest is 0.
hi = 100
lo = 0
guessed = False

# Loop until we guess it correctly
while not guessed:
    # Bisection search: guess the midpoint between our current high and low guesses
    guess = (hi + lo)//2
    print("Is your secret number " + str(guess)+ "?")
    user_inp = input("Enter 'h' to indicate the guess is too high. Enter 'l' to indicate the guess is too low. Enter 'c' to indicate I guessed correctly. ")

    if user_inp == 'c':
        # We got it right!
        guessed = True
    elif user_inp == 'h':
        # Guess was too high. So make the current guess the highest possible guess.
        hi = guess
    elif user_inp == 'l':
        # Guess was too low. So make the current guess the lowest possible guess.
        lo = guess
    else:
        print("Sorry, I did not understand your input.")

print('Game over. Your secret number was: ' + str(guess))

Wednesday, March 8, 2017

Write a program that prints the longest substring of s


Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = 'azcbobobegghakl', then your program should print

Longest substring in alphabetical order is: beggh
In the case of ties, print the first substring. For example, if s = 'abcbcd', then your program should print

Longest substring in alphabetical order is: abc
Note: This problem may be challenging. We encourage you to work smart. If you've spent more than a few hours on this problem, we suggest that you move on to a different part of the course. If you have time, come back to this problem after you've had a break and cleared your head.


s=str(input('Please enter your string: ')).lower()
letter=str()
i=0
length=len(s)
print (length)
for i in range (len(s)-1):
    if s[i] < s[i+1] :
        letter+=s[i]
        print (letter)
    elif s[i] >= s[i+1] :
        break
print (letter)

Find a sub string

s=str(input('Please enter your string: ')).lower()
numberofbob=0
i=0
length=len(s)
print (length)
for i in range (len(s)):
    print (s[i:i+3])
    if s[i:i+3] == 'bob' :
        numberofbob+=1
print (numberofbob)