USING PYTHON!!!! A number is considered valid if it is a power of 2, 3 or 5 Ask
ID: 3833980 • Letter: U
Question
USING PYTHON!!!!
A number is considered valid if it is a power of 2, 3 or 5 Ask the user to enter a space separated list of numbers. Output all numbers from the entered numbers which are also valid numbers. The output should be sorted and formatted as maximum 3 numbers per line with each number right justified to a column of 10. For this program, you need to use functions. Provide code for the following: A function is Valid which takes a number as an input and returns True if the number is a power of2, 3 or 5 and False otherwise. A function printList which takes a list and prints it formatted as 3 numbers per line with each number right justified to a column of 10. After writing these two functions, within main, after the user to enter a space separated list of numbers. Thereafter, loop through the numbers entered. Check each such number using the is Valid function. Add it to a list if it is a valid number. Finally, use the printList function to print out the list you have generated in the required format.Explanation / Answer
# Code is in python 3.6
from __future__ import print_function
def power2(num): # Function to check power of 2
if(num == 1 ):
return True
else:
if(num % 2 == 0):
return power2(int(num/2))
else:
return False
def power3(num): # Function to check power of 3
if(num == 1 ):
return True
else:
if(num % 3 == 0):
return power3(int(num/3))
else:
return False
def power5(num): # Function to check power of 5
if(num == 1 ):
return True
else:
if(num % 5 == 0):
return power5(int(num/5))
else:
return False
def printList(valid_list):
valid_list.sort()
i = 0
length = len(valid_list)
while(length >= 3):
print('%10d' % valid_list[i],'%10d' % valid_list[i+1],'%10d'% valid_list[i+2])
i += 3
length -= 3
if length == 2:
print('%10d' % valid_list[i],'%10d' % valid_list[i+1])
length -= 2
if length == 1:
print('%10d'%valid_list[i])
def isValid(num):
if( power2(num)):
return True
if(power3(num)):
return True
if(power5(num)):
return True
return False
def main():
values = input('Please enter the numbers :') #take input from user should be in format "num1 num2 num3 ..."
values_list = values.split(' ') #split by space and make list
values_list = list(map(int, values_list)) # convert string list to integer list
valid_list = [] # valid_list for valid strings
for i in values_list:
if (isValid(i)):
valid_list.append(i)
printList(valid_list)
if __name__ == '__main__':
main()
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.