What conversion is being used in these commands-- multiples of 16? - io

I'm controlling a board that has 16 outputs in two groups #1: 1-8, #2: 9-16.
The first part of the command is the group [1,...] or [2,...]
The second part is the output, so in the limited examples I am shown [1,1,...] would turn on [group 1, channel 1, ....]-- so far so good.
The next example is Output 8: [1, 128, ...]
The next example is Outputs 1 & 8: [1, 129, ...]
What is this conversion called? I'm assuming the outputs map as follows, is this correct:
Output 1 (or 9): 1
Output 2 (or 10): 16
Output 3 (or 11): 32
...
Output 8 (or 16): 128
So if I wanted outputs 2 & 3 the command would be [1, 48]?

You work with bits. 10000000 means turn on output 8. 10000000 in binary means 128 in decimal. If you wanted output 7 you’d do 1000000 which is 64 in decimal. Most programming languages would let you do something like 0x01001100 for example to turn on 7,4 and 3. Easier to work in binary.

The generic formula for you to find the value to set 1 output would be:
second_part = 2^(output_to_set - 1)
For multiple outputs, you just need to add them.
So if you want to set, outputs 2 and 3:
second_part = 2^1 + 2^2 = 6

Related

Program does not run faster as expected when checking much less numbers for finding primes

I made a program to find primes below a given number.
number = int(input("Enter number: "))
prime_numbers = [2] # First prime is needed.
for number_to_be_checked in range(3, number + 1):
square_root = number_to_be_checked ** 0.5
for checker in prime_numbers: # Checker will become
# every prime number below the 'number_to_be_checked'
# variable because we are adding all the prime numbers
# in the 'prime_numbers' list.
if checker > square_root:
prime_numbers.append(number_to_be_checked)
break
elif number_to_be_checked % checker == 0:
break
print(prime_numbers)
This program checks every number below the number given as the input. But primes are of the form 6k ± 1 only. Therefore, instead of checking all the numbers, I defined a generator that generates all the numbers of form 6k ± 1 below the number given as the input. (I added 3 also in the prime_numbers list while initializing it as 2,3 cannot be of the form 6k ± 1)
def potential_primes(number: int) -> int:
"""Generate the numbers potential to be prime"""
# Prime numbers are always of the form 6k ± 1.
number_for_function = number // 6
for k in range(1, number_for_function + 1):
yield 6*k - 1
yield 6*k + 1
Obviously, the program should have been much faster because I am checking comparatively many less numbers. But, counterintuitively the program is slower than before. What could be the reason behind this?
In every six numbers, three are even and one is a multiple of 3. The other two are 6-coprime, so are potentially prime:
6k+0 6k+1 6k+2 6k+3 6k+4 6k+5
even even even
3x 3x
For the three evens your primality check uses only one division (by 2) and for the 4th number, two divisions. In all, five divisions that you seek to avoid.
But each call to a generator has its cost too. If you just replace the call to range with the call to create your generator, but leave the other code as is(*), you are not realizing the full savings potential.
Why? Because (*)if that's the case, while you indeed test only 1/3 of the numbers now, you still test each of them by 2 and 3. Needlessly. And apparently the cost of generator use is too high.
The point to this technique known as wheel factorization is to not test the 6-coprime (in this case) numbers by the primes which are already known to not be their divisors, by construction.
Thus, you must start with e.g. prime_numbers = [5,7] and use it in your divisibility testing loop, not all primes, which start with 2 and 3, which you do not need.
Using nested for loop along with square root will be heavy on computation, rather look at Prime Sieve Algorithm which is much faster but does take some memory.
One way to use the 6n±1 idea is to alternate step sizes in the main loop by stepping 2 then 4. My Python is not good, so this is pseudocode:
function listPrimes(n)
// Deal with low numbers.
if (n < 2) return []
if (n = 2) return [2]
if (n = 3) return [2, 3]
// Main loop
primeList ← [2, 3]
limit ← 1 + sqrt(n) // Calculate square root once.
index ← 5 // We have checked 2 and 3 already.
step ← 2 // Starting step value: 5 + 2 = 7.
while (index <= limit) {
if (isPrime(index)) {
primeList.add(index)
}
index ← index + step
step ← 6 - step // Alternate steps of 2 and 4
}
return primeList
end function

function with multiple outputs in python 3

I have problem that I could not figured out yet. In this problem I want to assemble chocolates in ordered way. To do this I have function called chocolate() and seven inputs which are
final weight (27)
number of smaller chocolates (4)
weight of smaller chocolates (2)
number of medium chocolates (4)
weight of medium chocolates (5)
number of large chocolates (3)
weight of large chocolates (8)
The problem wants from me to use as much as large chocolate then medium them small ones and finally return to (number of final small chocolates in final, number of medium chocolates in final, number of large chocolates in final). Actually it looks easy but I am not sure about how can I use functions with multiple inputs and then return to multiple outputs. IF you can help me about how can I start I would be very glad and continue to write a proper code, I hope.
Here some example
input: 27 4 2 4 5 3 8
output: 3 1 2
I imagined that your goal is packing the chocolates, starting with the big ones first and trying to reach the target weight if possible.
The below returns the packed choc sizes and also the packed weight, as it may not always be possible to exactly match the target weight.
As you may know, this is a known problem called 'bin packing' with better solutions than the 'first-fit decreasing' approach below (which assumes only one bin).
def chocolates(final_weight, num_small_choc, w_small_choc, num_medium_choc, w_medium_choc, num_big_choc, w_big_choc):
packed_weight = 0
# Try to pack chocolates if they are not too big
def pack_choc(packed_weight, num_choc, w_choc):
while num_choc > 0:
if packed_weight + w_choc <= final_weight:
packed_weight += w_choc
num_choc -= 1
else:
break
return packed_weight, num_choc
packed_weight, remaining_big_choc = pack_choc(packed_weight, num_big_choc, w_big_choc)
packed_weight, remaining_medium_choc = pack_choc(packed_weight, num_medium_choc, w_medium_choc)
packed_weight, remaining_small_choc = pack_choc(packed_weight, num_small_choc, w_small_choc)
return num_small_choc - remaining_small_choc, num_medium_choc - remaining_medium_choc, num_big_choc - remaining_big_choc, packed_weight
>>> chocolates(27, 4, 2, 4, 5, 3, 8)
... (1, 0, 3, 26)

Can anybody explain me print statement in this code?

I found this code on internet but I am not able to understand how the print statement is working.
I have already tried to see many answers but none answers it perfectly.
def main():
n=int(raw_input())
for i in range(0, 1<<n):
gray=i^(i>>1)
print "{0:0{1}b}".format(gray,n),
main()
for i in range(0, 1<<n):
Here, 1 << n shifts 1 by n bits to left. It means:
if n = 1, 1 << 1 would be 10,
n = 2, 1 << 10 would be 100 [2 = binary 10]
and so on.
For decimal number the answer is equivalent 2 to the power n.
For binary 'n' number of zeros are added.
So the range is for i in range(0, 2 ** n).
gray=i^(i>>1)
Here i>>1 shifts i by 1 bit to right. It means:
if i = 1, 1 >> 1 would be 0,
i = 2, 10 >> 1 would be 1 [2 = binary 10]
i = 3, 100 >> 1 would be 10 (in binary) 2 in decimal
and so on.
For decimal numbers it is equivalent to dividing by 2 (and ignoring digits after . decimal point).
For binary last digit is erased.
^ is exclusive OR operator. It is defined as:
0 ^ 0 = 0,
0 ^ 1 = 1 ^ 0 = 1,
1 ^ 1 = 0
print "{0:0{1}b}".format(gray,n)
Here {1} refers to n, b refers to binary. So gray is converted to binary and expressed in n digits.
What you are looking at is known by the concept of Advanced string formatting. Specifically, PEP 3101 Advanced string Formatting
You may refer the official documentation for understanding purposes.

problem with rounding in calculating minimum amount of coins in change (python)

I have a homework assignment in which I have to write a program that outputs the change to be given by a vending machine using the lowest number of coins. E.g. £3.67 can be dispensed as 1x£2 + 1x£1 + 1x50p + 1x10p + 1x5p + 1x2p.
However, I'm not getting the right answers and suspect that this might be due to a rounding problem.
change=float(input("Input change"))
twocount=0
onecount=0
halfcount=0
pttwocount=0
ptonecount=0
while change!=0:
if change-2>=0:
change=change-2
twocount+=1
else:
if change-1>=0:
change=change-1
onecount+=1
else:
if change-0.5>=0:
change=change-0.5
halfcount+=1
else:
if change-0.2>=0:
change=change-0.2
pttwocount+=1
else:
if change-0.1>=0:
change=change-0.1
ptonecount+=1
else:
break
print(twocount,onecount,halfcount,pttwocount,ptonecount)
RESULTS:
Input: 2.3
Output: 10010
i.e. 2.2
Input: 3.4
Output: 11011
i.e. 3.3
Some actually work:
Input: 3.2
Output: 11010
i.e. 3.2
Input: 1.1
Output: 01001
i.e. 1.1
Floating point accuracy
Your approach is correct, but as you guessed, the rounding errors are causing trouble. This can be debugged by simply printing the change variable and information about which branch your code took on each iteration of the loop:
initial value: 3.4
taking a 2... new value: 1.4
taking a 1... new value: 0.3999999999999999 <-- uh oh
taking a 0.2... new value: 0.1999999999999999
taking a 0.1... new value: 0.0999999999999999
1 1 0 1 1
If you wish to keep floats for output and input, multiply by 100 on the way in (cast to integer with int(round(change))) and divide by 100 on the way out of your function, allowing you to operate on integers.
Additionally, without the 5p, 2p and 1p values, you'll be restricted in the precision you can handle, so don't forget to add those. Multiplying all of your code by 100 gives:
initial value: 340
taking a 200... new value: 140
taking a 100... new value: 40
taking a 20... new value: 20
taking a 20... new value: 0
1 1 0 2 0
Avoid deeply nested conditionals
Beyond the decimal issue, the nested conditionals make your logic very difficult to reason about. This is a common code smell; the more you can eliminate branching, the better. If you find yourself going beyond about 3 levels deep, stop and think about how to simplify.
Additionally, with a lot of branching and hand-typed code, it's very likely that a subtle bug or typo will go unnoticed or that a denomination will be left out.
Use data structures
Consider using dictionaries and lists in place of blocks like:
twocount=0
onecount=0
halfcount=0
pttwocount=0
ptonecount=0
which can be elegantly and extensibly represented as:
denominations = [200, 100, 50, 10, 5, 2, 1]
used = {x: 0 for x in denominations}
In terms of efficiency, you can use math to handle amounts for each denomination in one fell swoop. Divide the remaining amount by each available denomination in descending order to determine how many of each coin will be chosen and subtract accordingly. For each denomination, we can now write a simple loop and eliminate branching completely:
for val in denominations:
used[val] += amount // val
amount -= val * used[val]
and print or show a final result of used like:
278 => {200: 1, 100: 0, 50: 1, 10: 2, 5: 1, 2: 1, 1: 1}
The end result of this is that we've reduced 27 lines down to 5 while improving efficiency, maintainability and dynamism.
By the way, if the denominations were a different currency, it's not guaranteed that this greedy approach will work. For example, if our available denominations are 25, 20 and 1 cents and we want to make change for 63 cents, the optimal solution is 6 coins (3x 20 and 3x 1). But the greedy algorithm produces 15 (2x 25 and 13x 1). Once you're comfortable with the greedy approach, research and try solving the problem using a non-greedy approach.

How to generate 1825 numbers with a step of 0.01 in a specific range

In the following code I want to get len(a) should be 1825 keeping step 0.01. But when I print len(a) it gives me 73. For getting length of 1825 I have to generate numbers from 2.275 to 3 with a step of 0.01 ,73 times. How can I do that? I tried to use np.linspace but that command doesn't work for this case.
a = np.arange(2.275, 3, 0.01)
Seems like you want to np.random.choice 1825 times
>>> a = np.arange(2.275,3,0.01)
>>> c = np.random.choice(a, 1825)
array([2.995, 2.545, 2.755, ..., 2.875, 2.275, 2.605])
>>> c.shape
(1825,)
Edit
If you want a repeated 25 times (i.e. 1825/73) in sequence, use np.tile()
target = 1825
n = target/len(a)
np.tile(a, int(n))
yields
array([2.275, 2.285, 2.295, ..., 2.975, 2.985, 2.995])
Here's a one liner, given a = np.arange(2.275, 3, 0.01) and n = 1825:
a = np.broadcast_to(a, (n // a.size + book(n % a.size), a.size)).ravel()[:n]
This uses np.broadcast_to to turn a into a matrix where it repeats itself enough times to fill 1825 elements. ravel then flattens the repeated list and the final slice chops off the unwanted elements. The ravel operation is what actually copies the list since the broadcast uses stride tricks to avoid copying the data.

Resources