Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Locked thread
huhu
Feb 24, 2006
I've just started watching the MIT lectures found here:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-00-introduction-to-computer-science-and-programming-fall-2008

The videos are not clear enough to view the code. Is there some better quality video or do they realize their error and get a better quality video camera or something? Not trying to decipher blurry code.

Adbot
ADBOT LOVES YOU

huhu
Feb 24, 2006

Captain Capacitor posted:

You can look at the course readings here which has most of the material for the course.

Just realized that they actually zoom in to the coding later in the video so all is well. Have another question though. In the video they do operations such as 9/5 equals 1 and 'a' < 3 equals false. I understand the reason for this but I'm using Python 2.0 which gives answers of 1.8 and "TypeError: unorderable types: str() < int()" Are they using Python 1? If not what is the difference between their setup and mine?

huhu
Feb 24, 2006
Another small question. I see that 25**.5==9**.5+16**.5 is false and I understand why. What is the correct way to work around this?

huhu
Feb 24, 2006

how!! posted:

25 ** .5 == 5
9 ** .5 == 3
16 ** .5 == 4

3 + 4 != 5

not sure what you mean by a work around

Oh gently caress, I think it's time for me to stop coding for the night I'm starting to lose it. Thanks for clarifying.

Edit:I swear I have a real question now.

The problem is:

quote:

A Pythagorean triplet is a set of three natural numbers, a b c, for which,

a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.

There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

Here is my code:
code:
a=0
b=0
c=0
for x in range(1,1000):
    a=x
    for y in range(1,1000):
        b=y
        for z in range(1,1000):
            c=z
            if a<b<c and a+b+c==1000:
                if a**2+b**2==c**2:
                    print(a,b,c)
It gets the answer but takes about 30 seconds to do so. What makes it so horribly inefficient? I thought that moving around the last three commands of a<b<c a+b+c==1000 and a**2+b**2==c**2 to their own if statements would make it faster but I don't think so.

huhu fucked around with this message at 18:04 on Aug 26, 2012

huhu
Feb 24, 2006
Thanks everyone for your input, I'm going to take a look at your suggestions now. Have another question. If I have a def such as prime_test(#) and I have it setup to print 'nprime' if it's not prime and 'prime' if it's prime. Another part of my program has if prime_test(#)=='prime' then do something else. If I type prime_test(5) I get prime but if I type prime_test(5)=='prime' I get false. How do I make these two things interact with each other? Here is my code so far.

code:
#Find Primes
def prime_test(test_prime):
    test_list=range(2,round(test_prime/2)+2)
    for i in test_list: #Creates list of numbers from 2 to one more than test_prime/2
        if test_prime%i == 0: #If it finds the number is not prime, ends right away.
            print('nprime')
            break
        elif i==(round(test_prime/2)+1): #If i is the last number of the list, the # is prime.
            print('prime')


prime_list=[2]
i=3
prime_count=1
while prime_count <10:
    if prime_test(i) == 'prime':
        prime_list.append(i)
        prime_count=prime_count+1
        print(prime_list)

huhu fucked around with this message at 20:56 on Aug 27, 2012

huhu
Feb 24, 2006
Played around with my code and got:
code:
a=0
b=0
c=0
for x in range(1,1000):
    for y in range(1,1000):
        z=1000-x-y
        if x<y<z and x**2+y**2==z**2:
                    print(x,y,z)
                    break
Which takes less than a second to compute. Thanks for the input! Also another question about the line if x<y<z and x**2+y**2==z**2: if it finds that x<y<z is false will it break the loop and go back to the beginning or will it still try to compute x**2+y**2==z**2? I feel that this operation could slow down the code.

Also, :suicide: forgot to include a counter for my while loop and took me ten minutes to figure out that was the problem.

huhu fucked around with this message at 21:08 on Aug 27, 2012

huhu
Feb 24, 2006
I have this code:
code:
test=0
remainder=1
while remainder !=0:
    test=test+1
    for i in range(1,21):
        if test%i !=0:
            remainder=1
            break
        else:
            remainder=0
            print(test)
It's a test for the smallest number that can be divided evenly by the numbers 1 to 20. Where I wrote break, I want it to break out of the if statement and start over with a new test number. Is there such a command to do this?

huhu
Feb 24, 2006

sund posted:

continue

edit: continue would be useful in restarting a loop, but just leave the whole line out as there are no more lines after the if block. it will continue automatically.
I think I didn't explain myself properly. I want to break out of the if statement and start the while loop over again. I ended up redoing my coding and got it to work a different way though by moving 'test' around.

Any suggestions for making this more efficient though? It took somewhere between two and five minutes to solve. Also, is making coding more efficient in regards to math problems mostly done by knowing more advanced theories? Like for example, here is another method for solving this problem:
http://ca.answers.yahoo.com/question/index?qid=20100123221401AA7q4lR
code:
test=1
remainder=1
while remainder !=0:
    for i in range(1,21):
        if test%i==0:
            remainder=0
        elif test%i !=0:
            remainder=1
            test=test+1
            break
print(test)

huhu
Feb 24, 2006
Thanks again for all of your input.

Can anyone point me to a basic introduction to matrices and interacting with rows, columns, changing elements, adding, rows/columns, etc? I must be searching the wrong thing because I've been looking for twenty minutes and can't find anything useful.

huhu
Feb 24, 2006
If I assign values to each of the letters such that a=1, b=2, c=3, etc, etc, how could I go about converting a string to a numerical value such as cat = 3 + 1 + 20? I would prefer a push in the right direction instead of a solution if possible.

My thoughts so far is to set
a=1
b=2
...
z=26

Then take a name such as "cat" and break it up and treat c a t as variables and sum these values. I'm just not sure how to identify each of the strings as variables.

huhu fucked around with this message at 18:03 on Sep 8, 2012

huhu
Feb 24, 2006
Ended up with a surprisingly fast code which went through about 5000 names in less than a second. I will check out dictionaries and ord now though thanks.

code:
def score(this_name):
    sum=0
    for j in range(len(this_name)):
        if this_name[j]=='A': sum+=1
        if this_name[j]=='B': sum+=2
        if this_name[j]=='C': sum+=3
        if this_name[j]=='D': sum+=4
        if this_name[j]=='E': sum+=5
        if this_name[j]=='F': sum+=6
        if this_name[j]=='G': sum+=7
        if this_name[j]=='H': sum+=8
        if this_name[j]=='I': sum+=9
        if this_name[j]=='J': sum+=10
        if this_name[j]=='K': sum+=11
        if this_name[j]=='L': sum+=12
        if this_name[j]=='M': sum+=13
        if this_name[j]=='N': sum+=14
        if this_name[j]=='O': sum+=15
        if this_name[j]=='P': sum+=16
        if this_name[j]=='Q': sum+=17
        if this_name[j]=='R': sum+=18
        if this_name[j]=='S': sum+=19
        if this_name[j]=='T': sum+=20
        if this_name[j]=='U': sum+=21
        if this_name[j]=='V': sum+=22
        if this_name[j]=='W': sum+=23
        if this_name[j]=='X': sum+=24
        if this_name[j]=='Y': sum+=25
        if this_name[j]=='Z': sum+=26
    return(sum)
Edit: I've solved 14 of the first 22 problems on Project Euler. I'd like to start learning about other aspects of Python that aren't focused primarily on solving math problems similar to Project Euler. What would be the next best logical step from here?

huhu fucked around with this message at 18:47 on Sep 8, 2012

huhu
Feb 24, 2006
I'm trying to install the beautofulsoup4 module, my first attempt at installing a module, and I'm totally lost reading online guides. Could someone point me to an idiots guide to installing modules?

huhu fucked around with this message at 01:37 on Feb 4, 2016

huhu
Feb 24, 2006

accipter posted:

What OS? If you are on windows, install miniconda3, then open terminal and run:
code:
conda install beautifulsoup4

That's about as idiot-level as you can get. Thanks!

huhu
Feb 24, 2006

accipter posted:

What OS? If you are on windows, install miniconda3, then open terminal and run:
code:
conda install beautifulsoup4
So beautifulsoup4 is installed but in the Python Shell when I try and import it it's not found. Is there a special command I have to use with conda to import it?

Edit:
Getting this:
code:
C:\Users\huhu>python -m pip install beautifulsoup4
Requirement already satisfied (use --upgrade to upgrade): beautifulsoup4 in c:\users\huhu\miniconda3\lib\site-packages
If I try and import it in the Python Shell it can't be found.

huhu fucked around with this message at 01:30 on Feb 6, 2016

huhu
Feb 24, 2006

accipter posted:

I am guessing that you now have multiple Python versions installed. Run the following commands you should see something similar
.
code:
C:\Users\accipter>python --version
Python 3.4.4 :: Continuum Analytics, Inc.

C:\Users\accipter>where python
C:\Users\accipter\AppData\Local\Continuum\Miniconda3\python.exe
code:
C:\Users\huhu>python --version
Python 3.5.1 :: Continuum Analytics, Inc.

C:\Users\huhu>
I did have Python 2.7 installed by I uninstalled it. Maybe not fully?

Edit: Forgot the second part.
code:
C:\Users\Travis>where python
C:\Users\Travis\Miniconda3\python.exe

huhu fucked around with this message at 01:43 on Feb 6, 2016

huhu
Feb 24, 2006
:suicide: The folder I was in was C:\Python34 but I'm using Python35 which is in a completely different location.

huhu
Feb 24, 2006
If I have a variable and I want to check if it's either a non-empty string, an empty string, or was never actually created... how would I check if it was never actually created?

huhu
Feb 24, 2006

Illegal Move posted:

Just out of curiosity, why do you need this?

I'm scraping data from a language translator and depending on the inputs you give it: "father", "the father", "like father like son", you get something that's either a string, an empty string, or doesn't exist. There might be a more eloquent way to deal with this but I'm just trying to get through writing my first program.

Thermopyle posted:

try/except?
I'll try that out.

huhu fucked around with this message at 00:53 on Feb 7, 2016

huhu
Feb 24, 2006
code:
def funct(word):
    print(word)
funct(hello world)
Is there something I can add to this so that I don't have to put quotes around my string? OR is that just dumb coding practice?

I'm writing a class with dictionary.openD(filename.txt) and I'm lazy and don't want to write dictionary.openD("filename.txt")

huhu
Feb 24, 2006
Simplified question.

code:
class Test:
    def method():
        print("hello")
    def method2():
        method()
How would I get Test.method2() to print "hello"?

huhu fucked around with this message at 20:57 on Feb 13, 2016

huhu
Feb 24, 2006
code:
import io
def fromFile(fileName):
    with io.open(fileName,'r',encoding='utf8') as f:
        text = f.readlines()
        print(text)
     return text
the fileName refers to:
code:
peinó
porquería
print gives:
code:
peinó
porquería
return gives:
code:
['\ufeffpeinó', 'porquería']
What is \ufeff and how can I stop it from appearing?

huhu
Feb 24, 2006

Asymmetrikon posted:

FEFF is a zero-width space. You've probably got one in your file.

I've found this: http://stackoverflow.com/questions/17912307/u-ufeff-in-python-string

Is a zero-width space the fact that's encoded in UTF-8? And how would I go about removing that? I've tried reading the instructions listed on the page and I don't understand it at all.

huhu
Feb 24, 2006
I've got this code that is searching through a directory and trying to match files up to another directory. If the file in the first is found with the same name in the second, it'l move the file in the first directory to the second.
code:
for filename_current in filenames_current:
	print("Checking %s to %s" % (filename_new, filename_current))
	if (filename_new == filename_current):
		print('Moving "%s" to "./uploads"...' % (filename_new),end="")
		filename_new_path = os.path.join(pdf_folder_new,filename_new)
		filename_current_path = os.path.join(foldername_current,filename_current)	
		shutil.move(filename_new_path, filename_current_path)
		print('done')
		break
Everything looks fine when running
code:
Checking file3.pdf to file1.pdf
Checking file3.pdf to file2.pdf
Checking file3.pdf to file3.pdf
Moving "file3.pdf" to "./uploads"...done
However, the code keeps running...
code:
Checking file3.pdf to file4.pdf
Checking file3.pdf to file5.pdf
Am I doing something wrong with the break statement?

huhu
Feb 24, 2006

cinci zoo sniper posted:

Is it straightforward to implement something so that when you have script.py that imports stuff from library.py, you can also get it to make you a copy of both library.py and script.py in the output folder? I'm specifically after doing it through Python, doing that via OS would be trivial.

Is this what you want?

to_copy.py
code:
print("I am going to be copied")
import make_copy		
make_copy.py
code:
import os
import shutil
folder_path = os.path.abspath("to_copy.py")
shutil.copy(folder_path, "./output")

huhu
Feb 24, 2006
Two things I'd suggest looking into are for loops which will run a loop a set amount of times and interupts which can stop other functions. I'm new to gpio stuff so you'll have to do some searching.

huhu
Feb 24, 2006
Oops

huhu
Feb 24, 2006
What Python Debugger do you guys use for Linux?

huhu
Feb 24, 2006

Thermopyle posted:

PyCharm or ipdb.

Awesome Thanks.

New Question, is there a cleaner way to write this?

[code]
columns_int = self.columns_int[:]
columns_int.remove(self.column_with_id_int)
self.columns_int_no_id = columns_int
[code]

huhu
Feb 24, 2006
After hours of frustration with a script I'm writing, I've come to realize I could have been using CSVs instead of Excel files. So, lesson learned, if you can deal with CSV files instead of Excel do it. If you're wondering why, Excel columns can start at 1 or "A" however everything in Python starts at 0.

huhu
Feb 24, 2006
Has anyone ever been able to pin a python script to the start menu?

huhu
Feb 24, 2006
Any suggestions for naming variables in Python for loops? I tend to just go with each or index but it gets quite confusing if I'm nesting loops. I also sometimes use, if my list is named something like "pairs" I'll do for each pair in pairs but that also seems a bit chaotic.

huhu
Feb 24, 2006
I'm building a webcam that pushes images to the internet after capture. I found a script to upload the images to Dropbox and it works great. However, I've found an issue that if the internet goes down mid upload, no error is returned and the upload just gets stuck at whatever percent its at. This wouldn't really be an issue however my hackspace's internet is utter garbage and I suspect the internet will go down pretty often. Is there some nifty way to detect a stuck upload and break?

huhu
Feb 24, 2006

Tigren posted:

If your script uses the Dropbox v2 API, it looks like it raises a requests.exceptions.ConnectionError when it times out.

code:
ConnectionError: ('Connection aborted.', timeout('The write operation timed out',))
I think that error message is hidden away in the script I found on Github.

huhu
Feb 24, 2006

Tigren posted:

Can you link to the script you're using? The Dropbox python API is very straight forward if you just want to write your own.

Python code:
In [1]: import dropbox
In [2]: import requests
In [3]: dropbox_client = dropbox.Dropbox(API_TOKEN)
In [4]: try:
            with open('test', 'rb') as f:
                upload = dropbox_client.files_upload(f.read(), '/path/to/file')
        except (requests.exceptions.ConnectionError) as err:
            print('Error uploading picture: ', err)
        else:
            print('Upload succeeded: ', upload)

Oh that's much nicer than what I'm using, thanks.

huhu
Feb 24, 2006

I'd say first calm down, you'll have a lot of experiences like this ahead so you'll need to manage them better. Second, you have this forum, ask specific questions more often. Perhaps start on a project that's not so hard.

huhu
Feb 24, 2006
Uneducated question - why does memory management matter? I understand why it would with something like an Arduino which has almost no memory but why would that matter on something like a computer with so much more memory? For context, I'm reading about arrays vs linked lists.

Related question: "To create an array, we must allocate memory for a certain number of elements"... when is this done? I thought a list was an array and I could just do my_list.append(x). What are they talking about that I'm missing?

huhu fucked around with this message at 23:19 on Feb 15, 2017

huhu
Feb 24, 2006
For anyone thinking about getting an Algorithms book for Python, don't buy this -
https://www.amazon.com/Data-Structu...gorithms+python

It boggles my mind that it managed to get 76 ratings of 4 stars. I'm catching at least one error every 5 to 10 pages and some of them are quite significant.

huhu
Feb 24, 2006
code:

import configparser

config = configparser.ConfigParser()
config.read('config.ini')

some_value = config['DEFAULT']['some_value']

some_function(some_value)

Is there a more elegant way to get values from a config file and then use them in a Python script or is this it?

huhu
Feb 24, 2006
Could you guys give me an example of what your settings.py files my look like? Also, does the dot notation you use autofill in something like Pycharm? I'd like to be able to type my_config.a and have all the settings with a pop up. Perhaps I'm going about this wrong.

Edit: I'm probing because the project I'm trying to work on might be useful for others. Probably not but I'd like the practice of making my stuff more user friendly.

Edit2: I think I can clarify a bit. I have a code like so:
code:
def dropbox_upload(file):
    dropbox_auth_token = open("dropbox_auth.txt", "r").read()
    #do all the uploading stuff here
Where I'll call it later on in several other different functions. I feel like the first line of the dropbox_upload function is bed. My two other thoughts are to do:

code:
import my_config

def dropbox_upload(file, auth_key):
    dropbox_auth_token = open(auth_key, "r").read()
    #do all the uploading stuff here

dropbox_upload(file, my_config.auth_key)
code:
import my_config

def dropbox_upload(file):
    dropbox_auth_token = open(my_config.auth_key, "r").read()
    #do all the uploading stuff here
But I think both of those are sloppy. How best could this be done?

huhu fucked around with this message at 01:58 on Feb 26, 2017

Adbot
ADBOT LOVES YOU

huhu
Feb 24, 2006

onionradish posted:


Automate the Boring Stuff is probably the most-recommended starter since it emphasizes doing something practical with the language.

[/list]

This has been an amazing book to learn from and I still go back to it every other project or so.

  • Locked thread