Motoma 3,237
Recognized Expert Specialist
This article is cross posted from my personal blog. You can find the original article, in all its splendor, at http://motomastyle.com/thinking-outs...x-with-python/ . Introduction:
I recently came across this job posting in the forums. It has an interesting brain teaser as a requirement for applying. The brain teaser was stated as: "What is the exponent of the largest power of two whose base seven representation doesn't contain three zeros in a row?" The only stipulation was that the applicant use Python to solve the problem. My Initial Approach:
My inital approach to the problem is blunt and straight forward. I build three functions, BaseSeven which takes a number and convert it to base seven, HasThreeZeros which takes a number and checks if it has three zeros in it, and FindWithoutZero s which was the main loop of my program. The code for my problem is listed below: - def BaseSeven(num):
-
powersOfSeven = 1;
-
res = 0;
-
while num / powersOfSeven > 6: powersOfSeven = powersOfSeven * 7
-
while powersOfSeven != 1:
-
res = res * 10 + int(num / powersOfSeven)
-
num = num - int(num / powersOfSeven) * powersOfSeven
-
powersOfSeven = powersOfSeven / 7
-
res = res * 10 + num
-
return res
-
-
def HasThreeZeros(num):
-
return str(num).find("000") != -1
-
-
def FindWithoutZeros(power):
-
lastWithoutThreeZeros = power
-
failures = -1
-
num = pow(2, power)
-
while failures <= lastWithoutThreeZeros:
-
if HasThreeZeros(BaseSeven(num)):
-
failures = failures + 1
-
else:
-
failures = 0
-
lastWithoutThreeZeros = power
-
print power
-
power = power + 1
-
num = num * 2
-
if (float(power) / 100) == int(power / 100): print "CheckPoint:", power
-
return lastWithoutThreeZeros
-
-
print FindWithoutZeros(1)
The solution is quick and dirty, though severely lacking in elegance and speed. The biggest problem with this solution is that the program is constantly performing arithmetic operations on a huge number; when the exponent climbs into the upper thousands, it takes well over a minute to build, convert, and check a single number.
"There is no need for this," I say to myself, "There is a better way to do it." Round 2:
With a new cup of coffee in hand, I begin to further analyze the problem. Rereading the problem, I begin to think about the properties of powers of two: the most important property being that each successive power of two is double the previous. I know this is a pretty rudementary conclusion, however, realizing that the same will hold true for the base seven equivalent is the key to solving this problem efficiently.
I begin constructing a class, titled BaseSevenNumber . I give it a list, named digits, whose elements will contain a single base seven digit. I build a constructor to initialize this list to [1], and a member function titled Double which will handle my "exponentiation ." I finish off the class by creating another member, aptly titled HasThreeZeros, to give me the current status of number. The Double Function:
BaseSevenNumber 's Double function would hold the key to solving this problem in a timely manner. Rather than perform one arithmetic operation on a huge number, I design my second program to perform many arithmetic operations on a handful of tiny numbers. Iterating through the list, Double doubles each digit in the digits list, and in a second pass, performs all base seven carry operations. the HasThreeZeros function can now quickly traverse the digits list, and return the appropriate status for the current base seven number. - class BaseSevenNumber:
-
-
def __init__(self):
-
self.digits = [1]
-
-
def Double(self):
-
for i in range(0, len(self.digits)):
-
self.digits[i] = self.digits[i] * 2
-
for i in range(len(self.digits) - 1, -1, -1):
-
if self.digits[i] > 6:
-
self.digits[i] = self.digits[i] - 7
-
if i == 0: self.digits.insert(0,1)
-
else: self.digits[i - 1] = self.digits[i - 1] + 1
-
-
def HasThreeZeros(self):
-
for i in range(0, len(self.digits) - 2):
-
if self.digits[i] == 0 and self.digits[i + 1] == 0 and self.digits[i + 2] == 0: return True
-
return False
-
-
def SolveRiddle(maxFailuresAssumeFound):
-
bsn = BaseSevenNumber()
-
failures = 0
-
power = 1
-
while failures < maxFailuresAssumeFound:
-
bsn.Double()
-
if bsn.HasThreeZeros(): failures = failures + 1
-
else:
-
failures = 0
-
print power
-
power = power + 1
-
-
SolveRiddle(10000)
Thoroughly pleased with my ability to think my way around the problem, I put the code to the test. In a meager 16 seconds, it has given me the answer I am looking for. Talk about using the wrong tools for the job; just because the problem stated "power of two" and "base seven representation" does not mean one should restrict oneself to these methods. A careful and thorough analysis of a problem can give one an efficient, elegant, and fast solution to some of the trickiest of problems.
3 6068 bvdet 2,851
Recognized Expert Moderator Specialist
Motoma - Excellent solution! I need to be producing but could not get this problem off my mind. Here's a top down approach: - def ConvDecToBaseVar(num, base):
-
if base > 10 or base < 2:
-
raise ValueError, 'The base number must be between 2 and 10.'
-
if num == 0: return '0'
-
ans = ''
-
while num != 0:
-
num, rem = divmod(num, base)
-
ans = str(rem)+ans
-
return ans
-
-
def solve_test1(max):
-
for i in xrange(max, 0, -1):
-
if '000' not in ConvDecToBaseVar(2**i, 7):
-
return i
-
else:
-
print 'Checked power %s, FAILED TEST' % (i)
It took a while, but found that the highest number below 20000 is 8833. It's not nearly as efficient as yours. Now I can get back to work.
so, did you get the job? :D
Motoma 3,237
Recognized Expert Specialist
so, did you get the job? :D
Pffftt...I never applied. I have no Python experience :D
Sign in to post your reply or Sign up for a free account.
Similar topics |
by: Alexander Eberts |
last post by:
I'm new to python so appologies to the group if this question is asked
often. I'm wondering if it's possible to query an object instance to find
out what arguments the instance's __init__ function was called with from
*outside* the class's local namespace. For example, if I define a class Foo
as follows:
import sys
class Foo:
def __init__(self, *args):
print args # no problem here
|
by: Chris Perkins |
last post by:
Is there a reason why the ... notation as a literal for Ellipsis is
only allowed inside a slice? Would allowing it elsewhere frighten the
parser?
Chris Perkins
|
by: Mike Hofer |
last post by:
While I'd toyed with C, C++, and Java over the last 20 years or so, my
principal language has been BASIC, QBASIC, then Visual Basic, and
finally Visual Basic .NET. But lately, I've been using C# and I
absolutely *love* it. It makes me think more about what I'm doing it
before I just spew code into the editor. I'm writing better code than
ever.
The only thing so far that I don't like about it is the switch
construct. I can't do this:
|
by: Alex Pavluck |
last post by:
Hello. On page 124 of "Thinking like a Computer Scientist". There is
an exercise to take the following code and with the use of TRY: /
EXCEPT: handle the error. Can somone help me out? Here is the code:
def inputNumber(n):
if n == 17:
raise 'BadNumberError: ', '17 is off limits.'
else:
print n, 'is a nice number'
|
by: Sébastien Boisgérault |
last post by:
Hi,
Could anyone explain me how the python string "é" is mapped to
the binary code "\xe9" in my python interpreter ?
"é" is not present in the 7-bit ASCII table that is the default
encoding, right ? So is the mapping "é" -"\xe9" portable ?
(site-)configuration dependent ? Can anyone have something
different of "é" when 'print "\xe9"' is executed ? If the process
is config-dependent, what kind of config info is used ?
| |
by: Fabiano Sidler |
last post by:
Hi folks!
I'm trying to implement a python function that returns the current stack
depth of its frame. Unfortunately, I don't see any possibility to get this
value outside of PyEval_EvalFrameEx. Inside of it, I'd use the STACK_LEVEL
macro. How do I do it?
Greetings,
Fips
|
by: Aggelos |
last post by:
Hello,
Is it possible to run a script that will be used from all the websites
on the server outside of the web dir ?
At the moment for every site I have I upload the script in the web dir
of the specific site...
Specifically it is a RichEditor so it has javascripts as well ...
But it is difficult to maintain updates of the script to all websites
so I would prefer if I had only one place to update it...
|
by: riverhorus |
last post by:
I'm new to Python. I got this Python script from a friend. When I run it, I get an error message for line 7, "return None" saying "SyntaxError: 'return' outside function" Can someone explain what the SyntaxError is and how to fix it?
Here's the block of script. The error occurs in line 7.
def PC1(key, src, decryption=True):
sum1 = 0;
sum2 = 0;
keyXorVal = 0;
if len(key)!=16:
print “Bad key length!”
|
by: Hussein B |
last post by:
Hey,
Well, as you all know by now, I'm learning Python :)
One thing that is annoying my is the OOP in Python.
Consider this code in Java:
--
public class Car {
private int speed;
private String brand;
// setters & getters
}
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
| |
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
| |
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |