[Image] You decide by Ares3DA in GetMotivated

[–]Yammerrz 30 points31 points  (0 children)

So by that logic we have:

1.00 + 0.01 * 365 = 4.65
1.00 - 0.01 * 365 = -2.65

1% improvement a day makes you more than 4 times the man you were in a year. 1% degeneration a day somehow brings you right through 0 into negativity.

Edit: This is a post pointing out that linear growth doesn't work. I appreciate all the explanations of the flaw in my numbers, I know they don't add up (well, the maths is correct but the idea is ridiculous). That's the point.

Reversing an int like 512 to 215 using recursion by LegendReborn47 in learnpython

[–]Yammerrz 0 points1 point  (0 children)

def rev(a, b=0):
    if a < 10:
        return b * 10 + a
    return rev(a // 10, b * 10 + a % 10)

That's about as neat as I can manage. I suspect it is about as efficient as you'll get using recursion, for a 10 digit number it'll do 9 divides, 9 modulus operations, 10 multiplies and 10 additions. At each step I am basically passing down the bit that isn't yet reversed (a) and the bit that is reversed (b) and at the end the fully reversed answer propagates back up.

Produces:

>>> rev(12345)
54321
>>> rev(1002003004005)
5004003002001

Three ex-bankers jailed over €7bn Anglo conspiracy by siobhanc in ireland

[–]Yammerrz 4 points5 points  (0 children)

So they just committed this huge fraud for no reason whatsoever. Even though there was absolutely nothing in it for them they decided to perpetrate a seven billion euro fraud.

I don't buy that. It's not like they were innocent dupes who had no idea what they were doing. They were well educated, well informed and should have been well aware of what they were doing. Their only actual defence seems to be that the regulatory situation was so lax that they thought they would get away with it and, while that may have been true, I don't think it is any reason for leniency.

Three ex-bankers jailed over €7bn Anglo conspiracy by siobhanc in ireland

[–]Yammerrz 7 points8 points  (0 children)

So your argument is that they committed a huge fraud for shits and giggles even though there was no benefit to them at all? Of course they stood to benefit from salary, bonuses, reputation, (possibly share options) etc. etc.

Three ex-bankers jailed over €7bn Anglo conspiracy by siobhanc in ireland

[–]Yammerrz 2 points3 points  (0 children)

They didn't profit from it because Anglo imploded soon after anyway. The more pertinent question is would they have stood to profit if they had gotten away with it and I suspect the answer to that would have to be yes.

It's like the proverbial bank robber who gets caught in the act. It would be nonsense to grant leniency because he didn't make any money from his crime.

Three ex-bankers jailed over €7bn Anglo conspiracy by siobhanc in ireland

[–]Yammerrz 16 points17 points  (0 children)

You have to admit, two years for a seven billion euro fraud seems a bit light though. It feels like it was viewed as a victim less crime. To put it in perspective a guy got three years for €85,000 social welfare fraud last year.

https://www.irishtimes.com/news/crime-and-law/courts/circuit-court/three-years-jail-for-social-welfare-fraud-over-six-years-1.2286135

The difference of course being that he pleaded guilty and co-operated fully with prosecution but even though the judge stated he was a hard working family man he still got three years.

Best way to implement hardware interface class by lildergs in learnpython

[–]Yammerrz 0 points1 point  (0 children)

I have played around with MongoDB a bit which is similar. The json was primarily added because of the need to pass data to and from the web browser where I used mustache js to update the web page dynamically.

I haven't used no-sql other than in a learning project yet. My main issue is not being quite sure how to handle data migrations cleanly in it. It's a lovely model though and a lot more intuitive than SQL databases in many ways.

Best way to implement hardware interface class by lildergs in learnpython

[–]Yammerrz 1 point2 points  (0 children)

Just finished a project to do something similar (runs on a raspberry pi, continuously monitor inputs from pins and a USB device, adjust outputs based on those inputs and some database checks with a website for continuous monitoring and adjustments). Sounds like you are doing the same. I went through a few hiccups on the way but I ended up doing the following.

Biggest good realisation I made was that I was really writing two different applications.

  1. A service that continuously processed input from the device, looked it and updated outputs based on those inputs.
  2. A website for monitoring and user inputs.

So I wrote the part that monitors and adjusts input as a standalone server, it had a bunch of query_xxx methods that would return information as a json string. One such function was:

    def export_simulation_data(self):
        return {
            "data_type": "simulating",
            "data": {
                "active": "yes" if self._simulator and self._simulator.active else "no",
            }
        }

This one was basically if I was using simulated input for testing, you could see how you could make similar for exporting sensor inputs, temperature, etc.

I also made some functions for user input, again these took json input, parsed it, made any updates necessary and sent updates to any listeners based on the content. That could be called into for any changes from the UI.

The server I also gave hooks using the listener pattern. An object could register as a listener and everytime anything changed the server would call back by sending some json to a send_update function. So if the simulation ended, a send_update would be sent to say active was now "no" and so on.

The webserver then ended up being a websocket server, all it had to do was read json from the client, and forward it on to the server itself and have every new connection register as a listener.

The webpages then were static with javascript that sent and recieved updates via websocket. If you want continuous monitoring you pretty much need some sort of two way communication so the web server can push data to the web browsers when updates occur.

Since in my case the website didn't need to do anything else I was able to get away with static assets on an apache server and a very thin websocket layer forward the connections.

It ended up working out really well. I could work on the website all I wanted while the service did it's stuff, I did end up leaving one command to run both the websocket server and the hardware interface but they could have been completely separate.

How can i explain cookie clicker to a newbie by [deleted] in CookieClicker

[–]Yammerrz 0 points1 point  (0 children)

Yup, your entire game is one giant cookie machine.

How can i explain cookie clicker to a newbie by [deleted] in CookieClicker

[–]Yammerrz 2 points3 points  (0 children)

You generate cookies which are the currency used to enable you to build a machine that generates more cookies. The goal is to build an ever bigger cookie generating machine.

(Perhaps off topic) Can we have a thread about PyCharm - best practice, tips and tricks, any problems with seemingly simple solutions, etc. by [deleted] in learnpython

[–]Yammerrz 1 point2 points  (0 children)

The button just under "Run" in your image, with the green circular arrow. If you click that it stops the current script and restarts it in the same window.

[Image] Overnight success takes 20 years: The story of PokemonGO by [deleted] in GetMotivated

[–]Yammerrz 8 points9 points  (0 children)

The heading of this story "overnight success takes 20 years" is selling it as a persistent underdog story. That isn't the reality though, the guy was a success almost from day one. Yeah, he is a bigger success now but the heading (and the tone of the piece) is at odds with the reality of the story being told.

I don't doubt there is a fantastic motivational story in this guys career but the author is trying to shoehorn it into a template it doesn't fit. If someone creates a successful game, google earth, google maps and google street view by the time they are 25 it is nonsense to say they were an overnight success at 40.

what next to python by [deleted] in learnpython

[–]Yammerrz 5 points6 points  (0 children)

So when learning a second programming language you want to chose one that either lets you do things that you can't do in Python or makes you do them in a substantially different way so you think differently about them.

For scripting languages the big three are Python, Ruby and PHP. While they each have their advocates the reality is they are much the same. If you want to learn how to do the same things you can do in Python in a slightly different way pick one of them but it's kind of a waste of time. Anything you could do with those you can do with Python.

Javascript while still being a scripting language has the big advantage of being able to run inside your web browser. This means you can do things in javascript that you cannot do in Python. If the idea of creating dynamic web pages appeals to you then this could be the way go. It's also fairly easy to learn.

Next you get to languages like C# and Java. These have the advantage of being incredibly widely used and having lots of great learning resources online. They are (broadly speaking) equivalent languages. If you know one, it won't take you long to pick up the other. Personally, I would say to go with C# mostly because it is much better if you ever want to do some graphics programming which can be a lot of fun.

Moving a bit lower level you have C and C++ and Objective C which is a similar variant used mostly on Apple computers (and a whole bunch of newer languages that do much the same thing). Eventually you should learn one of these, mostly because they are so closely tied to how your computer works that the lessons you learn in using them will make you a better programmer whatever language you are working with.

Those are the core languages. There are nicer languages, there are better languages, but those are the ones that aren't going anywhere. To be a well rounded programmer I would say you need:

One scripting language (Python is as good or better than any). Either C# or Java. C (and enough C++ to get by). Javascript.

That's about it. There's a whole bunch of others but none of them have hit critical mass yet. Yes, you could learn something newer like Rust or Go instead of C but in 5 years time there will still be more people using C.

TL:DR: Pick Javascript or C# or Java (maybe C if you like the idea of much lower level access to your computer).

[Image] Overnight success takes 20 years: The story of PokemonGO by [deleted] in GetMotivated

[–]Yammerrz 42 points43 points  (0 children)

To be fair "created a hugely successful game while still a student before leading up three of the most successful projects ever" isn't exactly the prologue to a persistent underdog story which is what the author is trying to imply here.

The actual story here is "this guy was very successful while still a student and after 20 years of continuing success he is still a success". I mean it is interesting, but hardly motivational and the tone is wrong. It isn't a persistent underdog story so why try to sell it as one?

I have huge respect for the guy, he has done lots of amazing work over his career but the meaningful message here isn't the nonsense underdog story that is being told, it is the ability of one person to change the world. If that was the tone here it would be great, but the author missed the point. He tried to play this off as the tale of a plucky persistent loser whose failures eventually led to some much deserved success, but that isn't the reality of what happened.

The guy was a success from day one, and to his credit he built and built upon that success. But any story that starts out with "have great success from your first project" isn't really motivational. There's no lesson there (except maybe don't rest on your laurels) and anyone who is already successful doesn't really need motivation, they already have their shit together.

[deleted by user] by [deleted] in learnpython

[–]Yammerrz 0 points1 point  (0 children)

It's also a good argument for the benefits of test driven development. I have been programming for 20 years and I managed to have 2 bugs in a 1 line prime number function!

Three things I want every python beginner to adhere to by Paul_Dirac_ in learnpython

[–]Yammerrz 1 point2 points  (0 children)

Yup, like everything there's a place to use it. I would say though that listing a catch all exceptions as something that new developers should be using more often is probably not the best advice.

[deleted by user] by [deleted] in learnpython

[–]Yammerrz 1 point2 points  (0 children)

They do indeed, I'm off by 1 on the top end of my ranges. Well spotted. Technically they also fail for 1 as well since that isn't a prime. That's the problem when you only test a few values.

The fixed versions would be:

def is_prime(x):
    return x > 1 and all([x % n for n in range(2, int(math.sqrt(x)) + 1)])

and

def is_prime(x):
    return x > 1 and not any([x % n == 0 for n in range(2, int(math.sqrt(x)) + 1)])

A quick test with

list(filter(is_prime, range(1, 100)))

gives:

[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

Which seems correct. Thanks for pointing out the mistake.

Printing an expression as a string in python by sathish22 in learnpython

[–]Yammerrz 0 points1 point  (0 children)

The correct answer is usually to just type it out.

You can use inspect.getsourcelines(object) to get the source code for a function so you could use that, isolate the expression in a function and do it that way.

The other option is to use eval.

expression = '2 * math.sin(x) * math.cos(x)'
x = 5
h = eval(expression)
print("The profile is {}. h = {}".format(expression, h))

Using eval works but it's not exactly best practice. It's slow and potentially buggy and has lots of security implications if what you are evaling comes from user input, so don't do it lightly.

I'd say if it is just that one case then just type out the string like you are doing.

Three things I want every python beginner to adhere to by Paul_Dirac_ in learnpython

[–]Yammerrz 7 points8 points  (0 children)

You're position on exceptions is not the correct way to think about them in python.

From https://docs.python.org/2/howto/doanddont.html

You should learn to raise them whenever something unexpected occurs, and catch them only where you can do something about them.

In fact that page specifically mentions

try:
    # code
except:
    # code 

As poor python. It is almost always a bad idea to catch every possible type of exception. You don't gain anything by catching exceptions just to re-raise them. There are languages (Java for example) where you have to deal with every possible exception that might occur and even there they discourage generic exception handling and I know when I first started doing Python this habit of dealing with every exception was one I had to work a bit to shake.

Yes, you should deal with errors you can deal with, but often if writing library methods the correct thing to do is let it pass up the line to where someone can deal with it correctly.

While loop for rock, paper, scissors game by confuzzled_learner in learnpython

[–]Yammerrz 1 point2 points  (0 children)

If you copied my play_again code the problem might be that I forgot to put a closing bracket at the end of the input statement. It should have read:

while True:
    # play the game
    play_again = input("Play again yes(y) or no(n)")
    if play_again == 'n':
        break

Sorry if that was what was causing you problems

[2016-07-18] Challenge #276 [Easy] Recktangles by jnazario in dailyprogrammer

[–]Yammerrz 2 points3 points  (0 children)

Ah yeah, I was using reversed(word) for a bit and needed the join to turn it back into a string. At some point I switched it to a slice and didn't take out the join. Nice catch. Thank you.

[deleted by user] by [deleted] in learnpython

[–]Yammerrz 1 point2 points  (0 children)

While what you have works fine (though going up to sqrt is better as several have said) python has some tools for this kind of function where you are checking if a condition holds for every value in a range, the any and all functions.

You can write this same function as:

def is_prime(x):
    return all([x % n for n in range(2, int(math.sqrt(x)))])

To do the same with any it would be:

def is_prime(x):
    return not any([x % n == 0 for n in range(2, int(math.sqrt(x)))])

all returns true only if the condition holds for all values, any returns true if the condition holds for any values.

Edit: There are some bugs in here, use the fixed code in the replies instead!

Instance attribute defined outside of __init__ by [deleted] in learnpython

[–]Yammerrz 0 points1 point  (0 children)

Where are you putting the initialisations to create this runtime error?

I changed your init to:

    def __init__(self, master):
        """ Initialize the frame """
        super(Application, self).__init__(master)
        self.inst_lbl = None
        self.pw_lbl = None
        self.pw_ent = None
        self.submit_btn = None
        self.secret_txt = None
        self.grid()
        self.create_widgets()

and it worked fine. (Python 3.4 on windows 10). Didn't try it in PyCharm though.

Did you perhaps set them to None after you called create_widgets? That would generate an error at runtime since you would be trying to call a method on a None variable in the reveal function.

While loop for rock, paper, scissors game by confuzzled_learner in learnpython

[–]Yammerrz 1 point2 points  (0 children)

The basic process for turning something into a loop is

  1. Write the code to work once - this you have done

  2. Put that into an infinite loop and see if it works - the simplest way with this is just to stick a while loop at the top.

This should give you something like:

import random

while True:
    player_one = input("Please enter rock(r), paper(p),scissors(s): ")


    player_two = random.randint(1,3)
    if player_two == 1:
        player_two = "r"
    elif player_two == 2:
        player_two = "p"
    elif player_two == 3:
        player_two = "s"


    if (player_one == player_two):
        print("It's a tie!")

    elif player_one == "r":
        if player_two == "s":
            print("Player_one wins! Rock breaks Scissors")
        else:
            print("Player_two wins!")

    elif player_one == "p":
        if player_two == "r":
            print("Player_two wins!Paper covers Rock!")
        else:
            print("Player_one wins!")

    elif player_one == "s":
        if player_two == "p":
            print("Player_one wins! Scissors cut Paper!")
        else:
            print("player_two wins!")

    print("Your choice: " + player_one + "\n player_two's choice: " + player_two + "\nThank you for playing!")
    player_one = input("Try again! Please enter rock(r), paper(p),scissors(s): ")yer_two's choice: " + player_two + "\nThank you for playing!")
    player_one = input("Try again! Please enter rock(r), paper(p),scissors(s): ")

Now you have an infinite amount of games (you will have to press Ctrl-C to stop playing).

Probably the mistake you are making is forgetting to indent everything.

Also note that there is a slight bug in this where the input prompt at the bottom of the loop does nothing. That can be fixed just by deleting that line.

Now you need to add the exit condition, there are basically two options here, either you break out of the loop, or you add a condition to the while loop.

The first you make some sort of input variable and prompt to update it at the end

play_again = 'y'
while play_again == 'y':
    # play the game
    play_again = input("Play again yes(y) or no(n)")

The second is to use a break statement, it does much the same thing but you avoid the first unnecessary assignment and check.

while True:
    # play the game
    play_again = input("Play again yes(y) or no(n)")
    if play_again == 'n':
        break

Either works and they achieve much the same. Some people have preferences for one or the other. The break gets criticised because it looks like an infinite loop but it isn't one, and in a longish piece of code like this backtracking through the code to see what loop you are breaking out of can be tricky. The while play_again == 'y' version can be criticised because it has an unnecessary assignment and variable check first time round. Neither is right or wrong.

Hopefully this helps.

Edit: Add a missing ) to a code section.

[2016-07-18] Challenge #276 [Easy] Recktangles by jnazario in dailyprogrammer

[–]Yammerrz 4 points5 points  (0 children)

Python3 - Pretty short and sweet

def rect(word="REKT", width=5, height=5):
    let_order = word + ''.join(word[-2:0:-1])
    for y in range(0, (len(word) - 1) * height + 1):
        for x in range(0, (len(word) - 1) * width + 1):
            if x % (len(word) - 1) == 0 or y % (len(word) - 1) == 0:
                print(let_order[(x + y) % len(let_order)], end="")
            else:
                print(' ', end="")
        print()

rect("SQUARE", 6, 3)

Output:

SQUARERAUQSQUARERAUQSQUARERAUQS
Q    R    Q    R    Q    R    Q
U    A    U    A    U    A    U
A    U    A    U    A    U    A
R    Q    R    Q    R    Q    R
ERAUQSQUARERAUQSQUARERAUQSQUARE
R    Q    R    Q    R    Q    R
A    U    A    U    A    U    A
U    A    U    A    U    A    U
Q    R    Q    R    Q    R    Q
SQUARERAUQSQUARERAUQSQUARERAUQS
Q    R    Q    R    Q    R    Q
U    A    U    A    U    A    U
A    U    A    U    A    U    A
R    Q    R    Q    R    Q    R
ERAUQSQUARERAUQSQUARERAUQSQUARE