For Loops Python Programming Discussion

For Loops Python Programming Discussion

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 (that doesn’t use looping):

Algorithm Bitpattern(number)
1 if number & (1 << 0) > 0 # check first bit
2 print(1)
3 else
4 print(0)
5 if number & (1 << 1) > 0 # check second bit
6 print(1)
7 else
8 print(0)
9 if number & (1 << 2) > 0 # check third bit
10 print(1)
11 else
12 print(0)
13 … etc.

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

Algorithm ShiftBits(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

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

"You need a similar assignment done from scratch? Our qualified writers will help you with a guaranteed AI-free & plagiarism-free A+ quality paper, Confidentiality, Timely delivery & Livechat/phone Support.


Discount Code: CIPD30



Click ORDER NOW..

order custom paper