Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Couldn't figure out how to start this Python program exercise. Can some one help me? Write 2 functions using iterations: * while loop: While loops

Couldn't figure out how to start this Python program exercise. Can some one help me?

Write 2 functions using iterations:

* while loop: While loops are iterating if statements - while a condition is true keep looping * for loop: For loops have a known start, stop and increment/decrement value to keep looping

These functions determine the binary bit-pattern of a decimal number. There are a number of bitwise operators that can be used to determine the bit-pattern. See Bitwise.py for examples of using bitwise operators. Here's a general algorithm that can be used:

Algorithm Bitpattern(number) 1 if number & (1 << 0) > 0 2 print(1) 3 else 4 print(0) 5 if number & (1 << 1) > 0 6 print(1) 7 else 8 print(0) 9 if number & (1 << 2) > 0 10 print(1) 11 else 12 print(0) 13 ... etc.

The problem will be when to stop shifting. A way to determine the number of shifts can be found using logarithms:

Algorithm ShiftsB(number) log10 = math.log(number+1) log2 = log10 / math.log(2) shifts = math.ceil(log2) return shifts

Note: To use the log or ceil function:

1. First: import math 2. To call the ceil or log function: math.log(number) or math.ceil(number)

Consequently, to determine the number of iterations for a FOR loop using decimal 10 is 4. Here's proof:

2**0 = 1 2**1 = 2 2**2 = 4 2**3 = 8

Binary(10) = 1(2**3[8]) + 0(2**2[4]) + 1(2**1[2]) + 0(2**0)[1]) = 1010

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image_2

Step: 3

blur-text-image_3

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Technology And Management Computers And Information Processing Systems For Business

Authors: Robert C. Goldstein

1st Edition

0471887374, 978-0471887379

More Books

Students also viewed these Databases questions