Home > Net >  Python nested loops with if statements: Replacing values inside a range
Python nested loops with if statements: Replacing values inside a range

Time:07-09

Question

Given a range from 0 to 30, output all the integers inside the range with the following requirements:

I. Replace all the numbers that aren't divisible by 3 with Asterisk symbol(*);

II. Replace all the numbers inside range(10, 15) and range(20, 25) with Underscores(_).

Sample Output

0 * * 3 * * 6 * * 9 _ _ _ _ _ _ * * 18 * _ _ _ _ _ _ * 27 * * 30

My Codes:

range1 = range(10, 16)
range2 = range(20, 26)
for i in range(0, 31):
    while i not in range1 or range2:
        if i % 3 == 0:
            print(i, end = " ")
            break
        elif i % 3 != 0:
            print('*', end = " ")
            break
    else:
        print('_', end = " ")

My Output:

0 * * 3 * * 6 * * 9 * * 12 * * 15 * * 18 * * 21 * * 24 * * 27 * * 30

I am struggling with my codes since I've tried many times my codes failed to replace the numbers inside both ranges, it always skips the range check and outputs *. Any helpful ideas are appreciated, I hope I can improve my logic mindset instead of just getting the answers.

CodePudding user response:

You can't use i not in range1 or range2, I suggest to use set union for efficiency. Also the while loop is useless, a simple test is sufficient.

NB. trying to keep an answer as close as possible to your original code here.

ranges = set(range(10, 16)) | set(range(20, 26))

for i in range(0, 31):
    if i not in ranges:
        if i % 3 == 0:
            print(i, end = " ")
        elif i % 3 != 0:
            print('*', end = " ")
    else:
        print('_', end = " ")

output: 0 * * 3 * * 6 * * 9 _ _ _ _ _ _ * * 18 * _ _ _ _ _ _ * 27 * * 30

ranges: {10, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 25}

CodePudding user response:

It's so easy and simple to do it without extra ranges:

for i in range(0, 31):
    if (10 <= i <= 16) or (20 <= i <= 26):
        print('_', end=' ')
    elif i % 3 != 0:
        print('*', end=' ')
    else:
        print(i, end=' ')

CodePudding user response:

Do not use range, use a simpler and more efficient syntax of chained comparisons instead. Simplify your if condition as well: there is no need to check twice whether the number is divisible by 3. Skip break too. Separate creation of the list using append and printing of the list, which you do after the list is created (creation of the data and its printing are best kept separate).

lst = []
for i in range(31):
    if 10 <= i <= 15 or 20 <= i <= 25:
        lst.append('_')
    elif i % 3:
        lst.append('*')
    else:
        lst.append(i)

print(' '.join(str(x) for x in lst))
# 0 * * 3 * * 6 * * 9 _ _ _ _ _ _ * * 18 * _ _ _ _ _ _ * 27 * * 30

# You can also use a simpler `print` to give the same result, 
# as suggested by *QwertYou*:
print(*lst)
  • Related