Using Python 3.6.0 Consider the following code. It is supposed to take a list of
ID: 3828461 • Letter: U
Question
Using Python 3.6.0
Consider the following code. It is supposed to take a list of numbers from the user. Make a new list containing only the numbers which are multiples of 2. Finally it is supposed to print these numbers 5 numbers in a line.
It uses two functions ispow2 which takes a number n and returns the boolean value True if that number is a power of 2 otherwise False.
print5 which takes a list and prints the list 5 numbers per line separated by spaces.
Please write code the correct ispow2 and print5 functions and submit the complete program. Everything in main() is already correct.
def ispow2(n):
<your code here>
def print5(lst):
<your code here>
def main():
lst = input("Please enter the list")
nums = [int(j) for j in lst.split()]
newlst = []
for i in nums:
if (ispow2(i)):
newlst.append(i)
print5(newlst)
main()
Sample output:
Please enter the list:2 4 8 5 7 9 2 4 8 2 16 17
2 4 8 2 4
8 2 16
Explanation / Answer
#This function check n number is power of 2 or not
#It will return true if n is power of 2 else it retrun false
def ispow2(n):
if n == 0:
return False
while n!=1:
if n%2 != 0:
return False
n=n/2
return True
#This function will print the lst 5 elements in one line
def print5(lst):
start=0
for p in lst:
if start<5:
print(p, end=" ")
start= start +1
else :
print()
start=0
print()
lst = input("Please enter the list")
nums = [int(j) for j in lst.split()]
newlst = []
for i in nums:
if (ispow2(i)):
newlst.append(i)
print5(newlst)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.