Count Assignments to Same Variable
Python
Medium
2 views
Problem Description
You will receive n lines like 'x = value'. Count how many times the same variable name appears again (2nd time onwards). Output count.
Input Format
First line n. Next n lines assignments.
Output Format
One integer count.
Sample Test Case
Input:
5
a = 1
b = 2
a = 3
c = 4
a = 5
Official Solution
import sys,re
lines=sys.stdin.read().splitlines()
if not lines or not lines[0].strip():
sys.exit(0)
n=int(lines[0].strip())
seen=set()
rep=0
for i in range(1,1+n):
line=(lines[i] if i<len(lines) else '').strip()
m=re.match(r'^([A-Za-z_][A-Za-z0-9_]*)\\s*=.*$',line)
if not m: continue
name=m.group(1)
if name in seen:
rep+=1
else:
seen.add(name)
sys.stdout.write(str(rep))
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!