387
Pe
python-exercices / files
python-exercices / level_two / ex_11.py
1.2 KB
1#!/usr/bin/env python3 2 3# Question 11 4# Level 2 5 6# Question: 7# Write a program which accepts a sequence of comma separated 4 digit binary numbers as its input 8# and then check whether they are divisible by 5 or not. The numbers that are divisible by 5 are 9# to be printed in a comma separated sequence. 10# Example: 11# 0100,0011,1010,1001 12# Then the output should be: 13# 1010 14# Notes: Assume the data is input by console. 15 16# Hints: 17# In case of input data being supplied to the question, it should be assumed to be a console input. 18 19 20def binary_to_decimal(binary): 21 """ 22 A simple approach to convert from binary. This could have been done simpler thanks to python's 23 int type: 24 25 int(binary, 2) 26 27 This function is equivalent to the line above. 28 """ 29 decimal = 0 30 for n in binary: 31 decimal = decimal * 2 + int(n) 32 33 return decimal 34 35 36def divisible_by_five(): 37 numbers_raw = input('Enter a list of binary numbers, seperated by commas\n') 38 success_numbers = [] 39 40 for n in numbers_raw.split(','): 41 if binary_to_decimal(n) % 5 == 0: 42 success_numbers.append(n) 43 44 print(",".join(success_numbers)) 45 46 47if __name__ == '__main__': 48 divisible_by_five()