Skip to content
Advertisement

How can I replace items within a list in python3 using a condition?

Write a function which prints all integers between 0 and 100: For every number that is divisible by 7 or has the digit 7 print ‘boom’ instead of the number itself.

My solution so far:

JavaScript

print(boom())

Helped by: AkshayNevrekar

Question: Do you find a better way to solve this specific problem? a better algorithm? Thanks!

Advertisement

Answer

You can try this.

You need to check if i is divisible by 7 if yes then add 'BOOM' to your result list. Now if a number has digit 7 in it or not has to be checked you can typecast i to string and use in to check if 7 is present or not. If i not divisible by 7 and it doesn’t contain 7 in it then just append i to your result list.

JavaScript

JavaScript

Here, n is range and inp is string that replaces the number which has 7 in it or divisible by 7.


output

JavaScript

Try this to make your boom() complete.

JavaScript
  1. If boom() is called with no parameters then it considers n to be 101 and inp as 'BOOM'.
  2. If boom(n=x) is called then it considers range to be x+1 and inp as 'BOOM'
  3. If boom(inp=any_string) is called then it considers range to be 101 and inp as any_string.
  4. if boom(n=x,inp=any_string) is called then it considers range to be x+1 and inp to be any_string.

output

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement