r/inventwithpython • • Sep 07 '17

[Automate] Table Printer Response Help

3 Upvotes

While looking for help on the Chapter 6 Project Table Printer, I came across a Stackoverflow answer that was really good. The problem is that I have trouble understanding the last 2 lines in the code.

Here's the answer:

Here's an alternate method that perhaps you could apply to your own code. I first took tableData and sorted it out into a dictionary so it's easier to work with. After that I found the longest list in terms of characters. This allows us to know how far over the shorter lists should go. Finally, I printed out each lists adding spaces in front of the shorter ones based on the difference from the longest.

    # orginal data
tableData=[['apples', 'oranges', 'cherries', 'banana'],
        ['Alice', 'Bob', 'Carol', 'David'],
        ['dogs', 'cats', 'moose', 'goose']]

# empty dictonary for sorting the data
newTable = {0:[], 1:[], 2:[], 3:[]}

# iterate through each list in tableData
for li in tableData:
    for i in range(len(li)):
        # put each item of tableData into newTable by index
        newTable[i].append(li[i])

# determine the longest list by number of total characters
# for instance ['apples', 'Alice', 'dogs'] would be 15 characters
# we will start with longest being zero at the start
longest = 0
# iterate through newTable
# for example the first key:value will be 0:['apples', 'Alice', 'dogs']
# we only really care about the value (the list) in this case
for key, value in newTable.items():
    # determine the total characters in each list
    # so effectively len('applesAlicedogs') for the first list
    length = len(''.join(value))
    # if the length is the longest length so far,
    # make that equal longest
    if length > longest:
        longest = length

# we will loop through the newTable one last time
# printing spaces infront of each list equal to the difference
# between the length of the longest list and length of the current list
# this way it's all nice and tidy to the right
for key, value in newTable.items():
    print(' ' * (longest - len(''.join(value))) + ' '.join(value))

Wouldn't the last 2 lines print out ' ' * (-16)? I'm pretty sure Python follows PEMDAS, so i'm having trouble understanding this. It would be nice if someone could explain or break up what's happening below, because if I try running this through PythonTutor it just displays the answer.

Stackoverflow Answer


r/inventwithpython • • Apr 20 '17

Unsubscriber - pyzmail msg.html_part.charset vs. utf-8

2 Upvotes

I am working on the email unsubscriber program that uses imap, pyzmail, and beautifulsoup. I ran a couple tests and it seemed to be working fine. However, on another test (in which I didn’t change anything), I got an error message:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 21188: ordinal not in range(128)

This is the specific line it was failing on:

html=message.html_part.get_payload().decode(msg.html_part.charset)

From the best of my understanding, one of the emails it was trying to parse had a non-ASCII character that it was trying to convert to an ASCII character and failing to do. I saw a few workarounds that said to add this to the code:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

However, I am using python 3.5.2 and this solution seems to only work for python 2.7.

I looked into the pyzmail docs and swapped out a bit of the line that was failing so that it now looks like this:

html=message.html_part.get_payload().decode ('utf-8')

I ran another test and it seemed to work. However, I’m concerned that some of the html data is either being lost or altered. After getting the html, I am parsing it with regex to find words in the a tag like unsubscribe, optout, etc, and then getting the href in said tag. Am I just being paranoid, or do I need to be concerned about this conversion?


r/inventwithpython • • Jan 31 '18

I made a machine to play bells with Python on Raspberry Pi.

Thumbnail
youtu.be
12 Upvotes

r/inventwithpython • • Oct 11 '15

What is the best way to learn from "Invent Your Own Computer Games with Python"?

5 Upvotes

I've been reading and working through "Invent Your Own Computer Games with Python", and I find it to be amazing. I'm a beginner programmer and have worked my way through codecademy's Python and Javascript tracks, and this book, has been exactly what I need as a next step. I feel it gives a window into what actual programs might look like. Yes, I know these are supposedly beginner programs, but hey, you have to start somewhere.
I'm currently on Chapter 10, the Tic Tac Toe game, and I'm wondering what is the best way to learn from this book.
So far I've done a mixture of two things. First I've written down the code as the book suggest, and followed the step by step explanations of the various parts of the program. And If I don't understand something in the code, I'll try to figure it out by messing around with the concept in IDLE.
Secondly, when I've internalized the new concepts I'll try to implement my own version of game/code. So, more precisely, I don't know which way is better. Should I master the way the code is written in the book, knowing this has been written by a master of the trade, to the point where if I tried, without reference to the book, to recreate one of the games, my code would look quite similar to that of the book? Or should I make my own version of the game, and if this implementation works in the end, if they behave in the same manner, if the end user or the player of my game experiences the same thing as the book's game, can I be satisfied and move on? Or will this lead to bad programming practices, that in more complex programs will end up screwing me over?
Guaranteed if someone reviewed my code there would be red marks all over the place. So I dunno, what do you think?


r/inventwithpython • • Oct 13 '15

Beautiful Soup in Automate the Boring Stuff (Ch. 11) only works 50% of the time. Anyone else having this problem?

2 Upvotes

When I run the program exactly as offered, I succesfully get the price information only about half the time. The other half, I get a "503 Server Error: Service Unavailable".

This happens when run on the Amazon.com website, and I am completely unable to get accounting information from finance.yahoo.com website (example: downloading revenues from http://finance.yahoo.com/q/is?s=PG+Income+Statement&annual)

Any advice about where I am going wrong and/or how to remedy this situation would be greatly appreciated. Thanks!


r/inventwithpython • • May 08 '16

Think I am going crazy - where can I download python (Chapter 1)

1 Upvotes

It references a 'website':

On Mac OS X, download the .dmg file that’s right for your version of OS X from the website and double-click it. Follow the instructions the installer displays on the screen to install Python, as listed here:

I cannot find a link to this website at all :( Am I going crazy, missing some inside joke or what? I have komodo IDE installed atm- is that any good?


r/inventwithpython • • Jan 27 '15

Newbie questions in re chapter 3

3 Upvotes

I am trying to run guess.py and I keep getting a "syntax error" with the word "am" in the sentence "I am thinking" highlighted in red. Also the word "and" in "between 1 and 20" is in orange.

I have checked my code against "Diff" and it does not seem to be pointing out any errors although I am not sure what the different colored blocks represent.

Any guidance would be greatly appreciated, thanks.


r/inventwithpython • • Oct 11 '15

Interesting outcome of str(number) in random number generation game

1 Upvotes

Hi! I just started to make my way through the Invent with Python book and I came across something interesting. I decided I wanted to just add a little extra line to Chapter 4's game in the win/lose condition flow control statements. So, if you win it says "Well done! I was thinking of number [x]! You got it in just [y] guesses!" and if you lose it says "Aww, too bad! The number I was thinking of was [y]"

if guess == number:
    guessesTaken = str(guessesTaken)
    print('Well done! I was thinking of the number ' + str(number) + '! You got it in just ' + guessesTaken + ' guesses!')

if guess != number:
    number = str(number)
    print('Aww, too bad! The number I was thinking of was ' + number)

The code above works. However, when I first tried this I entered:

if guess == number:
    guessesTaken = str(guessesTaken)
    number = str(number)
    print('Well done! I was thinking of the number ' + number + '! You got it in just ' + guessesTaken + ' guesses!')

if guess != number:
    number = str(number)
    print('Aww, too bad! The number I was thinking of was ' + number)

This, resulted in it playing both outputs (win and lose) when you won.

I was wondering if someone could explain to me why this would be the case? Is the doubling up of number = str(number) just confusing Python interpreter? Or, is there a programming reason why it's not skipping the second block?

Sorry for the long first post and thank you :)

edited to apply proper formatting for code


r/inventwithpython • • Apr 18 '17

Transposition Hacker not working

2 Upvotes

Hello,

I have this as my code for the Transposition Hacker, which is not working...

import detectEnglish, trans_decrypter

def main():

    myMessage = """Cb b rssti aieih rooaopbrtnsceee er es no npfgcwu  plri ch nitaalr eiuengiteehb(e1  hilincegeoamn fubehgtarndcstudmd nM eu
eacBoltaeteeoinebcdkyremdteghn.aa2r81a condari fmps" tad   l t oisn sit u1rnd stara nvhn fsedbh ee,n  e necrg6  8nmisv l nc muiftegiitm tutmg cm
shSs9fcie ebintcaets h  aihda cctrhe ele 1O7 aaoem waoaatdahretnhechaopnooeapece9etfncdbgsoeb uuteitgna.rteoh add e,D7c1Etnpneehtn beete" evecoal
lsfmcrl iu1cifgo ai. sl1rchdnheev sh meBd ies e9t)nh,htcnoecplrrh ,ide hmtlme. pheaLem,toeinfgn t e9yce da' eN eMp a ffn Fc1o ge eohg dere.eec s nfap
yox hla yon. lnrnsreaBoa t,e eitsw il ulpbdofgBRe bwlmprraio po  droB wtinue r Pieno nc ayieeto'lulcih sfnc  ownaSserbereiaSm-eaiah, nnrttgcC  maciiritvledastinideI
nn rms iehn tsigaBmuoetcetias rn"""

    hackedMessage = hackTransposition(myMessage)

    if hackedMessage == None:
        print("Failed to hack encryption")

    else:
        print("Copying hacked message to clipboard")
        print(hackedMessage)


def hackTransposition(message):
    print("Hacking...")

    print('(press CTRL+D or CTRL+C to quit at any time)')

    for key in range(1, len(message)):
        print("Trying key #%s..." % (key))
        decryptedText = trans_decrypter.decryptMessage(key, message)
        if key == 10:
            print(decryptedText)
        if detectEnglish.isEnglish(decryptedText):
            print()
            print("Possible encryption hack...")
            print("Key %s: %s" % (key,decryptedText[:100]))
            print("Enter D for done or just press ENTER to continue hacking:")
            response = input(">")

            if response.strip().upper().startswith("D"):
                return decryptedText

    return None
if __name__ == '__main__':
    main()

The decrypter for key 10 is producing this text, despite it working during the actual Transposition Decryption chapter:

myMessage = """Cb b rssti aieih rooaopbrtnsceee er es no npfgcwu plri ch nitaalr eiuengiteehb(e1 hilincegeoamn fubehgtarndcstudmd nM eu eacBoltaeteeoinebcdkyremdteghn.aa2r81a condari fmps" tad l t oisn sit u1rnd stara nvhn fsedbh ee,n e necrg6 8nmisv l nc muiftegiitm tutmg cm shSs9fcie ebintcaets h aihda cctrhe ele 1O7 aaoem waoaatdahretnhechaopnooeapece9etfncdbgsoeb uuteitgna.rteoh add e,D7c1Etnpneehtn beete" evecoal lsfmcrl iu1cifgo ai. sl1rchdnheev sh meBd ies e9t)nh,htcnoecplrrh ,ide hmtlme. pheaLem,toeinfgn t e9yce da' eN eMp a ffn Fc1o ge eohg dere.eec s nfap yox hla yon. lnrnsreaBoa t,e eitsw il ulpbdofgBRe bwlmprraio po droB wtinue r Pieno nc ayieeto'lulcih sfnc ownaSserbereiaSm-eaiah, nnrttgcC maciiritvledastinideI nn rms iehn tsigaBmuoetcetias rn"""

Thus, there is no distinguishable English word, despite seeing remnants of bits and pieces of English, which tells me that the reason the Transposition hacker is failing has to do with the decryption process text or key being off. I tried the text as both a multi-line and single-line string.

I copied and pasted the text word-for-word multiple times from This page .

I'm stuck. Anyone else struggle with this? Thanks.


r/inventwithpython • • Apr 04 '14

Having problems with the sort method

Thumbnail
gist.github.com
2 Upvotes

r/inventwithpython • • Apr 02 '14

pygame not working

2 Upvotes

I've installed python, but when I put "import pygame" into the IDLE, it gives me an error. Please help.


r/inventwithpython • • Jan 29 '15

problem about pyperclip.py in caesarCipher.py, Chapter 6

2 Upvotes

when I run caesarCipher.py, it shows this:

".../pyperclip.py", line 150, in <module> import gtk ImportError: No module named 'gtk'

and ".../pyperclip.py", line 155, in <module> import PyQt4.QtCore ImportError: No module named 'PyQt4'

and also: ".../pyperclip.py", line 162, in <module> raise Exception('Pyperclip requires the gtk or PyQt4 module installed, or the xclip command.') Exception: Pyperclip requires the gtk or PyQt4 module installed, or the xclip command.

Can you help me to explain why I meet this problem?My system is Ubuntu 14.04


r/inventwithpython • • Apr 15 '17

Hangman 2 select difficulty problem

3 Upvotes

I have the following block of code for hangman 2 and the program refuses to go into this while loop. When I debug it shows the value of difficulty being ''. The only way I can get it to go into the loop is if I make difficulty = 'x'. Am I missing something obvious?

difficulty = ''
while difficulty not in 'EMH':
    print('Enter difficulty: E - Easy, M - Medium, H - Hard')
    difficulty = input().upper()

When I use the compare tool it highlights the print and difficulty=input lines but the only difference I see is that they are indented by only 2 spaces instead of 4. Like this

difficulty = ''
while difficulty not in 'EMH':
  print('Enter difficulty: E - Easy, M - Medium, H - Hard')
  difficulty = input().upper()

I am using Python 3.4.4 could that be the problem?

EDIT: Thanks for all the tips everyone!


r/inventwithpython • • Aug 15 '20

Comma code project. Converting items from tuples and lists to str. Error in my code, help???

6 Upvotes

Hi! Can anybody help me with my code?

Here is the code that I have written:

https://gist.github.com/mrd2689a/8779cf36cd8fda6e803d77c5e40b1e5f

As you can hopefully see in my code, I tried to write it so that it would work with *any* list.... even lists that contain other lists or tuples. These errors are occuring when I put either a tuple or a list in the main list, "items".

When I run my program, I get the following error:

Traceback (most recent call last):

File "C:\Users\mrd26\OneDrive\Desktop\simplify\comma_code_2.py", line 51, in <module>

loop_thru(items)

File "C:\Users\mrd26\OneDrive\Desktop\simplify\comma_code_2.py", line 40, in loop_thru

add_comma(item)

File "C:\Users\mrd26\OneDrive\Desktop\simplify\comma_code_2.py", line 28, in add_comma

string = string + ', ' + item

TypeError: can only concatenate str (not "NoneType") to str

[Finished in 0.5s]

I used Python Tutor to see what was happening during the execution of my program, and I see that after the two 6's in my internal list get passed to convert_to_string(), it starts to loop through loop_thru_again(), even though the interal list only has two items in it (6 and 6). This is why it's passing the NoneType, I think. I don't know why this is happening, or how to fix it. Any help would be very much appreciated!!


r/inventwithpython • • Aug 25 '20

Tutorials at nostarch.com/automatestuff2

9 Upvotes

Several places in 'automate the boring' 2nd ed mention links to tutorials available at https://nostarch.com/automatestuff2/, but I can't find any on there. Are there links on the page that I'm missing? Thanks.


r/inventwithpython • • Sep 05 '20

"Automate the Boring Stuff..." Chapter 1: the first program

6 Upvotes

I'm totally new to coding and I'm following the book "Automate the Boring Stuff". I'm just now following the part where they tell you to write your first program, so I copy+paste it in:

➊ # This program says hello and asks for my name.

➋ print('Hello, world!')
   print('What is your name?')    # ask for their name
➌ myName = input()
➍ print('It is good to meet you, ' + myName)
➎ print('The length of your name is:')
   print(len(myName))
➏ print('What is your age?')    # ask for their age
   myAge = input()
   print('You will be ' + str(int(myAge) + 1) + ' in a year.')

Instead of what the book said would happen, I get this:

File "/Users/(my computer's username)/mu_code/hello.py", line 1

➊ # This program says hello and asks for my name.

^

SyntaxError: invalid character in identifier

>>>

I've tried replacing the numbers with >>> and In [1]... but I still end up with the same message. I'm using Mu 1.0.3. I literally just copy+pasted it in, what's happened?


r/inventwithpython • • Sep 01 '20

"Automate the Boring Stuff with Python" online course is free to sign up for the next few days with code SEP2020FREE

40 Upvotes

https://inventwithpython.com/automateudemy (This link will automatically redirect you to the latest discount code.)

You can also click this link or manually enter the code: SEP2020FREE

https://www.udemy.com/course/automate/?couponCode=SEP2020FREE

This promo code works until September 4th (I can't extend it past that). Sometimes it takes an hour or so for the code to become active just after I create it, so if it doesn't work, go ahead and try again a while later. I'll change it to SEP2020FREE2 on the 4th.

Udemy has changed their coupon policies, and I'm now only allowed to make 3 coupon codes each month with several restrictions. Hence why each code only lasts 3 days. I won't be able to make codes after this period, but I will be making free codes next month. Meanwhile, the first 15 of the course's 50 videos are free on YouTube.

You can also purchase the course at a discount using my code SEP2020FREE or clicking https://inventwithpython.com/automateudemy to redirect to the latest discount code. I have to manually renew this each month (until I get that automation script done). And the cheapest I can offer the course is about $16 to $18. (Meanwhile, this lets Udemy undercut my discount by offering it for $12, and I don't get the credit for those referral signups. Blerg.)

Frequently Asked Questions: (read this before posting questions)

  • This course is for beginners and assumes no previous programming experience, but the second half is useful for experienced programmers who want to learn about various third-party Python modules.

  • If you don't have time to take the course now, that's fine. Signing up gives you lifetime access so you can work on it at your own pace.

  • This Udemy course covers roughly the same content as the 1st edition book (the book has a little bit more, but all the basics are covered in the online course), which you can read for free online at https://inventwithpython.com

  • The 2nd edition of Automate the Boring Stuff with Python is free online: https://automatetheboringstuff.com/2e/

  • I do plan on updating the Udemy course for the second edition, but it'll take a while because I have other book projects I'm working on. Expect that update to happen in late-2020. If you sign up for this Udemy course, you'll get the updated content automatically once I finish it. It won't be a separate course.

  • It's totally fine to start on the first edition and then read the second edition later. I'll be writing a blog post to guide first edition readers to the parts of the second edition they should read.

  • I wrote a blog post to cover what's new in the second edition

  • You're not too old to learn to code. You don't need to be "good at math" to be good at coding.

  • Signing up is the first step. Actually finishing the course is the next. :) There are several ways to get/stay motivated. I suggest getting a "gym buddy" to learn with.


r/inventwithpython • • Aug 27 '20

The Amazing Mutable, Immutable Tuple and Other Philosophic Digressions

Thumbnail
youtube.com
17 Upvotes

r/inventwithpython • • Sep 07 '20

PSA About the Flash game "Sushi Go Round" for the last practice project of the book

Post image
13 Upvotes

r/inventwithpython • • Aug 30 '20

Help with this simple code Im getting started

11 Upvotes

Can someone say me why it didn't print the if accion?

import random
x = random.randrange(10)
print(x)
res = input('He elegido un numero del 1 al 10 adivinalo')
res = int(res)
while res!=x:
if res == x:
print('Hacertaste') #This one
    res = input('Intentalo de nuevo pto')
    res = int(res)


r/inventwithpython • • Aug 23 '20

Chapter 9 - Updatable Multi-Clipboard. Pyperclip not pasting correctly

3 Upvotes

Hello, I'm following the Updatable Multi-Clipboard Project in chapter 9. It all seems to be working ok except for retrieving a 'keyword' via the command line. Saving a keyword works, as does calling the 'list'. but when I try to recall a keyword via the command line, Pyperclip doesn't copy it.

There's also another quirk with this. If my last command to was to recall the 'list'. Then, given the fact that recalling a 'keyword' doesn't work, then the 'list' should still be in the clipboard. But instead, my clipboard contains what ever was in there before recalling the list.

So say I copy this statement:

'Python is great'

I then recall the list of this Multi-Clip program via mcb.py which contains:

['Pookie', 'Zophie', 'Simon']

I then try to recall the keyword 'Pookie'. It doesn't work, but when I paste from the clipboard I get 'Python is great'. If the clipboard hasn't been updated, then surely it should still contain the 'list'?

Here's my code:

#! python3
# mcb.pyw - Saves and loads pieces of text to the clipboard.
# Usage: py.exe mcb.pyw save <keyword> - Saves clipboard to keyword.
#        py.exe mcb.pyw <keyword> - Loads keyword to clipboard.
#        py.exe mcb.pyw list - Loads all keywords to clipboard.


import sys, pyperclip, shelve

mcbShelf = shelve.open('mcb')

if len(sys.argv) == 3 and sys.argv[1].lower() == 'save':
    mcbShelf[sys.argv[2]] = pyperclip.paste()

elif len(sys.argv) == 2:
    # List keywords and load content

    if sys.argv[1].lower() == 'list':
        pyperclip.copy(str(list(mcbShelf.keys())))
        
    elif sys.argv[1] in mcbShelf:
        pyperclip.copy(mcbShelf[sys.argv[1]])


mcbShelf.close()

r/inventwithpython • • May 29 '22

Collatz sequence - practice project chapter 3

5 Upvotes

So, I've been working through the 'Automate the boring stuff with Python' book and having a good time. I'm not a coder or programmer but I do work in IT which means that I have come across code every now and again. I've adapted some VBA code made by Excel to make Excel macros work a bit better and have adjusted Powershell scripts made by colleagues now and again. The Collatz sequence project was a lot of fun to work and eventually getting to a version that worked was very satisfying

I've been playing around with it a bit and come across something that I don't understand though. For some inputs it correctly goes down to the '4 - 2 - 1' part of the sequence and then stops (it does this for 1 and 3, for example). For some other inputs, though, it repeats those three numbers once and then stops ('4 - 2 - 1 - 4 - 2 - 1' it does this for 4 and 1001, for example). I have tried this with both the Mu editor and Visual Studio Code and both exhibit the same behavior. Does anybody have any idea what is causing this? My code's below (it doesn't check if the input is positive yet, I am aware of that :)).

[edit: code isn't below, that didn't look very nice, there's a pastebin link now]

https://pastebin.com/hhgt7TZw


r/inventwithpython • • Apr 11 '22

EZSheets install

3 Upvotes

Hi all,

I'm trying to set up ezsheets.

I downloaded the json credentials fine. I moved it to the required folder.

I ran the terminal from that folder. In the terminal I typed python (which worked fine). At that point I was able to run python commands directly. I then did import ezsheets and nothing happened. I was expecting it to open on the browser but nothing.

I've confirmed it's the correct cwd.

I don't understand what I'm doing wrong....


r/inventwithpython • • Apr 17 '22

A few comments on Bayes project in Real-World Python

6 Upvotes

A bit about me so that you may understand why my experience here may be different than yours. I am an experienced programmer in many, many languages, but not really an expert in any. But I am relatively new to Python. I have worked through the excellent Cracking Codes with Python (which I posted about and have learned a bit of "how to do things the Python way" through StackExchange searches.

I'm also familiar with a number of statistical concepts, though my knowledge is spotty, as I tend to learn things as I need them or as curiosity hits me.

I also manually retype in the code for the projects instead of just running and then modifying what provided from the resources. It gives me a much stronger sense of what is going on, what I feel should be improved upon, and the inevitable typos get me to work through things in a debugger.

Bayes

I have been a Bayesian since before it was cool, and I am familiar with the missing submarine (USS Scorpion) hunt that the project is probably modeled after. Because I've trained myself (and have attempted to train others) on Bayesian reasoning, I personally did not find that my intuitions differed from the probabilities that the game was calculating. But for those for whom Bayesian updating is new, I suspect that this would be extremely instructive. I will be sure to use it in future teaching about Bayesian reasoning. So although, I personally didn't learn anything new about Bayesian analysis through this, I did learn an excellent teaching tool for Bayesian analysis.

I really love the way that Bayesian analysis is presented. The introduction to it through the search for glasses in a house, is just brilliant. It is one of the best introductions to the concept of Bayesian updating that I've seen for an audience outside of epistemology, cognitive science, or statistics. Everyone should read that chapter and then play the game enough to get a feel for how probabilities associated with search areas is updated.

Python

What I personally learned about Python and related tools was enormous. Although I didn't like how searches of areas were modeled in terms of proportion of coordinates searched, the "Smarter Search" challenge had me learn about using sets in Python. (It took me a while to discover that the infix operator set union was "|" instead of "+".) I did eventually rip the whole coordinate thing out and just had the search of an area look like

    def conduct_search(self, area_id) -> bool:
        """Return True if sailor found in area; False otherwise."""

        sa = self.areas[area_id]
        found = False
        if area_id == self._area_actual and random.random() < sa.sep:
            found = True     
        return found

(Yes, I know that the last four lines could be expressed more compactly, but I like doing things this way running in a debugger.)

I tend to be a functional/strict-typing bigot. I understand why Python is (correctly) the way it is for the kinds of tasks it is designed for, but I found myself reading about Python conventions to help me do things in ways that feel right. E.g., methods with side effects should not return values; methods that return values should not have side effects. This was a sizable enough project for me to modify to follow that sort of thing.

I had been entirely unaware of CV. While it ultimately played a tiny role in the project, the introduction of it was just really nice for me. Glancing ahead, I see that projects do introduce powerful Python packages.

One of the great advantages of retyping the code was that repetitive parts of code became more salient (and more annoying), so I tended to rewrite things before such rewriting was necessary for working on some of the "challenge" projects.

Best strategy for the MCS?

Before we had the Planned Search Effectiveness, I could not find a strategy that out-performed the one of "pick the top N" search areas, where N is the number of search teams to assign. I had thought that when the probability associated with a particular area was much higher than the other probabilities, there would be an advantage to sending both teams to search that high probability area. I was surprised that I wasn't able to tune strat_cond() to produce better results than strat_top_n()

def strat_top_n(probs, pods, teams, day):
    keys = sorted(probs, key = probs.get, reverse = True)
    choices = keys[:teams]
    return choices

def strat_top_cond(probs, pods, teams, day):
    """Picks top n unless best area is much much better than second
    """
    
    keys = sorted(probs, key = probs.get, reverse = True)

    if probs[keys[0]] ** teams >= probs[keys[1]]:
       return [keys[0]] * teams
    return keys[:teams]

I was also wondering whether there there would be any reason to adjust the strategy based on the day of the search. (That is why I have the day parameter to these, but don't use it in the two strategies listed.)

Anyway, if anyone has any thoughts on doing better than top N or taking into account which day of the search we are on, I'd like to hear it. (Once we have Probability of Detection based on Planned Search Effectiveness, that that is the only strategy to follow.)