Possible Google Riddle? - python

My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant.
t-shirt
So, I have a couple of guesses as to what it means, but I was just wondering if there is something more.
My first guess is that each block represents a page layout, and the logo "You should test that" just means that you should use google website optimizer to test which is the best layout. I hope that this isn't the answer, it just seems to simple and unsatisfying.
Well, I've spent the past hour trying to figure out if there is any deeper meaning, but to no avail. So, I'm here hoping that someone might be able to help.
I did though write a program to see if the blocks represent something in binary. I'll post the code below. My code tests every permutation of reading a block as 4 bits, and then tries to interpret these bits as letters, hex, and ip addresses.
I hope someone knows better.
#This code interprets the google t-shirt as a binary code, each box 4 bits.
# I try every permutation of counting the bits and then try to interpret these
# interpretations as letters, or hex numbers, or ip addresses.
# I need more interpretations, maybe one will find a pattern
import string
#these represent the boxes binary codes from left to right top to bottom
boxes = ['1110', '1000', '1111', '0110', '0011', '1011', '0001', '1001']
#changing the ordering
permutations = ["1234", "1243", "1324", "1342", "1423", "1432",
"2134", "2143", "2314", "2341", "2413", "2431",
"3124", "3142", "3214", "3241", "3412", "3421",
"4123", "4132", "4213", "4231","4312", "4321"]
#alphabet hashing where 0 = a
alphabet1 = {'0000':'a', '0001':'b', '0010':'c', '0011':'d',
'0100':'e', '0101':'f', '0110':'g', '0111':'h',
'1000':'i', '1001':'j', '1010':'k', '1011':'l',
'1100':'m', '1101':'n', '1110':'o', '1111':'p'}
#alphabet hasing where 1 = a
alphabet2 = {'0000':'?', '0001':'a', '0010':'b', '0011':'c',
'0100':'d', '0101':'e', '0110':'f', '0111':'g',
'1000':'h', '1001':'i', '1010':'j', '1011':'k',
'1100':'l', '1101':'m', '1110':'n', '1111':'o'}
hex = {'0000':'0', '0001':'1', '0010':'2', '0011':'3',
'0100':'4', '0101':'5', '0110':'6', '0111':'7',
'1000':'8', '1001':'9', '1010':'a', '1011':'b',
'1100':'c', '1101':'d', '1110':'e', '1111':'f'}
#code to convert from a string of ones and zeros(binary) to decimal number
def bin_to_dec(bin_string):
l = len(bin_string)
answer = 0
for index in range(l):
answer += int(bin_string[l - index - 1]) * (2**index)
return answer
#code to try and ping ip addresses
def ping(ipaddress):
#ping the network addresses
import subprocess
# execute the code and pipe the result to a string, wait 5 seconds
test = "ping -t 5 " + ipaddress
process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE)
# give it time to respond
process.wait()
# read the result to a string
result_str = process.stdout.read()
#For now, need to manually check if the ping worked, fix later
print result_str
#now iterate over the permuation and then the boxes to produce the codes
for permute in permutations:
box_codes = []
for box in boxes:
temp_code = ""
for index in permute:
temp_code += box[int(index) - 1]
box_codes.append(temp_code)
#now manipulate the codes using leter translation, network, whatever
#binary
print string.join(box_codes, "")
#alphabet1
print string.join( map(lambda x: alphabet1[x], box_codes), "")
#alphabet2
print string.join( map(lambda x: alphabet2[x], box_codes), "")
#hex
print string.join( map(lambda x: hex[x], box_codes), "")
#ipaddress, call ping and see who is reachable
ipcodes = zip(box_codes[0:8:2], box_codes[1:8:2])
ip = ""
for code in ipcodes:
bin = bin_to_dec(code[0] + code[1])
ip += repr(bin) + "."
print ip[:-1]
#ping(ip[:-1])
print
print
t-shirt.

I emailed the Website Optimizer Team, and they said "There's no secret code, unless you find one. :)"

I think Google are just trying to drive their point home - here are a bunch of different representations of the same page, test them, see which is best.
Which block do you like best?

I think it's simply a design, nothing secret, or mysterious.

What if it doesn't mean anything, what if it is just a neat design they came up with?

It says: "You are getting closer".

Well, I can't see an immediate pattern. But if you are testing IP, why not take two blocks of 4 as a single binary number.

Probably it's a base 4 notation?
I would try that, but I don't have any approach to this.

It reminded me of cellular automata:
http://www.wolframalpha.com/input/?i=rule+110
Anyone going that direction?

Related

How do I fix infinite loop bugs in Python?

I have a problem regarding a competition question I'm attempting to do. Here is the question (its a bit long)
""""
Welcome aboard, Captain! Today you are in charge of the first ever doughnut-shaped spaceship, The
Circular. There are N cabins arranged in a circle on the spaceship. They are numbered from 1 to N in
a clockwise direction around the ship. The ith and the (i + 1)th cabins are connected. So too are cabin
1 and cabin N.
Currently the ith cabin has Ai crewmates, however the spaceship cannot depart unless there are exactly
Bi crewmates in this cabin.
To achieve this, you have the power to pay crewmates to change cabins. You can pay a crewmate $1 to
move to an adjacent cabin. A crewmate can be asked to move multiple times, provided that you pay
them $1 each time.
What is the fewest dollars you must pay before you can depart? It is always be possible to depart.
""""
https://orac2.info/problem/aio22spaceship/ (the link to the intereactive Qs)
I searched the web and i found no solutions to the Q. My code seems to be infinite looping i guess but im not sure as i cant see what cases the sit uses to determine if my code is right.
Heres my code
#!/usr/bin/env python
import sys
sys.setrecursionlimit(1000000000)
#
# Solution Template for Spaceship Shuffle
#
# Australian Informatics Olympiad 2022
#
# This file is provided to assist with reading and writing of the input
# files for the problem. You may modify this file however you wish, or
# you may choose not to use this file at all.
#
# N is the number of cabins.
N = None
# A contains the initial number of crewmates in each cabin. Note that here the
# cabins are numbered starting from 0.
A = []
# B contains the desired number of crewmates in each cabin. Note that here the
# cabins are numbered starting from 0.
B = []
answer = 0
# Open the input and output files.
input_file = open("spacein.txt", "r")
output_file = open("spaceout.txt", "w")
# Read the value of N.
N = int(input_file.readline().strip())
# Read the values of A and B.
input_line = input_file.readline().strip()
A = list(map(int, input_line.split()))
input_line = input_file.readline().strip()
B = list(map(int, input_line.split()))
AM = A
#AM is my modifying set
# TODO: This is where you should compute your solution. Store the fewest
# dollars you must pay before you can depart into the variable
while AM != B:
#Check if the set is correct
#notfound is a testing variable to see if my code was looping due to input error
notfound = True
for i in range(N):
#Check which places needs people to be moved
while AM[i]>B[i]:
notfound = False
#RV and LV check the "neediness" for each half's people requirements. I check how many people
#are needed on one side compared to the other and subtract the "overflow of people"
RV = 0
LV = 0
for j in range(int(N/2-0.5)):
#The range thing makes sure that if N is odd, im splitting the middle but if N is even, i leave out the end pod
RV += B[(i+j+1)%N]-AM[(i+j+1)%N]
LV += B[(i-j-1)%N]-AM[(i-j-1)%N]
answer +=1
if RV>LV:
AM[i]+=-1
AM[(i+1)%N]+=1
else:
AM[i]+=-1
AM[(i-1)%N]+=1
print(AM,B)
if notfound:
break
print(answer)
# Write the answer to the output file.
output_file.write("%d\n" % (answer))
# Finally, close the input/output files.
input_file.close()
output_file.close()
please help i really neeed to know the answer, driving me mad ngl
Welp, there aren't any resources online and I've tried everything. I think the problem might be that because of my solving method, passengers may be flicked between two pods indefinitely. Not sure since i could make a case that demoed this.
also my post probably is messy since this is my first time posting

Formatting string from serial device

I know I asked a similar question before (Formatting a return value from a serial device), but this time around my question is different. I am reading a value from an Arduino, that looks something like this:
value = b'446.45 mV\r\n'
What I need from this, is simply 446.45. My code below works to extract this value, but every once and a while it will decide to not work. I am calling this value many times, up to 10,000 or more. It is frustrating when I get the error: "ValueError: could not convert string to float: '' " when I am on the 9000th iteration of my data collection. Does anyone know what my issue might be?
value = ser2.readline() # gives something like: b'446.45 mV\r\n'
val_str = str(value)
count = val_str.count('.') #count number of decimal points
if count != 1: #make sure there is only one decimal point
val_str = val_str[:6] #keep two decimal points
w = val_str.strip("b")
x = w.strip("mV\\r\\n")
y = float(x) # usually gives: 446.45
I think it is because your device gives different output due to serial port or cable corruption and your program cannot translate it to float.
Unfortunately you did not provide all the data, so I could not test the solution, but this is the best I could think of.
my_str = b'446.45 mV\r\n'
def separate(value):
value = value.decode("utf8") # decoding the value (it is better to use my_str.decode() instead of str(my_str))
value = value.split('m')[0] # removing all the letter that go after m
return float(value) # returning the separated value
separate(my_str)
Assuming you are sending analog Data from your Arduino to Python I highly recommend to send the raw 10-Bit (or sometimes 12-Bit) integers. This will make conversion much easier.
If you have your Arduino doing something like this:
Serial.println(analogRead(some_port));
then the Arduino will send the int data in ascii-bytes.
You can then grab those by doing something like this in python:
value = ser2.readline()
int_value = str(int(value))
# Here you can then calculate voltages based on that
voltage = 5/1023 * int_value

Python won't detect function loop if statement correctly

I have the following code
def numTest():
getNum = "https://sms-activate.ru/stubs/handler_api.php?api_key=" + api + "&action=getNumber&service=go&country=3"
numReq = requests.get(getNum)
smsNum = numReq.text
cleanNum = smsNum.split(":")
print(cleanNum)
reply = cleanNum[:6]
if reply == "ACCESS":
numID = cleanNum[1]
smsNo = cleanNum[2].replace("1", "", 1)
print(numID)
print(smsNo)
else:
numTest()
When the code is ran it doesn't detect the reply properly. So the API can either get back something such as ['ACCESS_NUMBER', '379609689', '12165419985'] or this ['NO_NUMBERS']
If it is the first one I need to split it and just keep array [1] and [2] and if it says No Numbers I need to run the loop again. What happens as well is if I get a number on the first try it stops and works correctly but if I get No numbers it trys again and if it gets a number it keeps going.
cleannum is a list, you're looking to find out if the first elements first 6 characters are ACCESS, not the first 6 elements of the list (which will never equal a string)
reply = cleanNum[0][:6]
Not sure if I understood your problem right. But if the array you mentioned is "cleanNum", then you should be using cleanNum[0][:6] here.

How do I calculate something inside a 'for' loop?

I'm doing an assignment in which I have to move a simulated robot across the screen in a loop - I've got that part down, however, between loops, I also have to print the percentage of area covered with each movement - that's my issue.
I googled a bit and even found someone with the same problem, however, I'm not sure if I'm doing it properly.
This code was offered:
percent_complete = 0
for i in range(5):
percent_complete += 20
print('{}% complete'.format(percent_complete))
However, after an error, further googling revealed that only worked with certain versions
so I used this code:
percent_complete = 0
for i in range(5):
percent_complete += 20
print '% complete' % (percent_complete)
And, at the very least, it now executes the code, however, the output when printing is the following:
Here we go!
hello
omplete
hello
(omplete
hello
<omplete
hello
Pomplete
hello
domplete
What is the cause of this? I assume because one of the codes had to be edited, the other parts do as well, but I'm not sure what needs to be done.
for i in range(5):
percent_complete += 20
print '%d complete' % (percent_complete)
You were missing the d specifier.
The first version only works in Python 3 because it uses print as a function. You're probably looking for the following:
percent_complete = 0
for i in xrange(5):
percent_complete += 20
print '{0} complete'.format(percent_complete)
Your other code doesn't do what you intend to do because it now display the number as a string. What you want is that the number is properly converted to a string first and then displayed in the string. The function format does that for you.
You can also use Ansari's approach which explicitly specifies that percent_complete is a number (with the d specifier).
To add to/correct above answers:
The reason your first example didn't work isn't because print isn't a function, but because you left out the argument specifier. Try print('{0}% complete'.format(percent_complete)). The 0 inside the brackets is the crucial factor there.

What is the Pythonic way to implement a simple FSM?

Yesterday I had to parse a very simple binary data file - the rule is, look for two bytes in a row that are both 0xAA, then the next byte will be a length byte, then skip 9 bytes and output the given amount of data from there. Repeat to the end of the file.
My solution did work, and was very quick to put together (even though I am a C programmer at heart, I still think it was quicker for me to write this in Python than it would have been in C) - BUT, it is clearly not at all Pythonic and it reads like a C program (and not a very good one at that!)
What would be a better / more Pythonic approach to this? Is a simple FSM like this even still the right choice in Python?
My solution:
#! /usr/bin/python
import sys
f = open(sys.argv[1], "rb")
state = 0
if f:
for byte in f.read():
a = ord(byte)
if state == 0:
if a == 0xAA:
state = 1
elif state == 1:
if a == 0xAA:
state = 2
else:
state = 0
elif state == 2:
count = a;
skip = 9
state = 3
elif state == 3:
skip = skip -1
if skip == 0:
state = 4
elif state == 4:
print "%02x" %a
count = count -1
if count == 0:
state = 0
print "\r\n"
The coolest way I've seen to implement FSMs in Python has to be via generators and coroutines. See this Charming Python post for an example. Eli Bendersky also has an excellent treatment of the subject.
If coroutines aren't familiar territory, David Beazley's A Curious Course on Coroutines and Concurrency is a stellar introduction.
You could give your states constant names instead of using 0, 1, 2, etc. for improved readability.
You could use a dictionary to map (current_state, input) -> (next_state), but that doesn't really let you do any additional processing during the transitions. Unless you include some "transition function" too to do extra processing.
Or you could do a non-FSM approach. I think this will work as long as 0xAA 0xAA only appears when it indicates a "start" (doesn't appear in data).
with open(sys.argv[1], 'rb') as f:
contents = f.read()
for chunk in contents.split('\xaa\xaa')[1:]:
length = ord(chunk[0])
data = chunk[10:10+length]
print data
If it does appear in data, you can instead use string.find('\xaa\xaa', start) to scan through the string, setting the start argument to begin looking where the last data block ended. Repeat until it returns -1.
I am a little apprehensive about telling anyone what's Pythonic, but here goes. First, keep in mind that in python functions are just objects. Transitions can be defined with a dictionary that has the (input, current_state) as the key and the tuple (next_state, action) as the value. Action is just a function that does whatever is necessary to transition from the current state to the next state.
There's a nice looking example of doing this at http://code.activestate.com/recipes/146262-finite-state-machine-fsm. I haven't used it, but from a quick read it seems like it covers everything.
A similar question was asked/answered here a couple of months ago: Python state-machine design. You might find looking at those responses useful as well.
I think your solution looks fine, except you should replace count = count - 1 with count -= 1.
This is one of those times where fancy code-show-offs will come up ways of have dicts mapping states to callables, with a small driver function, but it isn't better, just fancier, and using more obscure language features.
I suggest checking out chapter 4 of Text Processing in Python by David Mertz. He implements a state machine class in Python that is very elegant.
I think the most pythonic way would by like what FogleBird suggested, but mapping from (current state, input) to a function which would handle the processing and transition.
You can use regexps. Something like this code will find the first block of data. Then it's just a case of starting the next search from after the previous match.
find_header = re.compile('\xaa\xaa(.).{9}', re.DOTALL)
m = find_header.search(input_text)
if m:
length = chr(find_header.group(1))
data = input_text[m.end():m.end() + length]

Categories

Resources