Social Items

Showing posts with label Coding. Show all posts
Showing posts with label Coding. Show all posts
import random

def has_questionmark(qus):
 wordlist = qus.split()
 last_word = wordlist[-1]
 split_last_word = list(last_word)
 if '?' in split_last_word:
  return True


def has_special_words(qus):
 wordlist = qus.split()
 first_word = wordlist[0]
 first_word = first_word.lower()
 special_words = ['what', 'where', 'when', 'how', 'why', 'are','do','did']
 if first_word in special_words:
  return True
  
def is_a_yn_question(qus):
 wordlist = qus.split()
 first_word = wordlist[0]
 first_word = first_word.lower()
 special_words = ['do', 'did', 'are']
 if first_word in special_words:
  return True

def is_a_question(qus):
 if has_questionmark(qus) or has_special_words(qus):
  return True
  

print('\nSpeak to me!')
while True:
 question = input('')
 if question == 'q':
  break
 if is_a_question(question):
  if is_a_yn_question(question):
   choice = random.randint(0,1)
   if choice:
    print('Yes.\n')
   else:
    print('No...\n')
  
  
  
  
  
 else:
  print('This is not a question.')

Conversation Machine

This code is to find out the 3-digit numbers that have their digits add up to 9. The problem was originated from the "Problem of the week" from the university of Waterloo. The original question is stated here: https://www.cemc.uwaterloo.ca/resources/potw/2019-20/English/POTWD-19-NA-02-P.pdf

The digit positive integer is the sum of all of its digits. For example, the digit sum of the integer 1234 is 10, since 1 + 2+ 3 + 4 = 10. Find all three-digit positive integers whose digit sum is exactly 9.

This is the answer that I got, it can also be found out through running the code by pressing the green button:

108
117
126
135
144
153
162


Well, but there is another problem that I do not know how to solve. The problem can be found here: https://www.cemc.uwaterloo.ca/resources/potw/2019-20/English/POTWE-19-AE-02-P.pdf. If you find out the answer, please leave a comment!

POTW - It all adds up

Grade 9 Computer Science class has started. Although I have learned how to code in C and Python before, I have never drawn a flowchart. I had planned for my code, but not as precise as a flowchart. My first flowchart, a super easy one, to find the largest and smallest number from the 5 numbers, can be found here.

Largest and Smallest Number Flowchart

In the past week (July 1 to July 2), I participated in a coding camp organized by the ID Tech organization called "Intro to Coding for Machine Learning". I found the camp so exciting. I have learned to code before, but never with other students or a formal teacher (Dad taught me C and Python before). The first few days of the camp was about the basics of the basics, as some people in our class are beginners. Although I learned things that I have learned before in the first few days, I did many interesting projects. We made some small games such as Hangman and Tic Tac Toe, BattleBots that can compete with each other. We also did some bigger project like basic Machine Learning with a self-built Neuron Network and TensorFlow (though I did not really know what the difference is between these two). I will continue to learn Machine Learning in my next camp the week after next week. What I am going to show here is some interesting projects that I did.

Below is the Hangman Game in Python, which is my second favorite project:
-----

# Hangman Game
import random

secret_word = random.choice(["apple", 'banana', 'orange', 'strawberry', 'blueberry', 'watermelon', 'melon', 'mouse', 'delicious', 'python'])
trials = 15
win = False
# two lists
wordlist = list(secret_word)
blanks = []
i = len(secret_word)
while i > 0:
    blanks.append('-')
    i -= 1

# guessing starts
while trials > 0:
    if win:
        break
    else:
        user_guess = input("Guess: ")
        trials -= 1
        times = 0 #which letter
        for i in wordlist:
            if user_guess == i:
                blanks[times] = wordlist[times]
                print('Yes! "' + user_guess + '" is in the word!')

            times += 1

        if user_guess not in wordlist:
            print('Sorry, "' + user_guess + '" is not in the word! You have ' + str(trials) + " trials left.")

        for j in blanks:
            print(j, end='')
        print("\n")

        if '-' not in blanks:
            print('Congrats! You guessed the word! It is "' + secret_word + '"!')
            win = 1
            
        
if trials == 0:
    print('Sorry, you already tried for 15 times. The word is "' + secret_word + '", please play the game again!')
-----

This is still considered as an easy one (actually it is extremely easy. Lol I spent 1 hour on this).

Another game, my favorite, is the Tic Tac Toe Game:

-----
class Board:
    
    def __init__(self):
        self.spots = []
        for i in range(9):
            self.spots.append(None)

    def checkwin(self):
        
        for i in range (0, 9, 3):
            if (self.spots[i]==self.spots[i+1] == self.spots[i+2]) and self.spots[i] != None:
                return True
        
        for i in range(3):
            if (self.spots[i] == self.spots[i+3] == self.spots[i+6]) and self.spots[i] != None:
                return True
            
        if (self.spots[0] == self.spots[4] == self.spots[8]) and self.spots[0] != None:
            return True
        
        if (self.spots[2] == self.spots[4] == self.spots[6]) and self.spots[2] != None:
            return True
        
        return False

    def printSpot(self, spotNum: int):
        if self.spots[spotNum] == None:
            return spotNum
        else:
            return self.spots[spotNum]

    def print_board(self):
        print(" ", self.printSpot(0), " | ", self.printSpot(1), " | ", self.printSpot(2))
        print("-----|-----|-----")
        print(" ", self.printSpot(3), " | ", self.printSpot(4), " | ", self.printSpot(5))
        print("-----|-----|-----")
        print(" ", self.printSpot(6), " | ", self.printSpot(7), " | ", self.printSpot(8))
    
        
    def placesign(self, playerplace):
        if current_player == player1:
            self.spots[int(playerplace)] = player1sign
        elif current_player == player2:
            self.spots[int(playerplace)] = player2sign

# Start            
my_board = Board()
player1 = input("Player 1, please type your name: ")
while True:
    player1sign = input(player1 + ", please type your mark (O or X): ")
    if str(player1sign) == "O" or str(player1sign) == "X":
        break
    else:
        print("Sorry, that's not an 'O' or 'X'!")
print("Hello, " + player1 + "!")
player2 = input("Player 2, please type your name: ")
if player1sign == "O":
    player2sign = "X"
else:
    player2sign = "O"
print("Hello, " + player2 + "!")
current_player = player1

trials = 0
win = False
chosed = []
print("This is the board:")
my_board.print_board()

# Loop Starts
while trials < 9:
    if current_player == player1:
        while True:
            playerplace = input(player1 + ", please make your move (1 - 9): ")
            if playerplace in chosed:
                print("Sorry, the place was already taken!")
            elif playerplace not in chosed:
                chosed.append(playerplace)
                break
        my_board.placesign(playerplace)
        my_board.print_board()
    else:
        while True:
            playerplace = input(player2 + ", please make your move (1 - 9): ")
            if playerplace in chosed:
                print("Sorry, the place was already taken!")
            elif playerplace not in chosed:
                chosed.append(playerplace)
                break
        my_board.placesign(playerplace)
        my_board.print_board()
    
    if my_board.checkwin() == True:
        win = True
        break
    print(current_player)
    if current_player == player1:
        current_player = player2
    else:
        current_player = player1
    
    trials += 1

if win == True:
    print("Congratulations! " + current_player.title() + " wins!")
elif win == False:
    print("This is a draw! Play the game again!")

This program is much longer and has included the use of class, loops, and methods. I actually felt so proud of myself as a beginner after seeing this works, with no errors when I play it with my mum. (Mum was like: "Is this what you learned for the whole week? There's nothing special about it!", thinking: "There are much better ones on the web!") Dad (Programming as his first job after his graduation) was kind of surprised for what I have done (and confused how I could make so many errors). Anyway, I like these games a lot and if you want to have a try, please try here:

Hangman:
Tic Tac Toe:
Despite these, we also have lots of happy memories at the id tech camp!



ID Tech Camp: Intro to Coding for Machine Learning