How to print python Byte variable? - python-3.x

I have this byte variable
testByte = b"\x02\x00\x30\x03\x35"
I would like to print it out
I've tried:
listTestByte = list(testByte)
However, I'm getting
[2, 0, 48, 3, 35]
I'm expecting it to be:
[2, 0, 30, 3, 35]

What you have are hexadecimal values. So what you're getting is what you should be getting. (Except that you should be getting [2, 0, 48, 3, 53] and not [2, 0, 48, 3, 35].)
If you want the list to have what you have in hexadecimal you can try converting it back to hexadecimal.
testByte = b"\x02\x00\x30\x03\x35"
listTestByte = list(testByte)
print(listTestByte) # [2, 0, 48, 3, 53]
listTestByteAsHex = [int(hex(x).split('x')[-1]) for x in listTestByte]
print(listTestByteAsHex) # [2, 0, 30, 3, 35]
Or use string operations, to split at '\x' depending on your purpose.

Related

What is the Easiest way to extract subset of a 2D matrix in python?

mat = [[0, 1, 2, 3, 4, 5],
[6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]]
Lets say I want to extract upper left 2x2 matrix
[[0, 1,],
[6, 7, ]]
doing mat2=mat[:2][:2] doesnt work.
It extracts the rows correctly but not columns.Seems like I need to loop throughto get the columns.
Additionally I need to do a deepcopy to mat2 suchthat modifying mat2 dont change mat.
This is because [:2] returns a list containing the first 2 elements of your matrix.
For example :-
arr = [[1, 2], [1, 3]]
print(arr[:2]) # will print the first 2 elements of the array, that is [1, 2] and [1, 3], packed into a list. So, Output : [[1, 2], [1, 3]].
In the same way,
mat = [[0, 1, 2, 3, 4, 5],
[6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23],
[24, 25, 26, 27, 28, 29],
[30, 31, 32, 33, 34, 35]]
mat2 = mat[:2] # => [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]
# Now, if you again try to get the first 2 elements from mat2 you will get the first 2 elements of mat2, not the first 2 elements of the lists inside mat2.
mat3 = mat2[:2] # => [[0, 1, 2, 3, 4, 5], [6, 7, 8, 9, 10, 11]]
That is where you went wrong, but this concept is quite counter-intuitive, so no worries.
So the solution would be to get the first 2 elements from matrix mat and then loop over its elements and then get the first 2 elements from them.
Therefore, this should work for you:
list(x[:2] for x in mat[:2])
Or, as #warped pointed, if you can use numpy, you can do the following:
import numpy as np
mat = np.array(mat)
mat[:2, :2]

How to select the elements of a numpy array without using loop?

I am doing crossover, so i want to replace the elements of matrix (m1) with another matrix (m2) Image for your reference(elements in green box has to be replaced).
How to do this without using loop?
Assume that your both arrays contain:
a: b:
array([[ 0, 1, 2, 3], array([[100, 101, 102, 103],
[ 4, 5, 6, 7], [104, 105, 106, 107],
[ 8, 9, 10, 11]]) [108, 109, 110, 111]])
and you want to copy elements from a to b through the "filter"
that you defined.
To do it, create a mask:
of size just like a, initially filled with 0,
fill left upper corner (2 rows by 2 columns) with 1.
The code to do it is:
msk = np.zeros_like(a)
msk[0:2, 0:2] = 1
So its content is:
array([[1, 1, 0, 0],
[1, 1, 0, 0],
[0, 0, 0, 0]])
And now copy b to a through this mask:
a = np.where(msk, a, b)
getting:
array([[ 0, 1, 102, 103],
[ 4, 5, 106, 107],
[108, 109, 110, 111]])
As you wish, without any loop.
Another solution (a one-liner) is:
a = np.where(np.array([[1,1,0,0], [1,1,0,0], [0,0,0,0]]), a, b)
You can simply use fancy indexing for that. Either use the elements of m1 to replace it in m2 or the other way round.
m3 = m2.copy()
m3[:2,:2] = m1[:2,:2]

How to return a dictionary with increasing swap using bubblesort to sort a list of random integers?

I am trying to return a similar output in the doctest but when the function is called, I get the amount of times the item has been swapped and also the sorted list.
I tried creating a variable for an empty dictionary and tried to include the returned function inside, but I do not know how to.
def bubbleSort(numList):
num_dict = {}
for j in range(1, len(numList)):
swap_check = False
for i in range(len(numList)-1):
if numList[i] > numList[i + 1]:
numList[i], numList[i + 1] = numList[i + 1], numList[i]
swap_check = True
return numList
if swap_check == False:
break
return j, numList
expected result:
Takes a list and returns 2 values
1st returned value: a dictionary with the state of the list after each complete pass of bubble sort
2nd returned value: the sorted list
>>> bubbleSort([9,3,5,4,1,67,78])
({1: [3, 5, 4, 1, 9, 67, 78], 2: [3, 4, 1, 5, 9, 67, 78], 3: [3, 1, 4, 5, 9, 67, 78], 4: [1, 3, 4, 5, 9, 67, 78], 5: [1, 3, 4, 5, 9, 67, 78]}, [1, 3, 4, 5, 9, 67, 78])
Actual result:
>>> bubbleSort([9,3,5,4,1,67,78])
(5, [1, 3, 4, 5, 9, 67, 78])
So the reason you got (5, [1, 3, 4, 5, 9, 67, 78]) as your output is because the last time through the loop j = 5 and [1, 3, 4, 5, 9, 67, 78] is your sorted list which is what you are returning from your function. return j, numList
We can use your num_dict dictionary to store the results of the sorting algorithm as we iterate through the list.
num_dict[j] = num_list[:]
Because we are mutating num_list I make a copy of the list when we store the result of the sort in num_dict. num_list[:] just returns a copy of num_list.
Here it is in the completed function:
def bubble_sort(num_list):
num_dict = {}
for j in range(1, len(num_list)):
swap_check = False
for i in range(len(num_list)-1):
if num_list[i] > num_list[i + 1]:
num_list[i], num_list[i + 1] = num_list[i + 1], num_list[i]
swap_check = True
# store result of sort iteration
num_dict[j] = num_list[:]
if swap_check == False:
break
return num_dict, num_list
And now we get this when we run the bubble_sort function:
>>> bubble_sort([9,3,5,4,1,67,78])
({1: [3, 5, 4, 1, 9, 67, 78],
2: [3, 4, 1, 5, 9, 67, 78],
3: [3, 1, 4, 5, 9, 67, 78],
4: [1, 3, 4, 5, 9, 67, 78],
5: [1, 3, 4, 5, 9, 67, 78]},
[1, 3, 4, 5, 9, 67, 78])

indexing through an array in blocks

I have an image represented as an array (img), and I'd like to make many copies of the image, and in each copy zero out different squares of the image (in the first copy zero out 0:2,0:2 in the next copy zero out 0:2, 3:5 etc). I've used np.broadcast_to to create multiple copies of the image, but I'm having trouble indexing through the multiple copies of the image, and the multiple locations within the images to zero out squares within the image.
I think I'm looking for something like skimage.util.view_as_blocks, but I need to be able to write to the original array, not just read.
The idea behind this is to pass all the copies of the image through a neural network. The copy that performs the worst should be the one with the class (picture) I am trying to identify in its zero'd out location.
img = np.arange(10*10).reshape(10,10)
img_copies = np.broadcast_to(img, [100, 10, 10])
z = np.zeros(2*2).reshape(2,2)
Thanks
I think I have cracked it! Here's an approach using masking along a 6D reshaped array -
def block_masked_arrays(img, BSZ):
# Store shape params
m = img.shape[0]//BSZ
n = m**2
# Make copies of input array such that we replicate array along first axis.
# Reshape such that the block sizes are exposed by going higher dimensional.
img3D = np.tile(img,(n,1,1)).reshape(m,m,m,BSZ,m,BSZ)
# Create a square matrix with all ones except on diagonals.
# Reshape and broadcast it to match the "blocky" reshaped input array.
mask = np.eye(n,dtype=bool).reshape(m,m,m,1,m,1)
# Use the mask to mask out the appropriate blocks. Reshape back to 3D.
img3D[np.broadcast_to(mask, img3D.shape)] = 0
img3D.shape = (n,m*BSZ,-1)
return img3D
Sample run -
In [339]: img
Out[339]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]])
In [340]: block_masked_arrays(img, BSZ=2)
Out[340]:
array([[[ 0, 0, 2, 3],
[ 0, 0, 6, 7],
[ 8, 9, 10, 11],
[12, 13, 14, 15]],
[[ 0, 1, 0, 0],
[ 4, 5, 0, 0],
[ 8, 9, 10, 11],
[12, 13, 14, 15]],
[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 0, 0, 10, 11],
[ 0, 0, 14, 15]],
[[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 0, 0],
[12, 13, 0, 0]]])

List modification using dictionarys (Python)

I have the following:
list = [['1234-4321-1',[5, 6, -4, 11, 22]], ['8763-1234-1', [43, -5, 0, 0, -1]], ['1234-5376-1', [3, 0, -5, -6, 0]]]
.
reversed__dict = {'8763-1234-1'}
I want to write a loop that iterates over list and when it detects the reversed value held in reversed_dict to rearrange the string permanently (change to '1234-8763-1' i.e. first two segments swapped) and also multiply it's corresponding int values by -1.
I have tried the following:
for i, x in list:
if i in ordered_dict:
p = (x * -1)
return list[p]
But I just keep getting 'return' and syntax errors, also this does not attempt to rearrange the '8763-1234-1'
desired end result is:
>>list
>>[['1234-4321-1',[5, 6, -4, 11, 22]], ['1234-8763-1', [-43, 5, 0, 0, 1]], ['1234-5376-1', [3, 0, -5, -6, 0]]]
help much, much appreciated.
for val in lst:
num = val[0]
if num in reversed_set:
parts = num.split('-')
val[0] = '-'.join([parts[1], parts[0], parts[2]])
>> lst
[['1234-4321-1', [5, 6, -4, 11, 22]], ['1234-8763-1', [43, -5, 0, 0, -1]], ['1234-5376-1', [3, 0, -5, -6, 0]]]
By the way, {'8763-1234-1'} is not a dict, it's a set. And it is not a good idea to use "list" as a name of a variable.
Also, what did you try to achieve by multiplying the list by -1?

Resources