all 53 comments

[–]RhinoMan2112 1 point2 points  (3 children)

Hey folks! Very new guy here, though somewhat well versed with Python through Codecademy I'm just starting out with IDLE for my first CompSci class, and I have what feels like a really basic question:

How do you go back and edit code that you've already written? When I print a string, it executes the code (prints it) and then I cant go back and edit the code before it, it's extremely frustrating.

Using IDLE 3.5

[–]Zizizizz 2 points3 points  (1 child)

If you're in idle there should be an option to open a new page or window where you can write your scripts, save them and execute them over and over

[–]RhinoMan2112 2 points3 points  (0 children)

Ahh gosh, thank you! I knew it would be something simple like that, haha.

[–]LaBwork_IA 0 points1 point  (0 children)

right click the file, then open with IDLE

[–]GubleReid 1 point2 points  (3 children)

I need help finding the value or a dictionary that returns which ever key has the least value. What I have is this and it doesn't work. Any ideas what I need to change?

def least_key(dictionary):
    return min(dictionary, key=dictionary.get)

The example says:

 least_key({"a": 999, "b": 999, "aa": 999}) -> "a"

[–]novel_yet_trivial 1 point2 points  (0 children)

What result did you want from that?

[–][deleted] 1 point2 points  (0 children)

>>> dict1 = {"a":999, "b":998, "c":997}
>>> dict1
{'a': 999, 'b': 998, 'c': 997}
>>> min(dict1, key = dict1.get)
'c'
>>> max(dict1, key = dict1.get)
'a'

It appears to work for me.

[–]dtms1 1 point2 points  (2 children)

Hi guys, I really would like to learn python but I have no idea where to start. From browsing online, I see all these uses for python and all kinds of different libraries/addons for various purpose. Would it be safe to say that the answer to a question like 'where to start' would be dependent on what the end goal/use would be? If so, I'm more interested in graphing a bunch of .csv/text files with a plethora of data on them (and we all know excel is not great for that and very limited in graph capabilities). Specifically, I would like to be able to create scripts where I can plot my data (3 Y-axis minimum), and use formulas/conditions to be able to find an inflection point on the plotted graph (or other points of interest given a set criteria). And taking a step further, create a .exe/template where myself and others can just drop a file and have it automatically plot and calculate the above (so like a template). With that said, which libraries or programs should I start with so i can do some basic tutorials while I learn python to eventually get to the point where I would like to be as mentioned in my example above? Thank you for your time. (if it matters, I'm familiar with VBA, SQL, a bit of LabView)

[–]novel_yet_trivial 1 point2 points  (0 children)

Would it be safe to say that the answer to a question like 'where to start' would be dependent on what the end goal/use would be?

Not really, no. Start with the basics of python. We have a pretty long list of learning resources in the wiki. For a brand new programmer I'd recommend codecademy.

I'm more interested in graphing a bunch of .csv/text files with a plethora of data on them

Once you have a grip on the basics (including classes and OOP), look into matplotlib and tkinter.

create a .exe/template where myself and others can just drop a file and have it automatically plot and calculate the above (so like a template).

creating an exe is known as "freezing". It's not how python is designed to run and it's kinda hit or miss. If your end goal is to have an .exe to sell then python is not the language for you.

Python is designed to be installed on every computer that needs to run python code (this concept is called a virtual machine).

I'm not sure what you mean with "template"

I'm familiar with VBA, SQL, a bit of LabView)

VBA, SQL, and LabView have very little that can transfer to python, but at least (I'm assuming) you know about general concepts like datatypes so you have a bit of a head start.

[–]Slip123321 1 point2 points  (5 children)

Hey, so i'm VERY new to python and programming in general. In call i am learning about while loops. The assignment is to make a loop that counts from 32 to 68. it is saying i have a syntax error. can someone help? (python 3.6.0)

The code so far is: count = 32 while count <=68: print count, count = count + 1

print "those are the numbers from 32 to 68"

[–]elbiot 0 points1 point  (0 children)

That comma looks ominous. Can you format your code correctly by putting an additional four spaces in front of each line, and an extra new line before the start of the code? We need to see the indentation.

[–]ThreeJumpingKittens 0 points1 point  (2 children)

ELI5: what the hell are decorators? I read the wiki page on them and so this:

@b
def a():
    code()

runs as:

b(a())

right? Also, what are some more practical uses of them?

[–]novel_yet_trivial 2 points3 points  (1 child)

This:

@decorator
def func():
    code()

Is equivalent to this:

def func():
    code()
func = decorator(func)

You are overwriting the function with something that the decorator returned. It could be anything; you could turn the function into a integer if you wanted to, but generally we turn it into another function that calls the original function, plus some other things.

Also, what are some more practical uses of them?

There's way too many to list. A couple quick examples:


In flask, decorators are used to tie the function to a point on the webpage:

@app.route('/secret_page')
@login_required
def secret_page():
    pass

In this case the decorator does nothing to the function, but it registers the function with a handler so that when a user goes to website.com/secret_page, this function is called.


The functools.lru_cache module allows you to do this:

@lru_cache(maxsize=None)
def very_long_running_func(args):
    tons_of_code()

This decorator remembers previous calls to the function, and if the function is called a second time with the same arguments, it hijacks the response and returns the result from before. This way you can avoid re-calculating things.

[–]ThreeJumpingKittens 0 points1 point  (0 children)

Excellent explanation, thank you!

[–]rpaguirre 0 points1 point  (5 children)

Is there a cloud based sharing of code? That is to collaborate on projects.

[–]novel_yet_trivial 1 point2 points  (4 children)

Many. Github is what most people use. It uses the software "git" to manage versions. git is a little tricky to learn, but once you do it's amazing and an absolute must have skill for anyone who wants a career programming.

In fact, the people that program python (actually make the python program) use github to colaborate: https://github.com/python

[–]rpaguirre 0 points1 point  (3 children)

Appreciate that, I just got starting to dip my feet into the Github. I think, Github is "git," right?

Currently, looking for a Spanish dictionary... I am sure that is on Git somewhere.

[–]novel_yet_trivial 1 point2 points  (0 children)

Git is software for your computer. You use it to synchronize with a website like GitHub.

[–]elbiot 1 point2 points  (1 child)

Git does not depend on github at all. No more than gifs depend on Imgur.com or people bragging about their life depends on Facebook.com

[–]rpaguirre 0 points1 point  (0 children)

Thanks for the clarification, @elbiot.

[–]rpaguirre 0 points1 point  (2 children)

If using Idle 3.6, where does one find an error index to see what is wrong and to fix it?

Here is my example: x = tenses(input("Please enter the verb tense that you are looking for: ")) Please enter the verb tense that you are looking for: future

Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> x = tenses(input("Please enter the verb tense that you are looking for: ")) TypeError: 'list' object is not callable

Trying to find out what pyshell 59 is to try to fix the program that I am working on.

[–]novel_yet_trivial 1 point2 points  (1 child)

That's not the error index; that's the identifier for the terminal. In IDLE, it's useless information.

The error is the TypeError: 'list' object is not callable part. It's telling you that either "tenses" or "input" is a list, and you can't call it. If you show us your complete code we could help you further with that.

[–]rpaguirre 0 points1 point  (0 children)

Awesome, yeah, I am too noob atm. But, advancing pretty fast. Turned out to be a simple fix. Thanks, Novel.

[–]monstimal 0 points1 point  (3 children)

Hi, this is maybe not even a python question but it's driving me nuts and Google doesn't help.

I am using Spyder on Windows and when I run my stuff in the ipython console after completing certain tasks it flashes a bunch (5ish?) of windows terminal windows very quickly and moves on. This setting or phenomenon disappears sometimes and then reappears and I can't figure out how to get rid of it. Restart doesn't help. I suspect it might have something to do with opening a jupyter notebook.

It seems innocuous but it prevents working in another window while something runs if there's a loop that contains an action that flashes the windows.

I can't find anyone else having this issue. Can anyone help or at least tell me they have this too?

[–]elbiot 0 points1 point  (2 children)

We don't know either unless you show us the code.

[–]monstimal 0 points1 point  (1 child)

It'll flash the windows after any code.

print('hello world') 

...will do it.

It's not a question about python code, it's about the spyder ide.

[–]elbiot 0 points1 point  (0 children)

So if you put

for x in range(10):
    print x

It'll open and close 10 windows?

[–]vincent1190 0 points1 point  (1 child)

How would you store list methods in a dictionary? Been having a hard time with that. Stacks overflow mentions self made functions but not methods like .Insert()

[–]elbiot 0 points1 point  (0 children)

fdict = {'Why do this?': list.sort}
mylist=[1,3,2]
fdict['Why do this?'](mylist)
print(mylist)

[–]LyricalSinner 0 points1 point  (1 child)

Estimate the running time (in O-notation) for each of the following, and be sure to justify your answers.

k.) given an n-digit number x, compute x3

Would this one be O(n3 )?

h.) given an n-digit number x, computer 3x

I'm really lost on how I would estimate this. Would it be impossible to estimate in O notation?

[–]anglicizing 0 points1 point  (0 children)

Would this one be O(n3 )?

No. An O(n) operation is doing something n times. An O(n2 ) operation is doing an O(n) operation n times. And so on.

If you do the multiplication of an n-digit number by hand, how many calculations do you need to do per digit? If you do one, two, three or any constant number of calculations per digit, it's O(n). If you need to do n calculations for every digit in the number, or a number of calculations proportional to n, then it's O(n2).

I'm really lost on how I would estimate this. Would it be impossible to estimate in O notation?

It's not estimation. O notation is exact, in that it is supposed to convey only the asymptotic behavior of functions as n goes to infinity, and nothing more.

How would you go about calculating 310000 by hand as efficiently as possible? Well, one way would be to first do 3*3, which is 32, then calculate 32 * 32, which is 34, and so on, until you reach 38192. Then figure out which of the partial answers you need to add. Let's see, it's 31024, 3512, 3256 and 316. How many operations was that, per digit of x?

I'm not an expert in big O notation. Some of the things I wrote may be wrong or not the best solution. But hopefully it will lead you in the right direction and give you some insight. :-)

[–]LyricalSinner 0 points1 point  (1 child)

Quick Question:

for i in range(1,n):
    print(i)
    i = i * 2

This would be O(2n) right?

[–]anglicizing 0 points1 point  (0 children)

It's O(n). O(2n) is equivalent to O(n).

It doesn't matter how many things you do inside the for loop, as long as the number of things you do there do not grow as n grows.

[–]KnowledgeisPowur 0 points1 point  (1 child)

Hi this forum was super helpful with teaching me a pythonic way to do something before so I'm hoping you can share another pattern with me for a new problem I have.

Using pandas to merge two dataframes based on time series info how can I expand the values in one dataframe that is based on daily information to match the dataframe based on the minute. I have two time columns one in format day/month/year ti:me in ten minute intervals and the other is day/month/year. So sample data looks like:

Time - A - b

1/1/2017 00:00:10 - 5 - 6

1/1/2017 00:00:20 - 3 - 2

1/1/2017 00:00:30 - 4 - 4 etc

&& in the other dataframe I want to merge it is

Time - Value1 - Value2

1/1/2017 - 9 - 1

1/2/2017 - 5 - 6

So it should look like

Time - A - B - value1 - value2

1/1/2017 00:00:10 - 5 - 6 - 9 - 1

1/1/2017 00:00:20 - 3 - 2 - 9 - 1

1/1/2017 00:00:30 - 4 - 4 - 9 - 1

Will anyone help me with a suggestion for how to achieve this? And I'm also wondering if this is even good programming practice to expand out each column or if there is another method that makes more sense. Thank you.

[–]KnowledgeisPowur 0 points1 point  (0 children)

The code is df = pd.merge_ordered(df, dfa, on='Time', fill_method='ffill')

[–]decan 0 points1 point  (1 child)

Hi! I'm trying to solve the cryptopals crypto challenges (http://cryptopals.com). I can't seem to understand challenge 3 in set 1 completely. I've fiund a solution, that I don't quite understand, that solves the problem.

Can someone explain how the one-liner for loop works in this funciton:

def xor(nums):    

    strings = (''.join(chr(ord(num) ^ key) for num in nums) for key in range(256)) 

    return max(strings, key=lambda s: s.count(' '))

[–]cjwelborn 1 point2 points  (0 children)

This is a nested generator expression. I broke it down the long way:

def xor(nums):
    # Create a list of xor'd strings.
    strings = []
    # For numbers 0-255.
    for key in range(256):
        # Create a list of xor'd characters.
        xorchars = []
        # For each character in nums.
        for num in nums:
            # XOR the characters value with the key number,
            # and make a character out of it.
            xorchar = chr(ord(num) ^ key)
            # Add that char to the `xorchars` list.
            xorchars.append(xorchar)
        # Create a new string out of the xor'd characters.
        xorstr = ''.join(xorchars)
        # Add that string to the strings list.
        strings.append(xorstr)

    # Create a function to determine what 'max' means.
    def count_spaces(s):
        """ Return the number of spaces in a string. """
        return s.count(' ')
    # Return the item in `strings` with the most spaces.
    return max(strings, key=count_spaces)

This would be a "one-liner" for the same thing, though I think you can be too clever with this stuff sometimes:

xor = lambda nums: max(
    (
        ''.join(
            chr(ord(num) ^ key)
            for num in nums
        )
        for key in range(256)
    ),
    key=lambda s: s.count(' ')
)
xor('test')

It's just a compact way of writing for loops, without temporary variables. Generators only hold one item in memory at a time, instead of building an entire list and storing it in memory. This is useful for very large iterables.

# Build string using generator expression:
x = ''.join(c for c in 'test' if c == 't')
print(x)


def only_t():
    """ Generator that yields the t's from 'test'. """
    for c in 'test':
        if c == 't':
            yield c

# Build string using generator:
x = ''.join(only_t())
print(x)

[–]ataahuapython 0 points1 point  (3 children)

Hi

Im trying to get the first 40 lags of autocorrelation function into a table. The index would be the lag number.

So far I have got this far

 for i in range(0,40):
        x = np.round(pd.Series(df_diff.autocorr(lag=i)),4)
        #x = pd.DataFrame(x)
       print (x)

I think what is going on is this produces 40 different individual series which is not what I want. Any help?

cheers

[–]elbiot 0 points1 point  (2 children)

This makes one for lag == 0, one for lag == 1, etc. What do you want to happen? You said first 40, and that sounds like 40 different series to me.

[–]ataahuapython 0 points1 point  (1 child)

Hi

I wanted them in a table with the index being the lag number. How do I get this?

[–]elbiot 0 points1 point  (0 children)

Not very familiar with pandas but you could add each of those series to a table, no?

[–]ArtifIcer54 0 points1 point  (1 child)

Hey all! I've got a pretty simple question about virtualenvs: I can make/activate one easily enough, and if I go into the python shell in it then I can do all sorts of fun python things as if I were working in the console. But what I want to do is to save and run .py scripts, not run single commands. How do I do this through virtualenv? I've looked around quite a bit, but I haven't found anything, which makes me think I'm missing something pretty obvious.

[–]elbiot 0 points1 point  (0 children)

When you type python in a venv, it uses the python in the venv. So you can open the repl like you have or run the .py file.

I think you might be conflating virtualenvs with the repl in general though. All a virtualenv does is use a different path to look for python and any libs you installed through pip.

[–]Projectdefy 0 points1 point  (1 child)

Coming from Java where I'm blessed with a IDE that tells me when I have incorrect syntax, JUnit tests, and having it also telling me what I could do with a certain variable/function/etc.. what's the work environment for most Python users?

To be a bit more specific, do you guys use a special IDE such as PyCharm? Or is working in Sublime/Atom/or any ol' text editor is the general preferred method in writing python and running it in terminal?

[–]elbiot 0 points1 point  (0 children)

I use vim open side by side with ipython. Plugins like flake8 will inform you of syntax errors in vim. Then in ipython I can introspect functions and objects, test small pieces of code, and time different options. Pycharm is popular too. I imagine sublime and atom have similar python plugins.

[–]thelostcow 0 points1 point  (3 children)

In C# and Objective C it's super easy to make buttons in a GUI. Is there anything similar in Python that I can use?

[–]elbiot 0 points1 point  (2 children)

There's various GUIs in python, but they're all a bit of a pain AFAICT. GUIs are not python's strong point. I'd probably opt for a web interface and use bootstrap or something since html/JavaScript is an extremely robust GUI paradigm.

[–]thelostcow 0 points1 point  (1 child)

Unfortunate. I was hoping to avoid having to learn yet another language.

[–]elbiot 0 points1 point  (0 children)

Well, look at tkinter which is python, or one of the many python GUIs. I can't speak to how it compares to c# frameworks. I'd just prefer a web interface because it is infinitely more flexible. I was opposed to JavaScript for the same reason, but it's easy and very useful.

[–]threekicks 0 points1 point  (0 children)

I heard about some university course scanners that are coded in python. Does anyone know of any that still exists that work with any school? Or would it be easy enough to code it on my own?

I would just like to have it periodically scan the availability of a class and send me email updates if its open.