Check if number can be displayed using seven segment led in Python

Suppose we have a number n and a constraint c. We need to check whether n can be displayed using 7-segment displays with at most c LEDs. Each digit requires a different number of LED segments to be illuminated.

For example, if the input is n = 315 and c = 17, the output will be True since 315 needs 12 LEDs (3 needs 5, 1 needs 2, 5 needs 5) and we have 17 available.

Seven Segment Display LED Count: 0: 6 LEDs 1: 2 LEDs 8: 7 LEDs

Algorithm Steps

To solve this problem, we follow these steps:

  • Create a list containing LED counts for digits 0-9: [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]
  • Convert the number n to a string to access individual digits
  • Initialize led_count to 0
  • For each digit in the string, add its LED count to led_count
  • Return True if led_count ? c, otherwise return False

Implementation

# LED count for each digit 0-9
seg = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]

def solve(n, c):
    s = str(n)
    led_count = 0
    
    for digit_char in s:
        digit = int(digit_char)
        led_count += seg[digit]
    
    return led_count <= c

# Test the function
n = 315
c = 17
result = solve(n, c)
print(f"Number {n} with {c} LEDs available: {result}")

# Show the calculation
s = str(n)
total = sum(seg[int(digit)] for digit in s)
print(f"LED breakdown: 3({seg[3]}) + 1({seg[1]}) + 5({seg[5]}) = {total} LEDs")
Number 315 with 17 LEDs available: True
LED breakdown: 3(5) + 1(2) + 5(5) = 12 LEDs

LED Count Reference

Digit 0 1 2 3 4 5 6 7 8 9
LED Count 6 2 5 5 4 5 6 3 7 8

Additional Example

seg = [6, 2, 5, 5, 4, 5, 6, 3, 7, 6]

def solve(n, c):
    s = str(n)
    led_count = sum(seg[int(digit)] for digit in s)
    return led_count <= c

# Test with different numbers
test_cases = [(123, 15), (888, 20), (1111, 8)]

for num, leds in test_cases:
    result = solve(num, leds)
    actual_leds = sum(seg[int(d)] for d in str(num))
    print(f"Number {num} needs {actual_leds} LEDs, limit {leds}: {result}")
Number 123 needs 12 LEDs, limit 15: True
Number 888 needs 21 LEDs, limit 20: False
Number 1111 needs 8 LEDs, limit 8: True

Conclusion

This solution efficiently checks if a number can be displayed on a 7-segment display within LED constraints. We map each digit to its LED count and sum them up for comparison with the available LED limit.

Updated on: 2026-03-25T15:21:24+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements