#09-1###################################################
"""The code below prints the numbers from 1 to 50.
Rewrite the code using a while loop to accomplish the
same thing.
for i in range(1,51):
    print(i,end=" ")
"""

##num = 1
##print()
##while num < 51:
##    print(num,end=" ")
##    num+=1
    

#09-2####################################################
"""(a) Write a program that uses a while loop (not a for
loop) to read through a string and print the characters
of the string one-by-one on separate lines. (b) Modify
the program above to print out every second character of
the string"""

##s = "Sorry"
##num =0
##while num < len(s):
##    print(s[num])
##    num += 1   ## a()
##print()   
##num =0
##while num < len(s):
##    print(s[num])   
##    num += 2 ## b



#09-3######################################################
"""A good program will make sure that the data its users
enter is valid. Write a program that asks the user for a
weight and converts it from kilograms to pounds. Whenever
the user enters a weight below 0, the program should tell
them that their entry is invalid and then ask them again
to enter a weight. [Hint: Use a while loop, not an if
statement].

"""

##weight =eval(input("Enter your weight in kilograms: "))
##while (weight < 0):
##     weight = eval(input("Your entry is invalid. Please re-enter: "))
##pounds = weight * 2.2
##print("Your weight in pounds is",pounds)

#or:
##while True:
##    weight =eval(input("Enter Weight in Kg: "))
##    if weight < 0:
##        print("Illegal weight entered")
##    else:
##        pounds = weight * 2.2
##        print("Your weight in Pounds is",pounds)
        

#09-4######################################################
"""Write a program that asks the user to enter a password.
If the user enters the right password, the program should
tell them they are logged in to the system. Otherwise,
the program should ask them to reenter the password. The
user should only get five tries to enter the password,
after which point the program should tell them that they
are kicked off of the system."""

##import sys
##correctPW ="pw"
##tries = 0
##response=input("Enter password: ")
##while (response != correctPW ):
##    tries += 1  
##    print("Incorrect. You have",5-tries,"left. ",end=" ")
##    response = input("Please re-enter: ")     
##    if (response != correctPW  and tries == 4):
##        print("Too many tries. You are kicked off the system")
##        sys.exit()    
##print("You are logged in")


#09-5######################################################
"""Write a program that allows the user to enter any number
of test scores. The user indicates they are done by entering
in a negative number. Print how many of the scores are A’s
(90 or above). Also print out the average."""


##scores=[]
##countScores = 0
##countAs = 0
##totalPoints = 0
##scoreIn = eval(input("Enter a test score or negative number to exit: "))
##while (scoreIn >= 0):
##    countScores += 1
##    totalPoints += scoreIn    
##    if scoreIn >= 90:
##        countAs += 1
##    scoreIn = eval(input("Enter a test score or negative number to exit: "))
##print("Total scores entered", countScores)
##print("Average score:", totalPoints/countScores)
##print("Total A's (90 or better):", countAs)
    

#09-6######################################################
"""Modify the higher/lower program so that when there is
only one guess left, it says 1 guess, not 1 guesses."""

##from random import randint
##secret_num = randint(1,100)
##num_guesses = 0
##guess = 0
##while guess != secret_num and num_guesses <= 4:
##           guess = eval(input('Enter your guess (1-100): '))
##           num_guesses  += 1
##           if 5-num_guesses == 1 and guess > secret_num:
##               print("LOWER.", 5 - num_guesses, "GUESS left")
##           elif 5 - num_guesses == 1 and guess < secret_num:
##                   print("Higher.", 5 - num_guesses, "GUESS left")
##           elif guess < secret_num and 5-num_guesses !=1:
##               print("HIGHER.", 5-num_guesses, "guesses left")
##           elif guess > secret_num and 5-num_guesses !=1:
##              print("LOWER.", 5-num_guesses, "guesses left")
##           else:
##              print('You got it!')
##           if num_guesses==5 and guess != secret_num:
##              print('You lose. The correct number is', secret_num)



#09-7######################################################
"""Recall that, given a string s, s.index('x') returns the
index of the first x in s and an error if there is no x.
(a) Write a program that asks the user for a string and a
letter. Using a while loop, the program should print the
index of the first occurrence of that letter and a message
if the string does not contain the letter. (b) Write the
above program using a for/break loop instead of a while loop."""

###a
##s1 = input("Enter a string: ")
##letter = input("Enter a letter: ")
##while (True):
##    if letter in s1:
##        print(s1.index(letter))
##        break
##    else:
##        print("Letter not found in string")
##        break
###b
##found = False
##s1 = input("Enter a string: ")
##letter = input("Enter a letter: ")
##for i in s1:
##    if i == letter:
##        print(s1.index(i))
##        found = True
##        break
##if (found== False):
##    print("Letter not found in string")


#09-8######################################################
"""The GCD (greatest common divisor) of two numbers is the
largest number that both are divisible by. For instance,
gcd(18, 42) is 6 because the largest number that both 18
and 42 are divisible by is 6. Write a program that asks the
user for two numbers and computes their gcd. Shown below is
a way to compute the GCD, called Euclid’s Algorithm.
• First compute the remainder of dividing the larger number
by the smaller number
• Next, replace the larger number with the smaller number
and the smaller number with the remainder.
• Repeat this process until the smaller number is 0. The GCD
is the last value of the larger number."""


##x=int(input("Enter the first number: "))
##y = int(input("Enter the second number: "))
##while x or y != 0:
##    if x>y :
##        remainder = x % y
##        if remainder== 0:
##            print("The GCD is",y)
##            break
##        else:
##          x = remainder
##    else:
##        remainder = y % x
##        if remainder ==0:
##            print("The GCD is",x)
##            break
##        else:
##            y = remainder


#09-9######################################################
"""
A 4000-year old method to compute the square root of 5 is
as follows: Start with an initial guess, say 1. Then
compute ((1 + (5/1)) / 2) = 3. Next, take that 3 and replace
the 1’s in the previous formula with 3’s . This gives
((3 + (5/3)) / 2) = 7/3 ≈ 2.33.
Next replace the 3 in the previous formula with 7/3. This
gives ((7/3) + (5/(7/3)))/2 = 47/21 ≈ 2.24. If you keep
doing this process of computing the formula, getting a
result, and plugging it back in, the values will eventually
get closer and closer to sqrt(5). This method works for
numbers other than 5. Write a program that asks the user
for a number and uses this method to estimate the square
root of the number correct to within 10**−10. The estimate
will be correct to within 10**−10 when the absolute value
of the difference between consecutive values is less
than 10**−10.
"""

##def validate_input(message):
##    valid = False
##    while not valid:
##        try:
##            user_input = int(input(message))
##            if user_input > 0:
##                valid = True
##            else:
##                print('\nPlease enter a positive number.')
##        except:
##            print('\nSorry, an integer was not inputted. Please enter an integer.')
##    return user_input
##def limit_squ_rt(valid_num):
##    x = 1
##    root = 10
##    while True:
##        root = round((x + (valid_num / x)) / 2, 10)
##        if abs(x - root) < 10**-10:
##            return root
##        x = root
##def main():
##    message = 'Enter a number to find the limit of the square root: '
##    valid_num = validate_input(message)
##    squ_rt = limit_squ_rt(valid_num)
##    print(f'\nThe limit of square root of {valid_num} is {squ_rt}.')
##if __name__ == '__main__':
##    main()


#09-10######################################################
"""Write a program that has a list of ten words, some of
which have repeated letters and some which don’t. Write a
program that picks a random word from the list that does not
have any repeated letters."""


##from random import randint
##word_list =["henry","laura","gaga","gagayas","monique","marina","thomas","leopold","jackson","abigail"]
##listofwords=[]
##for i in range(len(word_list)):
##    #print(words)
##    for j in range(len(word_list[i])):
##        #print(word_list[i][j], "----j") #You can use this print statement to understand code
##        for k in range(j+1,len(word_list[i])):
##           # print(word_list[i][k],"---k")            
##          if word_list[i][j] == word_list[i][k]:
##              if word_list[i] not in listofwords:
##                  listofwords.append(word_list[i])
####Random Selection not implemented
##print(listofwords)


#09-11######################################################
"""Write a program that starts with an 5 X 5 list of zeroes
and randomly changes exactly ten of those zeroes to ones."""


##from random import randint
##list1 =  [0,0,0,0,0,
##          0,0,0,0,0,
##          0,0,0,0,0,
##          0,0,0,0,0,
##          0,0,0,0,0,]
##i = 0
##totalZeros = len(list1)
##while (i < 10):
##    elementNum = randint(0, totalZeros-1)
##    if (list1[elementNum] != 1):
##        list1[elementNum] = 1
##        i = i+1
##print(list1)


#09-12######################################################
"""Write a program in which you have a list that contains
seven integers that can be 0 or 1. Find the first nonzero
entry in the list and change it to a 1. If there are no
nonzero entries, print a message saying so."""

##from random import randint
##L = [randint(0, 1) for i in range(7)]
##print('The initial list is the following: ')
##print(L)
##print('')
##valid = False
##while not valid:
##    try:
##         i = L.index(0)
##         print(f'The first zero occurs at index {i}.')
##         print('\nThe new list is the following: ')
##         L[i] = 1
##         print(L)
##         valid = True
##    except ValueError:
##        print('There are no zero entries.')
##        break


#09-14######################################################    
"""
Write a program to play the following simple game. The
player starts with $100. On each turn a coin is flipped and
the player has to guess heads or tails. The player wins $9
for each correct guess and loses $10 for each incorrect
guess. The game ends either when the player runs out of
money or gets to $200.
"""

##from enum import Enum
##from random import choice
##class coin(Enum):
##    FACE = {'h':'Heads', 't':'Tails'}
##MONEY = 100
##def heads_tails(MONEY):
##    while 0 < MONEY < 200:
##        rand_face = coin_face()
##        message = 'Enter "h" for heads or "t" for tails: '
##        user_guess = validate_input(message)
##        print(rand_face)
##        if rand_face == user_guess:
##            MONEY += 9
##            print(f'You guessed right! You now have ${MONEY}.')
##        else:
##            MONEY -= 10
##            print(f'You guessed wrong! You now have ${MONEY}.')
##    if MONEY < 0:
##        print('You do not have any more money to play.')
##    else:
##        print(f'You have ${MONEY}. Good job. Good-bye.')    
##def coin_face():
##    rand_face = choice(list(coin.FACE.value.keys()))
##    return rand_face    
##def validate_input(message):
##    valid = False
##    while not valid:
##        try:
##            user_input = input(message)
##            user_input = user_input.lower()
##            if (user_input == 'h') or (user_input == 't'):
##                valid = True
##            else:
##                print('\nPlease enter "h" or "t".')
##        except:
##            pass
##    return user_input
##def main():
##    print('Welcome to Heads and Tails.')
##    print('')
##    print(f'You have ${MONEY} to start with.')
##    print('')
##    print('If you guess right, you get $9. If you guess wrong, you lose $10.')
##    heads_tails(MONEY)    
##if __name__ == '__main__':
##    main()

    

#09-15######################################################  
"""
Write a program to play the following game. There is a list
of several country names and the program randomly picks one.
The player then has to guess letters in the word one at a
time. Before each guess the country name is displayed with
correctly guessed letters filled in and the rest of the
letters represented with dashes. For instance, if the
country is Canada and the player has correctly guessed
a, d, and n, the program would display -ana-da. The program
should continue until the player either guesses all of the
letters of the word or gets five letters wrong.
"""

##from random import choice
##from string import ascii_lowercase
##from re import finditer
##from sys import exit
##COUNTRY_LIST = ['canada', 'england', 'japan', 'china', 'germany', 'scotland', 
##                'chad', 'ghana', 'mexico', 'ireland', 'korea', 'denmark']
##def game_on():
##    num_guesses = 5
##    country = get_country(COUNTRY_LIST)
##    country_placeholder = country
##    for i in country:
##        country = country.replace(i, '*')
##    while num_guesses > 0:
##        print(country)
##        message = 'Enter a letter to guess: '
##        guess = validate_letter(message)
##        if guess in country_placeholder:
##            valid_letter = [x.start() for x in finditer(guess, country_placeholder)]
##            for j in valid_letter:
##                country = country[:j] + country[j].replace('*', guess) + country[j+1:]
##        else:
##            num_guesses -= 1
##            print(f'No "{guess}" in the country\'s name. You have {num_guesses} number of guesses left.\n')
##        win_lose(num_guesses, country, country_placeholder)
##def get_country(COUNTRY_LIST):
##    rand_country = choice(COUNTRY_LIST)
##    return rand_country
##def validate_letter(message):
##    valid = False
##    while not valid:
##        try:
##            user_input = input(message)
##            if (user_input in ascii_lowercase) and (len(user_input) == 1):
##                valid = True
##            else:
##                print('\nPlease enter a valid letter as a guess: ')
##        except:
##            pass
##    return user_input
##def win_lose(num_guesses, country, country_placeholder):
##    if num_guesses == 0:
##        print(f'You ran out of guesses. The country is {country_placeholder.capitalize()}. You lose.')
##    elif country == country_placeholder:
##        print(f'\nYes the country was {country.capitalize()}.')
##        print('You Win!')
##        exit()
##    else:
##        pass
##def main():
##    print('Welcome to the Country Guessing Game')
##    print('You have 5 guesses.\n')
##    game_on()
##if __name__ == '__main__':
##    main() 



#09-16######################################################   
"""
Write a text-based version of the game Memory. The game
should generate a 5 × 5 board (see the exercise from
Chapter 8). Initially the program should display the board
as a 5 × 5 grid of asterisks. The user then enters the
coordinates of a cell. The program should display the grid
with the character at those coordinates now displayed. The
user then enters coordinates of another cell. The program
should now display the grid with the previous character and
the new character displayed. If the two characters match, then
they should permanently replace the asterisks in those
locations. Otherwise, when the user enters the next set of
coordinates, those characters should be replaced by asterisks.
The game continues this way until the player matches everything
or runs out of turns. You can decide how many turns they player
gets.
"""

##from string import ascii_lowercase
##from random import sample, shuffle
##from pprint import pprint
##import numpy as np
##from sys import exit
##COOR = [0,1,2,3]
##def create_board():
##    # From string module, imported all corresponding characters and grouped them together in source variable.
##    source = ascii_lowercase    
##    # Using sample function from random module, grabbed 18 random characters from source string.
##    # After which, the random chars cloned to create pairs for memory game. 
##    # Note, sample returns a list.
##    chars = sample(source, 8) * 2    
##    # Used shuffle function to randomize the list of characters
##    shuffle(chars)    
##    # Used numpy instead of list comprehensions to create an array of the chars at a 4x4 size.
##    # After which, the array was converted to a list using the .tolist() method.
##    L = np.array(chars).reshape(4,4).tolist()
##    return L
##def create_asterisks_board(board):
##    M = [['*' for coulmn in row] for row in board]
##    return M
##def game_on(board, asterisks_board):
##    pprint(asterisks_board)
##    pprint(board) # DELETE LATER
##    N = 10
##    while N > 0:
##        user_coor_1 = get_coor()
##        print(f'\nFirst set of coordinates are {user_coor_1}.\n')
##        print(board[user_coor_1[0]][user_coor_1[1]])
##        user_coor_2 = get_coor()
##        print(f'\nSecond set of coordinates are {user_coor_2}.\n')
##        print(board[user_coor_2[0]][user_coor_2[1]])
##        asterisks_board, N = check_coors(user_coor_1, user_coor_2, board, asterisks_board, N)
##        win_lose_check(board, asterisks_board, N)
##        pprint(asterisks_board)    
##def get_coor():
##    message = 'Enter row: '
##    row = validate_coor(message, COOR)
##    message = 'Enter column: '
##    column = validate_coor(message, COOR)
##    return row, column
##def validate_coor(message, COOR):
##    valid = False
##    while not valid:
##        try:
##            user_input = int(input(message))
##            if user_input in COOR:
##                valid = True
##            else:
##                print('\nEnter a valid coordinate number.')
##        except ValueError:
##            print('\nEnter a valid integer.')
##    return user_input
##def check_coors(user_coor_1, user_coor_2, board, asterisks_board, N):
##    if user_coor_1 == user_coor_2:
##        N -= 1
##        print(f'\nThose are the same coordinates...no. You have {N} chances left.')    
##    elif board[user_coor_1[0]][user_coor_1[1]] == board[user_coor_2[0]][user_coor_2[1]]:
##        asterisks_board[user_coor_1[0]][user_coor_1[1]] = board[user_coor_1[0]][user_coor_1[1]]
##        asterisks_board[user_coor_2[0]][user_coor_2[1]] = board[user_coor_2[0]][user_coor_2[1]]
##    else:
##        N -= 1
##        print(f'\nNot a match. You have {N} chances left.')
##    return asterisks_board, N
##def win_lose_check(board, asterisks_board, N):
##    if board == asterisks_board:
##        print('You win')
##        exit()
##    elif N == 0:
##        print('You lose\n')
##        pprint(board)    
##        exit()
##    else:
##        pass
##def main():
##    print('Welcome to the Memory Game')
##    print('You have 10 chances to find all of the letter pairs.')
##    print('You must input the coordinates from 0 to 3 for the position on the 4x4 board.\n')
##    board = create_board()
##    asterisks_board = create_asterisks_board(board)
##    game_on(board, asterisks_board)    
##if __name__ == '__main__':
##    main()
    

#09-17######################################################    


'''Ask the user to enter the numerator and denominator of a
fraction, and the digit they want to know. For instance, if
the user enters a numerator of 1 and a denominator of 7 and
wants to know the 4th digit, your program should print out 8,
because 1/7 = .142856... and 8 is the 4th digit. One way to
do this is to mimic the long division process you may have
learned in grade school. It can be done in about five lines
using the // operator at one point in the program
'''


##num = eval(input('Enter numerator: '))
##denum = eval(input('Enter denumerator: '))  
##digit = int(input('Enter the digit you want to know: '))
##i = 0
##l=[]
##while i < digit+1:   
##    result=num//denum 
##    mod=num%denum
##    num=mod*10
##    l.append(str(result))
##    i+=1
##u=l[-1]    
###l.insert(1,'.')
###v = ''.join(l)
###print(v) ''' to print out all the digits'''
##print(f'The digit is {u}' )


#09-18######################################################    
"""
Randomly generate a 6 × 6 list that has exactly 12 ones
placed in random locations in the list. The rest of the
entries should be zeroes.
"""

##from pprint import pprint
##from random import randint
##L = [[0 for column in range(6)]for row in range (6)]
##i = 0
### Must use a while loop instead of for loop because can not repeat iterations.
##while i < 12:
##    a, b = randint(0, 5), randint(0, 5)
##    if L[a][b] == 1:
##        pass
##    else:
##        L[a][b] = 1
##        i += 1
##pprint(L)

 
