I'm a beginner in python and I'm stuck on a task I need to complete. I need to define a function that returns a list in a given range in which every time the number 7 appears or the number % 7 == 0 (no remainder), it is replaced with the word 'BOOM', otherwise the number returns the same. is needs to be done using the 'for' loop.
its supposed to look like this:
print(seven_boom(17))
['BOOM', 1, 2, 3, 4, 5, 6, 'BOOM', 8, 9, 10, 11, 12, 13, 'BOOM', 15, 16, 'BOOM']
print(seven_boom(17))
this is what ive tried and i have no idea what to do (end_number is the end of the range in the list but it needs to be included):
def seven_boom(end_number):
list = [range(0, end_number 1)]
for i in list:
if i % 7 == 0 or i[0:] == 7:
i =1
return list.replace(7, 'BOOM')
CodePudding user response:
Something like this should work:
end_number = 18
def seven_boom(end_number):
List = range(0, end_number 1)
boomList = ["BOOM" if (x%7 == 0) or ("7" in str(x)) else x for x in List ]
return boomList
CodePudding user response:
I think this can answer your question.
listEx= [x for x in range (1,20)] ## creates a list using ints from 1 to 19
def changeList(listex): # get a list as a parameter
text = 'boom' # you can change the text its the element to implement if condition meets
listnew = [item if item % 7 != 0 and '7' not in str(item) else text for item in listex ] # checks if number is divisible by 7 and changes the appending element
return listnew # return the changed list
it can be done simpler and cleaner but for now it should be enough. Also check list comprehensions in python List Comprehension
CodePudding user response:
Simply:
- creates a list in the range
- loop through the list values
- check if 7 appears in the value or if it divisible by 7
- If true, update the list value
- return updated list
def seven_boom(end_number):
#creates a list
created_list = [x for x in range(end_number 1)]
#loop through the list values
for i, v in enumerate(created_list):
#check if 7 in value or value divisible by 7
if v % 7 == 0 or '7' in str(v):
#update the list value
created_list[i] = 'boom'
#return updated list
return created_list
CodePudding user response:
I'm sure someone will edit it but next time use the curly brackets to make code easy to read. Also don't use "list" as a variable name as it is a keyword in Python. List will convert your data into a list form. I don't think leaving range in the square brackets is a good idea.
word = []
def seven_boom(end_number):
numbers = list(range(0, end_number 1))
for i in numbers:
if i % 7 ==0 or '7' in str(i):
word.append("BOOM")
else:
word.append(i)
return word