Saturday, May 23, 2026

Week 4 Notes


# Python Problem Solver
# Week 4 Example 1: Gauss, method 1
#

# Define total
total = 0

# Iterative approach
# Note this loop runs 100 times
for i in range(1, 101):
    total += i

print(total)

# Python Problem Solver
# Week 4 Example 1: Gauss, method 2
#

# Define total
total = 0

# Gauss approach
# Note this is only one line, and runs only once
total = (1 + 100) * 100 / 2

print(total)

# Python Problem Solver
# Week 4 Example 2: Metronome App
#

import time
import os

def metronome(bpm, timeSignature):
   beatInterval = 60 / bpm
   beatsPerMeasure = timeSignature.split('/')[0]

   while True:
      for beat in range(1, int(beatsPerMeasure) + 1):
         if beat == 1:
            os.system("clear")
            print("*** Metrononome App ***")
            print("----------------------")
            print("BPM: "+ str(bpm))
            print("Time Signature: "+ str(timeSignature))
            print("----------------------")
            print("> tick (" + str(beat) + ")")
         else:
            print("> tock (" + str(beat) + ")")
         time.sleep(beatInterval)

#Main Program Starts Here...
print("*** Metrononome App ***")
print("----------------------")
bpm = int(input("Enter BPM: "))
timeSignature = input("Enter time signature (e.g., 4/4): ")
metronome(bpm, timeSignature)

# Python Problem Solver
# Week 4 Example 3: Election II (AIO 2022 P1)
#

import sys
sys.setrecursionlimit(1000000000)

# N is the number of votes.
N = 0

# votes contains the sequence of votes.
votes = ""

answer = None

# Read the value of N and the votes.
N = int(input().strip())
votes = input().strip()

# TODO: This is where you should compute your solution. Store the winning
# candidate ('A', 'B' or 'C'), or 'T' if there is a tie, into the variable
# answer.

a = 0
b = 0 
c = 0

for v in votes[:N]:
    if v == 'A':
        a += 1
    elif v == 'B':
        b += 1
    elif v == 'C':
        c += 1

if a > b and a > c:
    answer = 'A'
elif b > a and b > c:
    answer = 'B'
elif c > a and c > b:
    answer = 'C'
else:
    answer = 'T'

# Write the answer.
print(answer)

No comments:

Post a Comment

Week 8 Assignments