Python3 ValueError: too many values to unpack with for loop - python-3.x

I've seen this same question asked around, but it's always with something like:
val1, val2 = input("Enter 2 numbers")
My problem is different.
I have two strings, str1 and str2. I want to compare them byte-by-byte such that the output would look something like this:
str1 str2
0A 0A
20 20
41 41
42 42
43 43
31 31
32 32
33 33
2E 21
So, I've tried various syntaxes to compare them, but it always ends in the same error. Here's one of my latest attempts:
#!/usr/bin/python3
for c1, c2 in (tuple("\n ABC123."), tuple("\n ABC123!")):
print("%02X %02X" % (ord(c1), ord(c2)))
And the error:
$ python3 test.py
Traceback (most recent call last):
File "test.py", line 1, in <module>
ValueError: too many values to unpack (expected 2)
Of course, this line:
for c1, c2 in (tuple("\n ABC123."), tuple("\n ABC123!")):
has gone through many different iterations:
for c1, c2 in "asdf", "asdf"
for c1, c2 in list("asdf"), list("asdf")
for c1, c2 in tuple("asdf"), tuple("asdf")
for c1, c2 in (tuple("asdf"), tuple("asdf"))
for (c1, c2) in (tuple("asdf"), tuple("asdf"))
All of which threw the same error.
I don't think I quite understand python's zipping/unzipping syntax, and I'm just about ready to resort hacking a low-level solution together.
Any ideas?

Okay, so I ended up doing this:
for char in zip(s1,s2):
print("%02X %02X" % ( ord(char[0]), ord(char[1]) ))
However, I notice that if I happen to have two lists of differing lengths, the longer list seems to get truncated at the end. For example:
s1 = "\n ABC123."
s2 = "\n ABC123!."
0A 0A
20 20
41 41
42 42
43 43
31 31
32 32
33 33
2E 21
# !! <-- There is no "2E"
So I guess I could work around that by printing the len() for each string, and then padding the shorter one to meet the longer one.

Related

replacing a value in python

I'm writing a bingo game in python. So far I can generate a bingo card and print it.
My problem is after I've randomly generated a number to call out, I don't know how to 'cross out' that number on the card to note that it's been called out.
This is the ouput, it's a randomly generated card:
B 11 13 14 2 1
I 23 28 26 27 22
N 42 45 40 33 44
G 57 48 59 56 55
O 66 62 75 63 67
I was thinking to use random.pop to generate a number to call out (in bingo the numbers go from 1 to 75)
random_draw_list = random.sample(range(1, 76), 75)
number_drawn = random_draw_list.pop()
How can I write a funtion that will 'cross out' a number on the card after its been called.
So for example if number_drawn results in 11, it should replace 11 on the card with an x or a zero.

modifying 2 lists and giving them scores

I want to make a output file which is simply the input file with the value of each byte incremented by one.
here is the expected output:
04 fb 56 13 21 67 68 51 e9 ac
which also will be in hexadecimal notation. I am trying to do that in python3 using the following command:

How to construct a String instance from a sequence of integers?

I would like to create a test string from Unicode code points
Something like this
65 asCharacter asString,
66 asCharacter asString,
67 asCharacter asString,
65 asCharacter asString,
769 asCharacter asString
Or
String with: 65 asCharacter
with: 66 asCharacter
with: 67 asCharacter
with: 65 asCharacter
with: 769 asCharacter
This works but
I am looking for a way to convert an array of integer values to an instance of class String.
#(65 66 67 65 769)
Is there a built in method for this?
I am looking for an answer like this What is the correct way to test Unicode support in a Smalltalk implementation? one, but for Strings.
Many ways
1. #streamContents:
Use stream if you are doing larger string concatenation/building as it is faster. If just concatenating couple of strings use whatever is more readable.
String streamContents: [ :aStream |
#(65 66 67 65 769) do: [ :each |
aStream nextPut: each asCharacter
]
]
or
String streamContents: [ :aStream |
aStream nextPutAll: (#(65 66 67 65 769) collect: #asCharacter)
]
2. #withAll:
String withAll: (#(65 66 67 65 769) collect: #asCharacter)
3. #collect:as: String
#(65 66 67 65 769) collect: #asCharacter as: String
4. #joinUsing: the characters
(#(65 66 67 65 769) collect: #asCharacter) joinUsing: ''
Note:
At least in Pharo you can use either [ :each | each selector ], or just simply #selector. I find the latter more readable for simple things, but that may be personal preference.
Construct the String instance with #withAll:
String withAll:
(#(65 66 67 65 769) collect: [:codepoint | codepoint asCharacter])
Here is a "low level" variant:
codepoints := #(65 66 67 65 769).
string := WideString new: codepoints size.
codepoints withIndexDo: [:cp :i | string wordAt: i put: cp].
^string
Please, consider the following as awfully hackish, undocumented, unsupported and thus absolutely wrong way to do it!
You would think that you cannot mix characters and integers that easily, err you can:
'' asWideString copyReplaceFrom: 1 to: 0 with: (#(65 66 67 65 769) as: WordArray).
Indeed, this goes thru a primitive that doesn't really check for the class, but just for the fact that both receiver and argument are VariableWord classes...
For the very same reason (depending on WriteStream implementation - let's say fragile) this can work:
^'' asWideString writeStream
nextPutAll: (#(65 66 67 65 769) as: WordArray);
contents
The same apply to ByteString and ByteArray.
And of course, in the same vein, let's not forget the most convoluted way to do it, BitBlt:
^((BitBlt toForm: (Form new hackBits: (WideString new: 5)))
sourceForm: (Form new hackBits: (#(65 66 67 65 769) as: WordArray));
combinationRule: Form over;
copyBits;
destForm) bits
We again exploit the WordArray nature of WideString to serve as the container for the bits of a Form (a bitmap).
Hopefully this answer won't get too many votes, it doesn't deserve it!

HEX & Decimal conversion

I have a binary file , the definition of its content is as below : ( all data is stored
in little endian (ie. least significant byte first)) . The example numbers below are HEX
11 63 39 46 --- Time, UTC in seconds since 1 Jan 1970.
01 00 --- 0001 = No Fix, 0002 = SPS
97 85 ff e0 7b db 4c 40 --- Latitude, as double
a1 d5 ce 56 8d 26 28 40 --- Longitude, as double
f0 37 e1 42 --- Height in meters, as float
fe 2b f0 3a --- Speed in km/h, as float
00 00 00 00 --- Heading (degrees ?), as float
01 00 --- RCR, log reason. 0001=Time, 0004=Distance
59 20 6a f3 4a 26 e3 3f --- Distance in meters, as double,
2a --- ? Don't know
a8 --- Checksum, xor of all bytes above not including 0x2a
the data from the Binary file "in HEX" is as below
"F25D39460200269652F5032445401F4228D79BCC54C09A3A2743B4ADE73F2A83"
I appreciate if you can support me to translate this data line based on the instruction before.
Probably wrong, but here's a shot at it using Ruby:
hex = "F25D39460200269652F5032445401F4228D79BCC54C09A3A2743B4ADE73F2A83"
ints = hex.scan(/../).map{ |s| s.to_i(16) }
raw = ints.pack('C*')
fields = raw.unpack( 'VvEEVVVvE')
p fields
#=> [1178164722, 2, 42.2813707974677, -83.1970117467067, 1126644378, 1072147892, nil, 33578, nil]
p Time.at( fields.first )
#=> 2007-05-02 21:58:42 -0600
I'd appreciate it if someone well-versed in #pack and #unpack would show me a better way to accomplish the first three lines.
My Cygnus Hex Editor could load such a file and, using structure templates, display the data in its native formats.
Beyond that, it's just a matter of doing through each value and working out the translation for each byte.

Haskell doubt: how to transform a Matrix represented as: [String] to a Matrix Represented as [[Int]]?

Im trying to solve Problem 11 of Project Euler in haskell. I almost did it, but right now im
stuck, i want to transform a Matrix represented as [String] to a Matrix represented as [[Int]].
I "drawed" the matrices:
What i want:
"08 02 22 97 38 15 00 40 [ ["08","02","22","97","38","15","00","40"], [[08,02,22,97,38,15,00,40]
49 49 99 40 17 81 18 57 map words lines ["49","49","99","40","17","81","18","57"], ??a [49,49,99,40,17,81,18,57]
81 49 31 73 55 79 14 29 ----------> ["81","49","31","73","55","79","14","29"], ---------> [81,49,31,73,55,79,14,29]
52 70 95 23 04 60 11 42 ["52","70","95","23","04","60","11","42"], [52,70,95,23,04,60,11,42]
22 31 16 71 51 67 63 89 ["22","31","16","71","51","67","63","89"], [22,31,16,71,51,67,63,89]
24 47 32 60 99 03 45 02" ["24","47","32","60","99","03","45","02"] ] [24,47,32,60,99,03,45,02]]
Im stuck in doing the last transformation (??a)
for curiosity(and learning) i also want to know how to do a matrix of digits:
Input:
"123456789 [ "123456789" [ [1,2,3,4,5,6,7,8,9]
124834924 lines "124834924" ??b [1,2,4,8,3,4,9,2,4]
328423423 ---------> "328423423" ---------> [3,2,8,4,2,3,4,2,3]
334243423 "334243423" [3,3,4,2,4,3,4,2,3]
932402343" "932402343" ] [9,3,2,4,0,2,3,4,3] ]
What is the best way to make (??a) and (??b) ?
What you want is the read function:
read :: (Read a) => String -> a
This thoughtfully parses a string into whatever you're expecting (as long as it's an instance of the class Read, but fortunately Int is such).
So just map that over the words, like so:
parseMatrix :: (Read a) => String -> [[a]]
parseMatrix s = map (map read . words) $ lines s
Just use that in a context that expects [[Int]] and Haskell's type inference will take it from there.
To get the digits, just remember that String is actually just [Char]. Instead of using words, map a function that turns each Char into a single-element list; everything else is the same.

Resources