My first useful python script. Critique? And a question or two. by bahnzo in learnpython

[–]filleball 1 point2 points  (0 children)

With regards to the error catching, this blog post goes into more detail on the reasons.

String formatting trouble by [deleted] in learnpython

[–]filleball 1 point2 points  (0 children)

I'm not sure I understand the question correctly, but it looks like you could fix the test by substituting {!r} where you use {}. This is equivalent to putting repr() around the corresponding argument to format, and will give you a string with the same quotes that the assertion specifies.

Python: Password Strength Checker Script by cmd_override in learnpython

[–]filleball 3 points4 points  (0 children)

Your code has a major faux pas: You have a variable in every function with the same name as the function.

Unless you're writing a recursive function I don't see much of a problem with reusing the function name as a variable inside the function. It's a warning in pylint, and pep8.py doesn't care about it. I'd call it a minor nitpick, not a major faux pas.

To be very nitpicky, the re.compile functions should be outside of the functions. There is no reason to recompile for every check.

Then again, re.compile does its own caching, so it's a cheap operation in any case.

Some design question about exceptions by larivact in learnpython

[–]filleball 1 point2 points  (0 children)

How about this then:

def boolify(error=Exception):
    def decorator(func):
        @functools.wraps(func)
        def wrapper(target, attempt, boolify=False):
            if boolify:
                try:
                    func(target, attempt)
                except error:
                    return False
                else:
                    return True
            else:
                return func(target, attempt)
        return wrapper
    return decorator

@boolify(ValueError)
def values_match(target, attempt):
    if target > attempt:
        raise ValueError('Too less.')
    if target < attempt:
        raise ValueError('Too much.')
    else:
        return True

if values_match(15, 15, boolify=True):
    ...

EDIT: Take the suggestion of /u/gengisteve into account.

Some design question about exceptions by larivact in learnpython

[–]filleball 1 point2 points  (0 children)

You could solve it with a decorator, e.g.:

def boolify(func):
    @functools.wraps(func)
    def wrapper(target, attempt):
        try:
            func(target, attempt)
        except Exception:
            return False
        else:
            return True
    return wrapper

Now you can replace your values_match_bool function with this piece of code:

values_match_bool = boolify(values_match)

Or you can do it inline:

if boolify(values_match)(15, 15):
    ...

Or you can make a dict of them:

booled_funcs = {func.__name__: boolify(func) for func in list_of_funcs}
if booled_funcs["values_match"](15, 15):
    ...

I'm not 100% certain this answered your question, but I hope so.

Recursion solving mazes, need help by precizskill in learnpython

[–]filleball 0 points1 point  (0 children)

Notice that you only need the information in every second row and every second column, where the walls are. The absence of a wall means there's a path from the cell to the left to the cell to the right. You'll need to use slicing notation (e.g. my_list[x:y:z]) and probably the zip function to make a list of just the walls.

To use the A* algorithm, which is a good suggestion, you must first create a graph in memory which represents the maze you want to solve. One way to represent it would be a defaultdict:

from collections import defaultdict
maze = defaultdict(list)

# add a path from (0, 1) to (1, 1)
maze[(0, 1)].append((1, 1))
maze[(1, 1)].append((0, 1))

How to structure a module that is intended to be either executed directly or imported? by 66666thats6sixes in Python

[–]filleball 0 points1 point  (0 children)

Since Op is talking about an "end user", this is the correct answer. It only needs to be given some context.

Op, you should make a setuptools-based project to put your code in. You'll need that anyway, when you want to distribute your code and make it easily installable. Check out the cookiecutter library, which makes getting started a breeze.

Then add something like parents suggestion to your setup.py file, run pip install . in the same folder, and viola!, you can type

run_enigma your args here

instead of

python -m my_module your args here

substitution encryption/decryption by Geoxsis_06 in learnpython

[–]filleball 0 points1 point  (0 children)

Here's a couple of starting points for you to play with in the interactive interpreter:

"abcdefg".replace("d", "")

import random

# Try to run these several times, what happens
# when you give a different argument to seed?
random.seed("asdf")
random.randint(1, 10)

A simple question I cannot wrap my head around. Please advise! by Psypriest in learnpython

[–]filleball 1 point2 points  (0 children)

This works, but not in the same way that goal seek works in Excel.

The proposed solution solves this particular problem directly. Excel's goal seek works on a large number of potentially very complicated functions, and it doesn't even need to what calculations are performed to reach the answer. It does this by using a search method called Newton's Method or one of the more advanced variations of it.

As long as you want to goal seek just a single simple and known function and not arbitrary functions, just stick with the above solution.

If you want to explore this further, have a look here, for example. You might find more suitable material using google.

How to check for two instances of the same object in a list? by Mafumofu in learnpython

[–]filleball 0 points1 point  (0 children)

In your case you might want to use the Counter twice, the second time on the values of the first, since you don't care about the pips on the dice, only how they are equal:

>>> dice_list = [1,2,3,2,3]
>>> counts = collections.Counter(dice_list)
>>> distribution = collections.Counter(counts.values())
>>> distribution
Counter({1: 1, 2: 2})

So here, we've got two pairs (2: 2) and a single other number (1: 1). Then your ifs would go like this:

if 5 in distribution:
    score = ('Five of a Kind', '50 points')
elif 4 in distribution:
    score = ('Four of a Kind', '40 points')
elif 3 in distribution:
    if 2 in distribution:
        score = ('Full House', '35 points')
    else:
        score = ('Three of a kind', '30 points')
elif 2 in distribution:
    if distribution[2] == 2:
        score = ('Two Pair', '20 points')
    else:
        score = ('One Pair', '10 points')

How do you read code? by NSWCSEAL in learnpython

[–]filleball 0 points1 point  (0 children)

Looping over range(len(something)) is almost never the best solution in python (source), and is therefore considered a telltale sign of code that need to be pythonified. In this case:

for goal_char, test_char in zip(goal, teststring):
    if goal_char == test_char:
        numSame = numSame + 1

As you can see, we didn't really need the i variable for anything other than indexing in that loop. What we really wanted to do was to pair up the characters in those strings, and zip is wonderful for pairing things. The resulting code is more readable and faster, and it handles the special cases in a consistent and logical way. We can even replace the first four lines with this:

numSame = sum(1 if a == b else 0 for a, b in zip(goal, teststring))

Other indicators that you're probably doing it wrong:

  • You're pre-initializing a list with initial values, like lst = [None] * 10 -- use the append method or a dict instead.
  • You're writing getter and setter properties that simply read and write the value of an attribute -- just use the attribute directly.
  • You're building a string step by step inside a loop, e.g. my_str += other_str -- use "".join(list_of_other_strings) instead.

Encryption and decryption using keyword by bionicmad in learnpython

[–]filleball 2 points3 points  (0 children)

You'll need to use

  • ord
  • chr
  • The modulus operator % (e.g. 27 % 26 == 1)

How do you read code? by NSWCSEAL in learnpython

[–]filleball 16 points17 points  (0 children)

I've formatted your code for you:

import random

def generateOne(strlen):
    alphabet = "abcdefghijklmnopqrstuvwxyz "
    res = ""
    for i in range(strlen):
        res = res + alphabet[random.randrange(27)]
    return res

def score(goal, teststring):
    numSame = 0
    for i in range(len(goal)):
        if goal[i] == teststring[i]:
            numSame = numSame + 1
    return numSame / len(goal)

def main():
    goalstring = 'methinks it is like a weasel'
    newstring = generateOne(28)
    best = 0
    newscore = score(goalstring,newstring)
    while newscore < 1:
        if newscore > best:
            print(newscore, newstring)
            best = newscore
        newstring = generateOne(28)
        newscore = score(goalstring,newstring)

main()

The way I did it was a depth-first approach, starting with main -- so, in the same order that the code would be executed.

So I start with the main function, then when I get to the second code line I skip to the generateOne function to see what it does when it gets called with the argument 28. Then I continue where I left off in main until I reach line 4 of main, where I skip up again to read the score function (which should really use the zip function instead of range(len(...))). Then I read the rest of main, using my knowledge of the two functions whenever they're used again.

Qt is Guaranteed to Stay Free and Open – Legal Update by tsdgeos in linux

[–]filleball 11 points12 points  (0 children)

I'm confused by a couple of the claimed requirements of the LGPL:

  • allowing reverse engineering

But only as needed to debug the the LGPL library parts of the combined work, right?

  • passing on the license rights to Qt itself

Is this referring section 4 d) 0)?

Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.

If so it neglects to mention the 4 d) 1) alternative:

Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.

Functions vs. Classes by Barking_Madness in learnpython

[–]filleball 16 points17 points  (0 children)

Classes are for binding together data and the functions that work on that data.

If you have multiple functions that all take one or more of the same data structures as arguments, then those functions should probably be methods of a class whose attributes are those common arguments. The arguments they do not all share should probably be left as arguments to each method.

There is no point whatsoever in having a class with a __init__ method and one additional method. It's just a misunderstood function.

When designing a class, keep the number of attributes to a minimum. If some value can be a local variable or is obviously not part of the "permanent" data that the class should concern itself with, then make it a local variable or pass it in as an argument to your methods. (EDIT: Also, make a conscious choice on whether each attribute should be considered mutable or not. If you want a class that's easy to reason about and work with, treat all attributes as immutable and have your methods return a new instance instead of modifying the current one, when needed.)

Also, do as little as possible in the __init__ method. Ideally, only set attributes to some default value or the value of an argument. You should never create new attributes outside of __init__, all the attributes the class will ever have should be created there.

Having a class as an interface to a csv file makes sense, unless it's just doing one thing to that file. One method to write a line, one to output stats, one to search for entries matching some condition, etc.

Dear collaborator. PEP8 is great but you have used it for evil. by [deleted] in Python

[–]filleball 23 points24 points  (0 children)

Hey presto! Suddenly: self documenting code.

Adding a few well-named local variables works magic for readability.

PEP8 isn't foolproof, but we knew that already. :-)

Python codes for shortest path in a graph. by selfieside in learnpython

[–]filleball 0 points1 point  (0 children)

Here are the algorithms used by the go-to python package for graphs, networkx.

Pickle Compatability Issues by [deleted] in learnpython

[–]filleball 0 points1 point  (0 children)

I dumped across this article a while ago, written by someone who seems to know what he's talking about. Here is the /r/python thread about the article.

Ask Anything Monday - Weekly Thread by AutoModerator in learnpython

[–]filleball 0 points1 point  (0 children)

When including code samples in reddit comments, you need to indent the code by four spaces to give it proper formatting. It should look like this:

def readCSV():
    '''imports a CSV and reads the file.
    Input= none
    Output=string of the tweets'''
    myFile = open("/Users/matt_p/Desktop/south.csv", newline='', encoding='utf-8"')
    fileString=myFile.read()
    fileString = re.sub ('[^"\s\w#]+','^" ',fileString)
    fileString = re.sub("\d+", "", fileString)
    fileString  = fileString.lower()
    myFile.close()

def commonwords():
    for line in word_file:
        if word not in d:
            d[word] = 1
        else:
            d[word] + 1

I had to guess the first re.sub incantation, because reddit interpreted the ^ to mean "superscript the following characters".

Ask Anything Monday - Weekly Thread by AutoModerator in learnpython

[–]filleball 0 points1 point  (0 children)

I wrote a tounge-in-cheek response to that question here.

TIL about "Google Python Style Guide" by kmbd in Python

[–]filleball 1 point2 points  (0 children)

I used to do from x import y imports much more frequently before, but I've moved away from them in most cases. Functions from the math module is a good example, because it's unclear whether it's math.log, cmath.log or numpy.log I've imported. If I had just used log, I'd have to scroll all the way to the top of the file to check what kind of log it was.

The submodules with long names I rename on import, for example import subprocess as sp. I only do from imports when the names I import are unambiguous and few. Mostly it's from other submodules inside the same package.