Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมหาจำนวนลูกบอลมากที่สุดในกล่อง (Digit Sum) ใน Python

โจทย์

มีลูกบอลหมายเลข l ถึง r ใส่ในกล่องที่หมายเลข = ผลรวมหลักของหมายเลขลูกบอล (เช่น 123 → กล่อง 6) หากมี l และ r ให้หาจำนวนลูกบอลมากที่สุดในกล่องใดกล่องหนึ่ง

ตัวอย่าง: l=15, r=25 → กล่อง 6 และ 7 มีลูกบอลมากที่สุด = 2 ลูก

อัลกอริธึม

  1. ใช้ Dictionary นับจำนวนลูกบอลต่อกล่อง
  2. วน i จาก l ถึง r คำนวณ Digit Sum
  3. เพิ่ม Count ใน Dictionary
  4. คืนค่า Max ของ Values

โค้ด Python


def solve(l, r):
    dict = {}
    for i in range(l, r + 1):
        total = 0
        for j in str(i):
            total += int(j)
        if total not in dict:
            dict[total] = 0
        dict[total] += 1
    return max(dict.values())

l, r = 15, 25
print(solve(l, r))  # Output: 2

Input / Output

Input:  15, 25
Output: 2