chriswelborn 63

I see that your __init__ method is misspelled, but you're gonna want an instance to work with. You have a calculating class, but no object. Instantiate the class:

mycalc = calculating()

...then use the method (mycalc.addition). Also, its good practice in python for classes to start with a capital letter. So calculating should be called Calculating instead.

chriswelborn 63

You could use RegEx, but that may be overkill. I think GetFiles supports glob matching like GetFiles("C:\dir", "*.exe"), but you don't want to call GetFiles multiple times. So maybe a simple If statement would suffice:

If IO.Path.GetExtension(s) = ".exe" Then
    MyOtherBox.Items.Add(IO.Path.GetFileNameWithoutExtension(s))
Else
    WithoutThisTypeBox.Items.Add(IO.Path.GetFileNameWithoutExtension(s))
End If

My VB.Net is rusty, but I think that would do it. There is also s.EndsWith(".exe").

chriswelborn 63

just type it out. Put a blank line before the code, make sure all of the code lines are indented with 4 spaces.

# I did not use the </>Code button.
print('Hello World.')

You can also use the tilde character (`) to do "inline code" such as this: int c = 5; ...for when you don't need a whole block.

chriswelborn 63

Indention level matters in Python. I see you assign s in main(), but the code following that is actually outside of main() because of it's indention level. In other words, this:

#main function
def main(self):

    s = Set([0, 1, 2, 3, 4])
print
"The elements in the set are : ",

# Ask the user to enter the element to be added
n = input('Enter the element to add to the set: ')

#calling method to add the element
valid = s.addElement(n)
# ... All code for main() below this too..

Needs to be this:

#main function
def main(self):
    s = Set([0, 1, 2, 3, 4])
    print "The elements in the set are : ",

    # Ask the user to enter the element to be added
    n = input('Enter the element to add to the set: ')

    #calling method to add the element
    valid = s.addElement(n)
    # ... All code for main() below this too..

So you were accessing s before main() was even called (during definition on file load). Also notice how I put the print statement all on one line. This will print a blank line:

print
"Hello",

This will print "Hello " (a space is added because of the ,):

print "Hello",

When you separate the lines like that, "Hello", is not part of the print statement. It is evaluated and the result is thrown away. print statements should be on the same line, or if you really have to break them up you can do something ...

chriswelborn 63

What is the error? Copy and paste the stacktrace/output. Also, formatting your code would help you get an answer. It makes it much easier to spot simple errors. Use the "</> Code" button, and paste your code there, or just make sure it is all indented with 4 spaces.

chriswelborn 63

..replied to the third post. Bumping to remove from 'Unanswered'.

chriswelborn 63

3 posts for 1 question? Usually people don't just write programs for you here. Why does it have to be in Turbo C? Can it be in C?

chriswelborn 63

I would refer to the API documentation for DataResult<fmd>. I'm sure there are methods to help you retrieve the images it captures. I'm not sure which SDK you are using, and the DigitalPersona documentation (which I think you may be using) requires that you purchase support.

DigitalPersona does have a SerializeXml method, which is database-friendly and allows you to recreate the images for verification after saving them.

chriswelborn 63

@codewar, this is not the complete code. Please post the code in question and any errors that are printed. "the system is not allowing me to run the program" does not give us enough information to help you.

Also, your formatString is a format that expects 2 arguments (%s and %.2f). It will work fine for printf(formatString, getName(), getPrice()), but will fail for printf(formatString, getName(), getPrice(), applyDiscount()). You need a new format string if you are going to be passing 3 arguments.

chriswelborn 63

applyDiscount() doesn't return anything. You shouldn't be using it like that. If you want it to return the discounted price then refactor it to do so.

chriswelborn 63

Switch m and n around in the if statement.

24 % 6 == 0
// not 6 % 24 == 6
25 % 6 == 1
// not 6 % 25 == 6

The arguments are backwards according to the way the % operator works.

isDivisor(m,n) == (n % m == 0)

..not the other way around.

Also, only when the second operand is not 0. So you need another check.

if (m == 0) {
    return false;
} else {
    return (n % m == 0)
}

...it also already returns a boolean so putting return true and return false is redundant.

chriswelborn 63

What is the error? return this.price instead of return price?

Also, your second print.. you never set the discount for that product. So I don't think it will have any effect.

chriswelborn 63

The constructor takes Product(string product, double price), but you are creating it (on line 8) with Product("200.00", 0). You set the price to 0 and the product to 200.00. Try this:

Product product = new Product("HP Computer", 200);

chriswelborn 63

Like @woooee said, your code is tackling the numbers backwards because of your use of mod to get the digits. You can fix that, or make n zero-based to shift the even/odd detection. Your code isn't far off. Also, basic code inside of a function can easily be made to work outside of a function. If this is a homework assignment about while loops we can't write the whole assignment for you. We're just trying to help you get where you need to be.

When dealing with user input from the console it comes in as a string. The most popular way to iterate over a string is a for loop. But if your teacher insist on using a while loop consider this example:

digits = '123456'
position = 0
# Save the length of the digits string.
digitlen = len(digits)
# Loop until position == digitlen
while position < digitlen:
    # Grab the digit at the current position, convert to int.
    value = int(digits[position])
    # Use mod 2 to determine evens and odds.
    if position % 2 == 0:
        print('even: ({}) = {}'.format(position, value))
    else:
        print(' odd: ({}) = {}'.format(position, value))
    position += 1

This grabs each digit in order, and determines if it is even or odd. From there you can decide what to do in each case.

chriswelborn 63

@woooee, your print statements are off.

Output:

2+4+6 = 11
3*5*7 = 126

Should be:

2+4+5 = 11
3*7*6 = 126

chriswelborn 63

The odd numbers in your example are 2 and 4. So 6 is correct.
The even number in your example is 3. So 3 is correct.
I would've probably did something like this:

def findproductandsum(userinput):
    # Initialize counters.
    finalproduct, finalsum = 1, 0

    # Iterate over index and character in userinput.
    for i, digitchar in enumerate(userinput):
        # Convert digit character to integer
        digit = int(digitchar)
        # Position is i + 1 since the index is zero-based.
        if (i + 1) % 2 == 0:
            # Even.
            finalproduct *= digit
        else:
            # Odd.
            finalsum += digit
    return finalproduct, finalsum

# Use 'raw_input' on Python 2 though, it's a good habit to get into.
n = input('Enter a number: ')

# findproductandsum returns a tuple, so unpack it into p and s.
p, s = findproductandsum(n)
print('n: {}, product: {}, sum: {}'.format(n, p, s))

You can check it using only evens (product):

 assert(findproductandsum('01010101') == (1, 0))

and only odds (sum):

 assert(findproductandsum('10101010') == (0, 4))
Jai_4 commented: i havnt done so much of python yet. cant we do it without defining a function. also my teacher tells me that the first digit is 0th digit then so on so in 234:2 and 4 are even 3 is odd so sum is 3 and product 8. please write down a simpler code. +0

chriswelborn 63

Line 28:

if(overnightCheck >= 0 && overnightCheck <= 1)
      {
         if(overnightCheck == 1)
            overnightPrice = 5.00;
      }

That wrapper to make sure overnightCheck is 1 or 0 is pointless. Because you are checking it again just below, and then doing nothing for the false case. What happens if a user enters 2,3, or 5 in this:

if (overnightCheck == 1) {
    overnightPrice = 5.00;
}

Nothing. So, they have to enter 1 for the price to be set. The extra guard is redundant.

chriswelborn 63

If libraries aren't allowed, you could make your own Counter.

words = ['this', 'this', 'that', 'that', 'that', 'and']
wordcount = {}
for word in words:
    existing = wordcount.get(word, 0)
    wordcount[word] = existing + 1

wordcountlist = []
for word, count in wordcount.items():
    wordcountlist.extend((word, count))

print(repr(wordcountlist))
# ['this', 2, 'that', 3, 'and', 1]

Of course, there are libraries that would simplify this too..

from collections import defaultdict
wordcount = defaultdict(int)
for word in words:
    wordcount[word] += 1

Anyway, I think there are some good answers here no matter what the constraints are on the problem. Plenty to choose from. :)

chriswelborn 63

There is also collections.Counter.

from collections import Counter
wordcount = Counter(['this', 'this', 'that', 'that', 'that', 'and'])
print(repr(wordcount))
# Reveals:
# {'this': 3, 'that': 2, 'and': 1}

Not only is it easy, but I'm pretty sure it performs better (coded in C).
If you really wanted it in list format you could do this to it:

wordcountlist = []
for word, count in wordcount.items():
    wordcountlist.extend((word, count))

Or you could combine the two:

words = ['this', 'this', 'that', 'that', 'that', 'and']
wordcountlist = []
for word, count in Counter(words).items():
    wordcountlist.extend((word, count))

The order may be off, because of the Counter converting to dict. Honestly, if you are going to be retrieving the counts in the future, a dict may be better anyway. Retrieving the count would just be: wordcount['this'] or wordcount[myword]. ..instead of having to construct your own for-loop to retrieve/parse the counts.

chriswelborn 63

You have an event loop up at the top (while done==False:) that runs until the user has quit. Because of the indention, your event loop runs until completion and only then draws what you wanted it to. Your indention signifies a 'code block'.Everything in that code block will run until the code block is exited. Right now only a portion of your code is inside of the event loop. The rest of it (the important part) is outside of the code block, and doesn't run until the event loop completes. By indenting all of your logic and draw-events to the same level as the while block I was able to make your game run.

Example:

done = False
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            print('User has exited!')
            done = True

    print('We are inside of the event loop, press CTRL + C!')

print('We are outside of the event loop.')
print('Now is not a good time to start drawing stuff.')

chriswelborn 63

What was the original problem? Your method reminds me of Visual Basic's "SendKey()". If downloading and writing an html page to disk was the problem, it can be easily solved in python.

chriswelborn 63

There is a possibility that the python executable is not in /usr/bin on other people's systems. It could be in /usr/local/bin, /home/otheruser/.local/bin, or anywhere else. Without the env, you are telling it exactly which executable to use.

env will use the system's $PATH to determine where python is. There is also a possibility the env executable isn't really in /usr/bin, but that's a slim chance.

Long story short, if you are writing for only yourself and your machine, you can use whatever you want. I think it's a good practice to use #!/usr/bin/env python if you are distributing your scripts.

chriswelborn 63

Confirmed, Windows 7 gets the same (correct) output. The problem lies elsewhere, so if this doesn't help you correct it you can show me the other parts I was asking about and we can continue from there.

chriswelborn 63

Here, I booted into Windows (windows 8, i'll check windows 7 just to be sure though). This little script writes a simple text file to user directories using both the os.path.expanduser method, and the ALLUSERSPROFILE method. Both seem to work fine for me.

""" testuserdir.py
    Trys two different methods for writing a simple logfile to
    user directories in Windows.
"""

import sys, os, os.path

# short name for the test log.
short_filename = "testlog.txt"

def test_write(homedir):
    """ Trys to write sample text to a file """
    logfile = os.path.join(homedir, short_filename)
    print "Writing " + logfile
    try:
        with open(logfile, 'w') as flog:
            flog.write("Testing log file...\n")
    except (IOError, OSError) as exio:
        print "Unable to write file: " + logfile + '\n' + \
              str(exio)
        return False
    return True

def test_read(homedir):
    """ Trys to read from the sample file """
    logfile = os.path.join(homedir, short_filename)
    # Check the file
    print "Checking the file..."
    if os.path.isfile(logfile):
        print "    File contents:"
        try:
            with open(logfile) as flog:
                print '    ' + flog.read()
                return True
        except (OSError, IOError) as exio:
            print "Unable to read file: " + logfile + '\n' + \
                  str(exio)
    else:
        print "File did not exist!: " + logfile

    return False

def test_remove(homedir):
    """ Try to remove the test file """
    logfile = os.path.join(homedir, short_filename)
    if os.path.isfile(logfile):
        try:
            os.remove(logfile)
            print "Test file removed: " + logfile
            return True
        except (IOError, OSError) as exio:
            print "Unable to remove file:" + logfile + '\n' + \
                  str(exio)
    else:
        print "File doesn't exist!: " + logfile
    return False ...

chriswelborn 63

can i see a couple things so I can help you better. first, in IDLE or whatever you're using to run your script, do a print LOG_FILENAME and let me see the output. second, show me the part where the file is actually written. From when you open it (with open(LOG_FILENAME, 'w') or however you're doing it), to when you close it (when you're done writing the file). I'm gonna boot up my Windows machine and make sure I'm not steering you wrong, but I'd like to see those two pieces of info..

chriswelborn 63

I see that you are overwriting the LOG_FILENAME variable. Instead of adding "log.txt" to it, you are replacing it with "log.txt". That would make it write to the desktop I think. Try doing this instead (After getting the user's home directory):

LOG_FILENAME = os.path.join(homedir, "log.txt")
# returns: C:\Users\USERNAME\log.txt
# instead of just "log.txt"

At the very least you would have to "add" or "append" the filename to the users directory like this:

LOG_FILENAME = homedir + "log.txt"

But the os.path.join() method accounts for extra '/' or '\', which is why I use os.path.join where applicable.

chriswelborn 63

It seems you've got your answer at SO.

chriswelborn 63

Just thought I would add my 2 cents. IDLE is my 'goto' for small scripts and quick prototyping/testing. If it's not that then its 'Kate' (kde's text editor for programmers, a gnome equivalent would be gEdit).

But for bigger projects, like my Django site that has like 78 modules (due to the way django works), I use Eclipse or Aptana (Eclipse-fork) with the PyDev installed. It has auto-completion and git-integration.

I'm rarely on Windows anymore, but when I am I use PyScripter.

chriswelborn 63

one thing that i do to trim code down a little is leave out the == or != when i know I will be dealing with small integers, like:

if proc.poll():
    # non-zero return from process equates to true
    print("failure")
else:
    # zero return from process equates to false
    print("success")

i've also been using the 'with' statement when dealing with files, maybe not as important on such a small script, but i like it anyway.

try:
    with open('/var/www/ServerOverview.txt', 'a') as Log:
        Log.write('some stuff')
        # file is closed at the end of 'with'
except IOError as exOS:
    # unable to open file, disk is full, file not found, etc.
    print("Unable to open file.")
TrustyTony commented: try..except good suggestion +12

chriswelborn 63

What other operating systems are on the computer?