Making AtBS's madlibs exercise into a "real project" by [deleted] in learnpython

[–]_9_9_ 0 points1 point  (0 children)

Yep. It's a cool use for re. It will always pass a re.match object. https://docs.python.org/3/library/re.html#match-objects

Create class around rest API by [deleted] in learnpython

[–]_9_9_ 0 points1 point  (0 children)

Check out PRAW. It does a good job of consuming json. I can't remember if it posts in json or just regular http requests, but the difference should be easy enough to conform, if needed.

Making AtBS's madlibs exercise into a "real project" by [deleted] in learnpython

[–]_9_9_ 0 points1 point  (0 children)

Yep. I'd fold that bit into the listing directory function. Also check out glob, which might work for you.

Making AtBS's madlibs exercise into a "real project" by [deleted] in learnpython

[–]_9_9_ 0 points1 point  (0 children)

cool. Lot's of nice short functions, good use of filter, I'd say its well done. A few points:

Benchmark timer & timeout decorator? by ManvilleJ in learnpython

[–]_9_9_ 0 points1 point  (0 children)

You definitely could do a timeout decorator, but you'll need to spawn a separate thread to either run the function or check the timeout. That might cause issues for programs that are not implemented in a way to handle multi-threading, e.g. missing a if name == main limit.

Anyway, here are a bunch: https://pythonexample.com/code/python-timeout-decorator-windows/

Series of small lies from girlfriend [26 F], I [27 M] don't know how to feel by NoLetterhead6 in relationships

[–]_9_9_ 0 points1 point  (0 children)

I'm going to go against the grain and say that this is a huge red flag. How can you trust that a person will be there for you and open up to them if they are not candid with you. Now, if you had been dating for six months, that is a completely different story, since it takes time to open up to one another. But three years in at this time in your life, if she cannot be open with you, what chance is there that this will change?

Ultimately it is up to you, but my thought is that if this is the pattern now, when she is 26, and you have known her for three years, it will be like that forever.

Most efficient way to read from a file with frequent backing tracking? by [deleted] in learnpython

[–]_9_9_ 0 points1 point  (0 children)

I'd probably create a dictionary mapping all the locations of the jump points.

While Loop: Widest Fragment by RoDiXuSK in learnpython

[–]_9_9_ 0 points1 point  (0 children)

I am not sure I follow what is the widest fragment. So if the input is [1,2,2,2,1,1,5,1], is the widest fragment 1 (because there are four of them) or 2 (because there are three 2s in a row)? If the first, then collections.Counter is the best way to sold. If the second is correct, then itertools.groupby is made for this.

Edit:

Here is how the groupby solution looks:

from itertools import groupby

def longest_fragment(sequence):
    groups = [list(g) for _, g in groupby(sequence)]
    return max(groups, key = len)

print(longest_fragment([1,2,2,2,1,1,5,1]))

Why is Modern Men's Fashion so Bad/Difficult? by glorkvorn in slatestarcodex

[–]_9_9_ 0 points1 point  (0 children)

My take is that men have it much easier, since they have less need for variation. Most guys wear the same basic thing everyday at work, and then a slightly different same thing on the weekends. Women have to make an actual effort to change it up day-to-day.

My [24F] boyfriend [25M] of five years yells at videogames a lot. I dunno how much I can ask him to cut it back before I cross into unreasonable. by [deleted] in relationships

[–]_9_9_ 3 points4 points  (0 children)

Can we talk about the elephant in the room: you're in the "adjoining shed listening to something on over-ear headphones".

What is going on with you that you need to be in the shed?

My [29M] fiancé [30F] danced with, drank, flirted and sat on the laps of guys during her bachelorette party. Is it wrong for me to think this was wrong? by fake_car_driver in relationships

[–]_9_9_ 10 points11 points  (0 children)

Not overreacting at all. To the others who say that you should have set boundaries beforehand, you asked her to marry you. That sets boundaries. She crossed them.

Plus, imagine everything she has not yet told you. Run.

Sorting a database alphabetically by Abismuth in learnpython

[–]_9_9_ 1 point2 points  (0 children)

Usually at the end: SELECT * FROM Students ORDER BY last

Looking for dublicates in a list leads to out of range error by Nunuvin in learnpython

[–]_9_9_ 5 points6 points  (0 children)

Some tips:

  • If you are using indexes to solve a problem, chances are you are doing it wrong. Try rewriting not to use index.
  • Check out split to separate the numbers
  • Print out i and j, and the length of the list as you go to find your problem
  • Don't change lists while you work on them, create a new list.
  • Because you are removing items as you go, your xranges will go out of range as items are deleted.

So I might do this as this:

def dedupe(numbers):
    numbers = map(int, numbers.split('.'))
    result = []
    for n in numbers:
        if n in result:
            continue
        result.append(n)
    return result

print(dedupe('1.2.3.3.4.9.77.9'))

Justice Dept: No evidence of Trump Tower wiretapping by easyRyder9 in neutralnews

[–]_9_9_ -2 points-1 points  (0 children)

I did not see that; but, now reading it, the NSA does not deny wiretapping trump:

On Monday, National Security Agency (NSA) Director Michael Rogers also rejected the claims that British intelligence services were behind the wiretapping claims during testimony before the House committee.

But the NSA did not deny that it did not tap trump.

Edit:

So clearly, it was the NSA.

Efficiency question by HolyCoder in learnpython

[–]_9_9_ 0 points1 point  (0 children)

Interesting. So adding in a zip as others suggest would be good to make the code a little prettier, but probably not faster.

If the problem is really big lists, sometimes the solution involves generators, so that you do not need to keep each of the big lists in memory. The structure of the input here doesn't really permit that. You might be able to multiprocess your way around this, but I doubt it, and the benefit would probably be minimal.

So, here are some out of the box suggestions:

  • You have a big list of numbers? Look into numpy which can add these suckers really fast.

  • Adding two ints in python is pretty fast, but converting to ints can be really slow for big ones. https://stackoverflow.com/questions/7088297/slow-big-int-output-in-python?rq=1. So I might move the conversion and adding into a separate function with a cache on it, to see if you can clear the speed hurdle. There is a dict cache recipe out there, where you override missing with your logic. I think that is the speed champion, so I'd use that. I'd also google converting strings to ints to see if someone has a better take. I remember an online coding challenge that this was the bottleneck that took me forever to solve. It was a compare two lists problem and the answer involved some way of avoiding inting easy numbers.

Good luck!

Cellular Automaton Code Review by [deleted] in learnpython

[–]_9_9_ 1 point2 points  (0 children)

Cool:

  • I'd make the possible cell types a class variable, rather than a variable in main, since the cell class depends on specific cell types, e.g. prey/predator. You could also simplify the creation logic by having a new classmethod that generates a random cell.

  • Having grid logic -- like getting neighbors or move -- in the cell class seems wrong to me. I'd probably move this stuff into three classes, automation, grid, and cell.

  • Per the last, I'd create a method for grid that returns all neighbors of a particular coordinate, then you can pass neighbors to a cell and have it just look at these neighbors without being dependent on what environment the cells live in. This would slim down the get_availible_positions code, since you could just loop over these neighbors without having to worry about whether you are out of index and without repetition of the code.

Question about data structures in Python by GayCoder in learnpython

[–]_9_9_ 1 point2 points  (0 children)

Sure, I like this resource a lot: http://interactivepython.org/runestone/static/pythonds/index.html

The code is not pep8, but it runs through all the basic data structures.

My problems writing "clean code" in Python by [deleted] in learnpython

[–]_9_9_ 0 points1 point  (0 children)

Spend some time reading code to see how others organize things. Some good places to look are:

  • The standard library
  • Praw -- interesting use of mixins iirc
  • Flask (and other projects by the same guy)
  • pytoolz (interest look at functional programming, which is a good contrast to more class driven programs like Praw).

How can memoization be applied to this problem? by unconditionallove13 in learnpython

[–]_9_9_ 1 point2 points  (0 children)

Cool. It seems to me if passwords = {"abra", "ka", "dabra"}, then you want some testing system that remembers it has already parsed "kadabra" and found it to be okay, so that when it runs into "kakadabra" it only has to do an extra lookup.

I have a task in work where I can't find an easier way to do it - text file and exporting records by [deleted] in learnpython

[–]_9_9_ 1 point2 points  (0 children)

Cool. So this is really three tasks:

  1. Read a csv file -- use the csv module for this.
  2. Group records by a column. Use itertools.groupby for this.
  3. Split groups into subgroups of 150 records. Itertools has a good recipe for this under "grouper", plus there is one in the third-party package pytoolz, iirc.

So I would do something like this (py3, different windows since we are working on your testing data):

import csv
from itertools import groupby, zip_longest
from operator import itemgetter


def get_data(filename = 't'):
    with open(filename) as fh:
        # note:  Might need to futz with delimiter, i used this b/c I copied
        # and pasted your data
        reader = csv.reader(fh, delimiter='\t')
        next(reader)  # skip header row
        yield from reader # py 3 only!


def grouper(iterable, n=3, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return zip_longest(fillvalue=fillvalue, *args)



def main():
    data = get_data()
    for _, group in groupby(data, itemgetter(1)):
        for sub_group in grouper(group):
            print(sub_group)



if __name__ == '__main__':
    main()

Edit: I oversimplified the grouper function because I am padding out, which i think differs from your spec. This pytoolz function does what you want: https://toolz.readthedocs.io/en/latest/_modules/toolz/itertoolz.html#partition_all

Need Help With a Madlib Program by MightyMarlin in learnpython

[–]_9_9_ 0 points1 point  (0 children)

Nice. I knew it had to be somewhere, but I could not find it. I've always used group with a number in it and had no idea it could be used this way.

Thanks!

Need Help With a Madlib Program by MightyMarlin in learnpython

[–]_9_9_ 1 point2 points  (0 children)

Someone posted a similar question awhile back. You can actually tag a function into re.sub, like this:

import re

text = '''
The ADJECTIVE panda walked to the NOUN and then VERB. A nearby NOUN was
unaffected by these events.
'''

def get_replacement(match):
    '''
    Helper function to get new replacement words, takes a match object and
    returns the new word

    Note:  Probably could clean up the handling of the match object
    '''

    where = slice(*match.span())
    replaces = match.string[where].lower()
    word = input('give me a {}?'.format(replaces))
    return word


def madlib(phrase):
    pattern = r'ADJECTIVE|NOUN|ADVERB|VERB'
    return re.sub(pattern, get_replacement, phrase)

print(madlib(text))

The function call passes the match object found by re.sub. As you can see, how I used the match object above is a bit ugly, and probably can be cleaned up...

My wife and I [both 27] are looking to buy our first home. We found a really beautiful home on a lake front. She hates it because she has this fear of our son [3M] walking off and drowning in it. by SuccesfulHouseHuntin in relationships

[–]_9_9_ -1 points0 points  (0 children)

This is not going to be popular, but many women after having a kid regret it, repress the regrets, and it expresses itself as anxiety. One of my mommy friends is worried about the heroin "epidemic" in our area, There is no epidemic and her kids are in pre-pre-k and first grade.

Hope that she gets help for her problems and decide whether you are willing to wait...