November 15, 2024, 12:53:28 AM

1,531,348 Posts in 46,734 Topics by 1,523 Members
› View the most recent posts on the forum.


I decided to step up to Guff's challenge

Started by ncba93ivyase, January 19, 2009, 11:18:13 PM

previous topic - next topic

0 Members and 1 Guest are viewing this topic.

Go Down

Daddy


Daddy

[spoiler]help> keywords

Here is a list of the Python keywords.  Enter any keyword to get more help.

and                 elif                if                  print
as                  else                import              raise
assert              except              in                  return
break               exec                is                  try
class               finally             lambda              while
continue            for                 not                 with
def                 from                or                  yield
del                 global              pass               

help> topics

Here is a list of available topics.  Enter any topic name to get more help.

ASSERTION           DEBUGGING           LITERALS            SEQUENCEMETHODS2
ASSIGNMENT          DELETION            LOOPING             SEQUENCES
ATTRIBUTEMETHODS    DICTIONARIES        MAPPINGMETHODS      SHIFTING
ATTRIBUTES          DICTIONARYLITERALS  MAPPINGS            SLICINGS
AUGMENTEDASSIGNMENT DYNAMICFEATURES     METHODS             SPECIALATTRIBUTES
BACKQUOTES          ELLIPSIS            MODULES             SPECIALIDENTIFIERS
BASICMETHODS        EXCEPTIONS          NAMESPACES          SPECIALMETHODS
BINARY              EXECUTION           NONE                STRINGMETHODS
BITWISE             EXPRESSIONS         NUMBERMETHODS       STRINGS
BOOLEAN             FILES               NUMBERS             SUBSCRIPTS
CALLABLEMETHODS     FLOAT               OBJECTS             TRACEBACKS
CALLS               FORMATTING          OPERATORS           TRUTHVALUE
CLASSES             FRAMEOBJECTS        PACKAGES            TUPLELITERALS
CODEOBJECTS         FRAMES              POWER               TUPLES
COERCIONS           FUNCTIONS           PRECEDENCE          TYPEOBJECTS
COMPARISON          IDENTIFIERS         PRINTING            TYPES
COMPLEX             IMPORTING           PRIVATENAMES        UNARY
CONDITIONAL         INTEGER             RETURNING           UNICODE
CONTEXTMANAGERS     LISTLITERALS        SCOPING             
CONVERSIONS         LISTS               SEQUENCEMETHODS1   

help> modules

Please wait a moment while I gather a list of all available modules...

Audio_mac           _hotshot            fnmatch             pydoc_topics
BaseHTTPServer      _json               formatter           pyexpat
Bastion             _locale             fpformat            quopri
CGIHTTPServer       _lsprof             fractions           random
Canvas              _multibytecodec     ftplib              re
Carbon              _multiprocessing    functools           repr
CodeWarrior         _random             future_builtins     resource
ColorPicker         _sha256             gc                  rexec
ConfigParser        _sha512             genericpath         rfc822
Cookie              _socket             gensuitemodule      rlcompleter
Dialog              _sqlite3            gestalt             robotparser
DocXMLRPCServer     _sre                getopt              runpy
EasyDialogs         _ssl                getpass             sched
Explorer            _strptime           gettext             select
FileDialog          _struct             glob                sets
Finder              _symtable           grp                 setuptools
FixTk               _testcapi           gzip                sgmllib
FrameWork           _threading_local    hashlib             sha
HTMLParser          _tkinter            heapq               shelve
IN                  _warnings           hmac                shlex
MacOS               _weakref            hotshot             shutil
MimeWriter          abc                 htmlentitydefs      signal
MiniAEFrame         aepack              htmllib             site
Nav                 aetools             httplib             smtpd
Netscape            aetypes             ic                  smtplib
OSATerminology      aifc                icglue              sndhdr
PixMapWrapper       altgraph            icopen              socket
Queue               anydbm              idlelib             sqlite3
ScrolledText        applesingle         ihooks              sre
SimpleDialog        appletrawmain       imageop             sre_compile
SimpleHTTPServer    appletrunner        imaplib             sre_constants
SimpleXMLRPCServer  argvemulator        imghdr              sre_parse
SocketServer        array               imp                 ssl
StdSuites           ast                 imputil             stat
StringIO            asynchat            inspect             statvfs
SystemEvents        asyncore            io                  string
Terminal            atexit              itertools           stringold
Tix                 audiodev            json                stringprep
Tkconstants         audioop             keyword             strop
Tkdnd               autoGIL             lib2to3             struct
Tkinter             base64              linecache           subprocess
UserDict            bdb                 locale              sunau
UserList            bdist_mpkg          logging             sunaudio
UserString          bgenlocations       macerrors           symbol
_AE                 binascii            macholib            symtable
_AH                 binhex              macostools          sys
_App                bisect              macpath             syslog
_CF                 bsddb               macresource         tabnanny
_CG                 bsddb185            macurl2path         tarfile
_CarbonEvt          buildtools          mailbox             telnetlib
_Cm                 bundlebuilder       mailcap             tempfile
_Ctl                bz2                 markupbase          terminalcommand
_Dlg                cPickle             marshal             termios
_Drag               cProfile            math                test
_Evt                cStringIO           md5                 tests
_File               calendar            mhlib               textwrap
_Fm                 cfmfile             mimetools           this
_Folder             cgi                 mimetypes           thread
_Help               cgitb               mimify              threading
_IBCarbon           chunk               mmap                time
_Icn                cmath               modulefinder        timeit
_LWPCookieJar       cmd                 modulegraph         tkColorChooser
_Launch             code                multifile           tkCommonDialog
_List               codecs              multiprocessing     tkFileDialog
_Menu               codeop              mutex               tkFont
_Mlte               collections         netrc               tkMessageBox
_MozillaCookieJar   colorsys            new                 tkSimpleDialog
_OSA                command             nis                 toaiff
_Qd                 commands            nntplib             token
_Qdoffs             compileall          ntpath              tokenize
_Qt                 compiler            nturl2path          trace
_Res                contextlib          numbers             traceback
_Scrap              cookielib           opcode              tty
_Snd                copy                operator            turtle
_TE                 copy_reg            optparse            types
_Win                crypt               os                  unicodedata
__builtin__         csv                 os2emxpath          unittest
__future__          ctypes              parser              urllib
_abcoll             curses              pdb                 urllib2
_ast                datetime            pickle              urlparse
_bisect             dbhash              pickletools         user
_builtinSuites      dbm                 pimp                uu
_bytesio            decimal             pipes               uuid
_codecs             difflib             pkg_resources       videoreader
_codecs_cn          dircache            pkgutil             warnings
_codecs_hk          dis                 platform            wave
_codecs_iso2022     distutils           plistlib            weakref
_codecs_jp          dl                  popen2              webbrowser
_codecs_kr          doctest             poplib              whichdb
_codecs_tw          dumbdbm             posix               wsgiref
_collections        dummy_thread        posixfile           xdrlib
_csv                dummy_threading     posixpath           xml
_ctypes             easy_install        pprint              xmllib
_ctypes_test        email               profile             xmlrpclib
_curses             encodings           pstats              xxsubtype
_curses_panel       errno               pty                 zipfile
_elementtree        exceptions          pwd                 zipimport
_fileio             fcntl               py2app              zlib
_functools          filecmp             py_compile         
_hashlib            fileinput           pyclbr             
_heapq              findertools         pydoc               

Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose descriptions contain the word "spam".[/spoiler]

Uhm, so I have a question for the guy in red.  Why won't idle open a new window :(

Daddy

January 22, 2009, 08:44:05 AM #17 Last Edit: January 22, 2009, 08:52:38 AM by Hulk Hogan
multi3 = range(3, 1000, 3)
multi5 = range(5, 1000, 5)
multi3and5 = range(15, 1000, 15)
sum(multi3) +sum(multi5) - sum(multi3and5)
oh yay.
wait a minute, i can reduce that to one line why am i using variables.  baddood;

Code Select
sum(range(3, 1000, 3)) +sum(range(5, 1000, 5)) - sum(range(15, 1000, 15))


the first time I did that in december I didn't know about the sum function :(


My original solution for the problem.
[spoiler]a = 0
b = 0
guff = 0
for i in range(3, 1000, 3):
    a = a+ i
for i in range(5, 1000, 5):
    b = b+i
for i in range(15, 1000, 15):
    guff = guff+i;
print a+b-guff[/spoiler]



Daddy

Does anyone know why
Code Select
a = 0
b = 1
while a <= 100:
c=a
a=b
b=c+b
print b

Doesn't run directly in idle? It was pissing me off because I was all "wtf man, that code is correct" but it wouldn't run. I then saved it and did python ./Euler_2.py and it gave me.
QuoteValenteMac:Euler jamesvalente$ python ./Euler_2.py
1
2
3
5
8
13
21
34
55
89
144
233

Which isn't what the problem is asking for, nor what I coded. I just needed a working sequence first.

Daddy

January 22, 2009, 10:08:08 AM #19 Last Edit: January 22, 2009, 10:11:40 AM by JMV
And there we go.  hocuspocus;
Code Select
#!/usr/bin/python
# Filename : Euler_2.py
#Find the sum of all the even-valued terms in the sequence which do not exceed four million.
a = 0
b = 1
d = 0
while a <= 4000000:
c=a
a=b
b+=c
if a%2==0:
  d+= a
print d



ncba93ivyase

Quote from: andrƃĀ© the giant on January 22, 2009, 06:55:36 AM
okay how many you got now  baddood;

i haven't done any new ones yet but i did just redo number 12
my solution takes about 3.5 seconds to run though  saddood;
no, i just reworked my solutions to the previous ones to run in ruby

But I'm going to try a couple after I wake up tonight.

Quote from: ncba93ivyase on June 18, 2014, 07:58:34 PMthis isa great post i will use it in my sig

guff

Quote from: Pancake Persona on January 22, 2009, 12:49:12 PM
no, i just reworked my solutions to the previous ones to run in ruby

But I'm going to try a couple after I wake up tonight.
i was into ruby for a while but then i gave up on it because it didn't have list comprehensions (yeah sure there are ways to do the same thing in ruby but they take a little more effort and more typing and aren't as pretty >:o)  akudood;

but seriously learn about list comprehensions and generator expressions and iterators and blah and blah etc. baddood;

guff

also i rewrote my solution to problem 2:
Code Select
def fib(n):
fib1 = 0
fib2 = 1
for i in range(n - 1):
fib2, fib1 = fib2 + fib1, fib2
return fib2 if n > 0 else 0

import itertools
print(sum(itertools.takewhile(lambda x: x < 4e6, (fib(n) for n in itertools.count() if n % 3 == 0))))


fuck yes generator expressions  akudood;

also i'm using python3

also this guy has a crazy fast implementation of a fibonacci function
i did a test of fib(2**n) for n from 0 to 19 using the one i wrote above and his version:
[spoiler]
Code Select
0: fib1 time: 1.09673e-05, fib2time: 2.14577e-06; ratio: 5.11111
1: fib1 time: 5.96046e-06, fib2time: 1.78814e-05; ratio: 0.333333
2: fib1 time: 5.96046e-06, fib2time: 9.05991e-06; ratio: 0.657895
3: fib1 time: 2.19345e-05, fib2time: 1.00136e-05; ratio: 2.19048
4: fib1 time: 8.10623e-06, fib2time: 2.7895e-05; ratio: 0.290598
5: fib1 time: 1.00136e-05, fib2time: 2.90871e-05; ratio: 0.344262
6: fib1 time: 1.50204e-05, fib2time: 5.22137e-05; ratio: 0.287671
7: fib1 time: 4.31538e-05, fib2time: 1.69277e-05; ratio: 2.5493
8: fib1 time: 6.60419e-05, fib2time: 2.09808e-05; ratio: 3.14773
9: fib1 time: 0.000129938, fib2time: 2.59876e-05; ratio: 5.0
10: fib1 time: 0.000296831, fib2time: 3.79086e-05; ratio: 7.83019
11: fib1 time: 0.000808954, fib2time: 6.81877e-05; ratio: 11.8636
12: fib1 time: 0.00269389, fib2time: 0.000169039; ratio: 15.9365
13: fib1 time: 0.00888014, fib2time: 0.000478983; ratio: 18.5396
14: fib1 time: 0.031538, fib2time: 0.00162387; ratio: 19.4215
15: fib1 time: 0.119242, fib2time: 0.00447392; ratio: 26.6527
16: fib1 time: 0.460428, fib2time: 0.0133159; ratio: 34.5773
17: fib1 time: 1.81237, fib2time: 0.0404069; ratio: 44.8529
18: fib1 time: 10.1864, fib2time: 0.123036; ratio: 82.7918
19: fib1 time: 43.4756, fib2time: 0.384916; ratio: 112.948
[/spoiler]

ncba93ivyase

my solution to number 6:
Code Select
g = []
x = 0
for i in range(1, 101):
g.append(i**2)
x += i
print x**2 - sum(g)

I'm certain guff will criticize my method of doing it, but I'm willing to learn.

Quote from: ncba93ivyase on June 18, 2014, 07:58:34 PMthis isa great post i will use it in my sig

guff

Quote from: Pancake Persona on January 23, 2009, 01:16:32 AM
my solution to number 6:
Code Select
g = []
x = 0
for i in range(1, 101):
g.append(i**2)
x += i
print x**2 - sum(g)

I'm certain guff will criticize my method of doing it, but I'm willing to learn.
it's not bad but as i've said before USE LIST COMPREHENSIONS
also it's kind of weird that for x you just use an int but for g you use a list
this would be more consistent:
Code Select

x, g = 0, 0
for i in range(1, 101):
g += i ** 2
x += i
print x**2 - g


but anyways what i did was something more like print(sum(i for i in range(101)) ** 2 - sum(i ** 2 for i in range(101)))

guff

also if you want to do it all maths-like, then print(sum(i**3 - i**2 for i in range(101))) is prettier and also works akudood;

ncba93ivyase

Quote from: andrƃĀ© the giant on January 23, 2009, 04:45:40 AM
it's not bad but as i've said before USE LIST COMPREHENSIONS
also it's kind of weird that for x you just use an int but for g you use a list
i don't know why i did it, but it's probably because i just slapped together something in 15 seconds and didn't bother thinking about alternative (and superior) methods

Quote from: ncba93ivyase on June 18, 2014, 07:58:34 PMthis isa great post i will use it in my sig

guff

both of you still need to learn list comprehensions  baddood;

ncba93ivyase


Quote from: ncba93ivyase on June 18, 2014, 07:58:34 PMthis isa great post i will use it in my sig

guff


Go Up