0% found this document useful (0 votes)
1 views14 pages

GoogleTrends Python Guide

The document is a guide for a Google Trends Hackathon, detailing essential Python concepts and solutions for 10 levels of challenges without using built-in functions. It covers topics such as variables, conditional statements, loops, lists, strings, functions, and mathematical operations, providing examples and explanations for each. Additionally, it includes specific problem-solving strategies for various levels, focusing on data analysis and classification tasks.

Uploaded by

jivasrohith25
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views14 pages

GoogleTrends Python Guide

The document is a guide for a Google Trends Hackathon, detailing essential Python concepts and solutions for 10 levels of challenges without using built-in functions. It covers topics such as variables, conditional statements, loops, lists, strings, functions, and mathematical operations, providing examples and explanations for each. Additionally, it includes specific problem-solving strategies for various levels, focusing on data analysis and classification tasks.

Uploaded by

jivasrohith25
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Google Trends Hackathon

Python Concepts + Solutions Guide


No Built-in Functions | All 10 Levels

PART 1: Python Concepts You Must Know

1. Variables & Input / Output


Variables store data. input() reads from keyboard (always returns string). Use int() or float() to convert. print()
displays output.
x = input() # reads one line as string
n = int(input()) # convert to integer
score = float(input()) # convert to float

# Multiple values on one line:


a, b = input().split() # split by space -> ['a', 'b']
a, b = int(a), int(b)

# Read list of N integers in one line:


nums = input().split() # ['10','20','30']
arr = []
for val in nums:
[Link](int(val)) # manual conversion, no map()

print("Hello", x) # space-separated
print("Value:", n, end="") # no newline
print(f"Score: {score:.2f}") # f-string formatting

2. Conditional Statements (if / elif / else)


Rule: Conditions checked top-to-bottom. First True block executes, rest are skipped.
score = int(input())

if score <= 20:


print("Very Low")
elif score <= 40:
print("Low")
elif score <= 60:
print("Moderate")
elif score <= 80:
print("High")
else:
print("Trending Now")

# Nested if: if inside another if


diff = 35
if diff > 0:
if diff > 30:
print("Major difference")
else:
print("Minor difference")

3. Loops — for and while


Rule: for loop = known count. while loop = condition-based. range(n) gives 0,1,...,n-1.
# for loop with range
total = 0
for i in range(7): # i = 0,1,2,3,4,5,6
x = int(input())
total = total + x

# while loop
i = 0
while i < 7:
x = int(input())
total = total + x
i = i + 1 # always increment, else infinite loop

# Loop with index tracking


best = 0
best_idx = 0
for i in range(7):
if arr[i] > best:
best = arr[i]
best_idx = i

# Nested loops (2D data)


for row in range(3):
for col in range(7):
val = grid[row][col] # access 2D array

4. Lists (Arrays)
Rule: Lists are 0-indexed. arr[0] = first element. arr[i] to access. append() to add.
# Create empty list
arr = []

# Add elements
[Link](10)
[Link](20)

# Access
first = arr[0]
last = arr[len(arr) - 1] # no arr[-1] if avoiding builtins

# Length without len() — but len() is usually allowed


size = len(arr)

# Manual sum (no sum())


total = 0
for i in range(len(arr)):
total = total + arr[i]
# Manual max (no max())
best = arr[0]
for i in range(1, len(arr)):
if arr[i] > best:
best = arr[i]

# 2D list (list of lists)


grid = []
for r in range(3):
row = []
for c in range(7):
[Link](int(input()))
[Link](row)

5. Strings & Formatting


# f-string (formatted string literal)
avg = 66.4285
print(f"Average: {avg:.2f}") # 2 decimal places -> 66.43
print(f"Day {i+1}")

# Manual absolute value (no abs())


diff = a - b
if diff < 0:
diff = -diff

# Manual square root (no [Link]())


# Use Newton's method:
def my_sqrt(n):
if n == 0: return 0
x = n
for _ in range(100):
x = (x + n / x) / 2.0
return x

# Manual round to 2 decimal places (no round())


def my_round2(x):
return int(x * 100 + 0.5) / 100.0

6. Functions
Rule: def to define. return sends value back. Call function by name.
def classify(score):
if score <= 20: return "Very Low Interest"
elif score <= 40: return "Low Interest"
elif score <= 60: return "Moderate Interest"
elif score <= 80: return "High Interest"
else: return "Trending Now"

result = classify(85)
print(result) # Trending Now

# Function with multiple returns


def compare(s1, s2):
diff = s1 - s2
if diff < 0: diff = -diff
return diff

7. Math Without Built-in Functions


The hackathon may allow [Link]. If not, use Newton's method below.
# Square root (Newton-Raphson)
def my_sqrt(n):
if n == 0: return 0.0
x = float(n)
for _ in range(200):
x = (x + n / x) / 2.0
return x

# Absolute value
def my_abs(x):
return x if x >= 0 else -x

# Round to k decimal places


def my_round(x, k):
factor = 1
for _ in range(k): factor *= 10
return int(x * factor + 0.5) / factor

# Min / Max of two values


def my_min(a, b): return a if a < b else b
def my_max(a, b): return a if a > b else b

# Clamp value between lo and hi


def clamp(val, lo, hi):
if val < lo: return lo
if val > hi: return hi
return val
PART 2: All 10 Level Solutions (Python, No Built-ins)

LEVEL 1 — Search Volume Classifier [5 pts]


Topic: if-elif-else Input: Single integer 0-100 Output: Classification string

Classify score into 5 tiers: 0-20 Very Low, 21-40 Low, 41-60 Moderate, 61-80 High, 81-100 Trending Now.
score = int(input())

if score <= 20:


print("Very Low Interest")
elif score <= 40:
print("Low Interest")
elif score <= 60:
print("Moderate Interest")
elif score <= 80:
print("High Interest")
else:
print("Trending Now")

# Input: 85 -> Output: Trending Now


# Input: 45 -> Output: Moderate Interest

LEVEL 2 — Compare Two Search Terms [10 pts]


Topic: Nested if statements Input: term1 score1 on line1, term2 score2 on line2

Print which term is more popular (or Tie), print absolute difference, print Major difference if diff > 30 else Minor
difference.
line1 = input().split()
t1, s1 = line1[0], int(line1[1])
line2 = input().split()
t2, s2 = line2[0], int(line2[1])

# Absolute difference without abs()


diff = s1 - s2
if diff < 0:
diff = -diff

if s1 > s2:
print(t1 + " is more popular")
elif s2 > s1:
print(t2 + " is more popular")
else:
print("Tie")

print("Difference:", diff)

if diff > 30:


print("Major difference")
else:
print("Minor difference")

# Input: Python 75 / Java 45 -> Python is more popular / Difference: 30 / Minor difference

LEVEL 3 — Weekly Trend Analyzer [15 pts]


Topic: Loops Input: 7 space-separated daily scores

Compute: Total, Average (2dp), Days over 50, Best day name (Mon-Sun).
days = ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"]
nums = input().split()
scores = []
for val in nums:
[Link](int(val))

total = 0
days_over_50 = 0
best_idx = 0

for i in range(7):
total = total + scores[i]
if scores[i] > 50:
days_over_50 = days_over_50 + 1
if scores[i] > scores[best_idx]:
best_idx = i

# Average: manual division, manual rounding


avg = total / 7.0
avg_rounded = int(avg * 100 + 0.5) / 100.0

print("Total:", total)
print(f"Average: {avg_rounded:.2f}")
print("Days over 50:", days_over_50)
print("Best day:", days[best_idx], "(" + str(scores[best_idx]) + ")")

# Input: 65 70 45 80 90 55 60
# Total: 465 | Average: 66.43 | Days over 50: 6 | Best day: Friday (90)

LEVEL 4 — Heat Map Generator [20 pts]


Topic: Nested loops Input: 3 rows x 7 scores (Tech, Fashion, Food)

Print ASCII heat map: 0-20='.', 21-50='-', 51-80='+', 81-100='#'


categories = ["Tech", "Fashion", "Food"]

for i in range(3):
nums = input().split()
scores = []
for val in nums:
[Link](int(val))

row_output = categories[i] + ": "


for j in range(7):
s = scores[j]
if s <= 20:
sym = '.'
elif s <= 50:
sym = '-'
elif s <= 80:
sym = '+'
else:
sym = '#'
if j < 6:
row_output = row_output + sym + " "
else:
row_output = row_output + sym

print(row_output)

# Input row: 45 60 55 70 85 90 80
# Output: Tech: - + + + # # +

LEVEL 5 — Rising Star Detector [25 pts]


Topic: Loops + Conditionals Input: 10 daily scores

Find all sequences of 3 consecutive strictly increasing days. Output the START day (1-based) of the sequence with
the HIGHEST peak (3rd day). If none, print 'No rising star'.
nums = input().split()
s = []
for val in nums:
[Link](int(val))

best_peak = -1
best_start = -1

for i in range(8): # i = 0..7, checks s[i], s[i+1], s[i+2]


if s[i+1] > s[i] and s[i+2] > s[i+1]:
peak = s[i+2]
if peak > best_peak:
best_peak = peak
best_start = i + 1 # convert to 1-based

if best_start == -1:
print("No rising star")
else:
print("Day", best_start)

# Input: 30 45 60 55 58 62 70 65 68 72
# Sequences: days 1-3 (peak 60), days 4-6 (peak 62), days 5-7 (peak 70), days 8-10 (peak 72)
# Best peak = 72 -> Day 8

LEVEL 6 — Seasonality Pattern Matcher [30 pts]


Topic: Nested loops + stats Input: 12 monthly scores

Find longest consecutive streak of months above yearly average. If tie in length, pick streak with higher average.
Print avg, streak start/end, length.
months = ["January","February","March","April","May","June",
"July","August","September","October","November","December"]

nums = input().split()
s = []
for val in nums:
[Link](int(val))

# Yearly average (manual)


total = 0
for val in s:
total = total + val
yearly_avg = total / 12.0

print(f"Yearly avg: {yearly_avg:.2f}")

best_len = 0
best_start = -1
best_avg = 0.0

i = 0
while i < 12:
if s[i] > yearly_avg:
j = i
streak_sum = 0
while j < 12 and s[j] > yearly_avg:
streak_sum = streak_sum + s[j]
j = j + 1
length = j - i
s_avg = streak_sum / length
if length > best_len or (length == best_len and s_avg > best_avg):
best_len = length
best_start = i
best_avg = s_avg
i = j
else:
i = i + 1

if best_start == -1:
print("No streak found")
else:
end_month = months[best_start + best_len - 1]
print(f"Longest streak: {months[best_start]} to {end_month} ({best_len} months, avg {best_avg:.2f})")

# Input: 80 75 60 55 70 85 90 88 65 50 45 40
# Yearly avg: 66.92 | Longest streak: May to August (4 months, avg 83.25)
LEVEL 7 — Correlation Calculator [35 pts]
Topic: Loops + formula implementation (Pearson r)

Given 30 scores each for Term A (line 1) and Term B (line 2), compute Pearson correlation. r = sum((xi-mx)(yi-my))
/ sqrt(sum((xi-mx)^2) * sum((yi-my)^2)). Print r (3dp) and interpretation.
Pearson r measures linear relationship. >0.7=Strong positive, 0.3-0.7=Weak positive, -0.3 to 0.3=None, -0.7 to
-0.3=Weak negative, <-0.7=Strong negative.
# Manual square root (Newton's method)
def my_sqrt(n):
if n == 0: return 0.0
x = float(n)
for _ in range(200):
x = (x + n / x) / 2.0
return x

n = 30
nums_a = input().split()
nums_b = input().split()

x = []
y = []
for val in nums_a: [Link](int(val))
for val in nums_b: [Link](int(val))

# Compute means manually


sum_x = 0
sum_y = 0
for i in range(n):
sum_x = sum_x + x[i]
sum_y = sum_y + y[i]
mx = sum_x / n
my = sum_y / n

# Compute numerator and denominators


numerator = 0.0
dx2 = 0.0
dy2 = 0.0
for i in range(n):
dx = x[i] - mx
dy = y[i] - my
numerator = numerator + dx * dy
dx2 = dx2 + dx * dx
dy2 = dy2 + dy * dy

r = numerator / my_sqrt(dx2 * dy2)


print(f"Correlation: {r:.3f}")

if r > 0.7:
print("Strong positive correlation")
elif r >= 0.3:
print("Weak positive correlation")
elif r >= -0.3:
print("No correlation")
elif r >= -0.7:
print("Weak negative correlation")
else:
print("Strong negative correlation")

LEVEL 8 — Breakout Alert System [40 pts]


Topic: Nested ifs + loops (moving average) Input: n, then n scores

For each day from day 8 onward, compute 7-day moving average of PREVIOUS 7 days. If score exceeds that avg
by >= 20, it is a BREAKOUT. Print all breakouts + max.
n = int(input())
nums = input().split()
s = []
for val in nums:
[Link](int(val))

max_mag = 0.0
max_day = -1

for i in range(7, n): # day 8 onward (0-indexed: i=7,8,...)


# Average of previous 7 days: s[i-7] to s[i-1]
win_sum = 0
for j in range(i - 7, i):
win_sum = win_sum + s[j]
win_avg = win_sum / 7.0

mag = s[i] - win_avg


if mag >= 20:
print(f"Day {i+1}: score {s[i]} > avg {win_avg:.2f} by {mag:.2f} -> BREAKOUT")
if mag > max_mag:
max_mag = mag
max_day = i + 1

if max_day != -1:
print(f"Max breakout: {max_mag:.2f} on day {max_day}")
else:
print("No breakouts detected")

# n=10, scores: 50 52 55 53 54 56 55 80 60 90
# Day 8: score 80 > avg 53.57 by 26.43 -> BREAKOUT
# Day 10: score 90 > avg 59.00 by 31.00 -> BREAKOUT
# Max breakout: 31.00 on day 10

LEVEL 9 — Trending Keyword Predictor [45 pts]


Topic: All concepts + Weighted Moving Average (WMA)

Input: 28 scores = 4 weeks x 7 days. Predict next week: Pd = (1*w1 + 2*w2 + 3*w3 + 4*w4) / 10 where w1-w4 =
same day across weeks 1-4. Clamp to [0,100]. Count days > 60. Classify trend: Upward/Downward/Stable.
weeks = []
for w in range(4):
nums = input().split()
row = []
for val in nums:
[Link](int(val))
[Link](row)

pred = []
high_days = 0

for d in range(7):
p = (1 * weeks[0][d] + 2 * weeks[1][d] + 3 * weeks[2][d] + 4 * weeks[3][d]) / 10.0

# Clamp without min/max


if p > 100: p = 100
if p < 0: p = 0

# Round to nearest int


p_int = int(p + 0.5)

[Link](p_int)
if p_int > 60:
high_days = high_days + 1

output = "Predicted week:"


for val in pred:
output = output + " " + str(val)
print(output)

print("High interest days:", high_days)

if pred[6] > pred[0]:


print("Trend: Upward")
elif pred[6] < pred[0]:
print("Trend: Downward")
else:
print("Trend: Stable")

LEVEL 10 — Real-Time Anomaly Detection System [50 pts]


Topic: Mastery — all concepts, z-score, sliding window, volatility alert

Input line 1: n_days window threshold. Line 2: n_days scores. For each day after the first 'window' days, compute
mean and std of previous 'window' days. z = (score - mean) / std. SPIKE if z >= threshold, DROP if z <= -threshold.
Volatility Warning if 3+ anomalies in any 7-day window.
# Manual square root
def my_sqrt(n):
if n == 0: return 0.0
x = float(n)
for _ in range(200):
x = (x + n / x) / 2.0
return x

# Manual absolute value


def my_abs(x):
return x if x >= 0 else -x

config = input().split()
n_days = int(config[0])
window = int(config[1])
threshold = float(config[2])

nums = input().split()
s = []
for val in nums:
[Link](int(val))

anomaly_days = []
z_values = []

for i in range(window, n_days):


# Mean of window
win_sum = 0
for j in range(i - window, i):
win_sum = win_sum + s[j]
mean = win_sum / window

# Std of window (population)


var_sum = 0
for j in range(i - window, i):
diff = s[j] - mean
var_sum = var_sum + diff * diff
std = my_sqrt(var_sum / window)

if std == 0:
continue

z = (s[i] - mean) / std

if my_abs(z) >= threshold:


atype = "SPIKE" if z > 0 else "DROP"
print(f"Day {i+1}: {atype}, score={s[i]}, z={z:.2f}")
anomaly_days.append(i + 1)
z_values.append(my_abs(z))

# Volatility: 3+ anomalies in any 7-day rolling window


for i in range(len(anomaly_days)):
count = 0
r_start = anomaly_days[i]
r_end = r_start + 6
for k in range(len(anomaly_days)):
if anomaly_days[k] >= r_start and anomaly_days[k] <= r_end:
count = count + 1
if count >= 3:
print(f"Volatility Warning! Days {r_start}-{r_end}")
break

# Summary
total_z = 0.0
for val in z_values:
total_z = total_z + val

print("Summary:")
print("Total anomalies:", len(anomaly_days))
if len(anomaly_days) > 0:
avg_sev = total_z / len(anomaly_days)
print(f"Average severity: {avg_sev:.2f}")
PART 3: Quick Reference

Manual Implementations (no built-ins)


# ABSOLUTE VALUE
def my_abs(x): return x if x >= 0 else -x

# SQUARE ROOT (Newton-Raphson, ~200 iterations)


def my_sqrt(n):
if n == 0: return 0.0
x = float(n)
for _ in range(200): x = (x + n / x) / 2.0
return x

# ROUND to 2 decimal places


def round2(x): return int(x * 100 + 0.5) / 100.0

# CLAMP between lo and hi


def clamp(v, lo, hi): return lo if v < lo else (hi if v > hi else v)

# MAX of array (manual)


def arr_max(arr):
m = arr[0]
for v in arr:
if v > m: m = v
return m

# MIN of array (manual)


def arr_min(arr):
m = arr[0]
for v in arr:
if v < m: m = v
return m

# SUM of array (manual)


def arr_sum(arr):
t = 0
for v in arr: t = t + v
return t

Level Summary
Level Name Topic Pts

1 Search Volume Classifier if-elif-else 5

2 Compare Two Search Terms Nested ifs 10

3 Weekly Trend Analyzer for/while loops 15

4 Heat Map Generator Nested loops 20

5 Rising Star Detector Loops + patterns 25

6 Seasonality Matcher Nested loops + stats 30

7 Correlation Calculator Pearson formula 35

8 Breakout Alert System Moving average 40

9 Trending Keyword Predictor WMA forecasting 45


10 Anomaly Detection System Z-score + sliding window 50

Bonus Code Quality Functions + validation +20

Total = 275 pts + 20 bonus. Bronze=50, Silver=125, Gold=200, Platinum=275

You might also like