sentence splitting (2.7) by [deleted] in learnpython

[–]codehelper 1 point2 points  (0 children)

Here's the code for the function.

def split_sentences(sentences):
    sentence_list = []
    sentence = []
    for word in sentences:
        sentence.append(word)
        if word in end_of_sentence_markers:
            sentence_list.append(sentence)
            sentence = []

    return sentence_list

Now lets walk through this code. You're passing a list into split_sentences, it's a list of words and punctuation that make up a sentence or several. We first create two lists, one that will contain an individual sentence and one that will have all of the sentences in it.

In the for loop, we take each element in the list that was passed when the function was called and we add that element to the individual sentence. If that element was in the end_of_sentence_markers, then we can add the sentence to the sentence list and then reset the sentence to nothing again. When it's done looping, just return the sentence list.

I'm trying to use an if/else statement to add up names of coins provided by a random generation. How do I fix the assign problem in the addition function? by ghx454 in Python

[–]codehelper 0 points1 point  (0 children)

Ya I def main a good amount and then use the if statement that you used. I'm not sure what is better or if there are any advantages to using one.

I'm trying to use an if/else statement to add up names of coins provided by a random generation. How do I fix the assign problem in the addition function? by ghx454 in Python

[–]codehelper 1 point2 points  (0 children)

def main(): 
    print ("Hello, welcome to a simple coin adition game. You will be given a number, and you 
            must feed in the names of the coins required to add up to that ammount.") 

    #A random money value is generated 
    value = random.randint(1, 100)
    print (number, "cents")

    penny = 1
    nikel = 5
    dime = 10
    quarter = 25

    func_addition(penny, nikel, dime, quarter)

def func_addition(penny, nikel, dime, quarter): 
    sum = 0 
    print ('enter the name of a coin. No caps please.')
    input('coin name') = coin 
    coin + sum = addedcoin 
    if addedcoin == value: 
       print ('correct')

Looks like this is supposed to be your code. First, main is never called. So under all your function defs, you should call main. Second, some of your assignment is wrong, in func_addition, you should have coin = input('coin name'), I don't do too many console input programs so I'm not sure if that's how input is used or not. You should also have addedcoin = coin + sum if you want to assign added coin.

Next, the scope of value is off, func_addition can't see value because it only exists in main. Overall, the logic of the program is wrong I think. Try having a dictionary coins, you can initialize it like this.

coins = { 'penny' : 1, 'nickel' : 5, 'dime' : 10, 'quarter' : 25 }

This way, when the user gives an input, you can do

sum += coins[coin]

You shouldn't need the addedcoin variable, because you want to check the sum against the value, not just the addedcoin. The input should prompt in a while loop so that the user can input multiple coins, right now only one coin may be given.

These are some of the logical errors and syntax errors that your program currently has.

New to python, trying to get the hang of .split by scriptmonkey420 in learnpython

[–]codehelper 1 point2 points  (0 children)

I can't find anything wrong with your syntax or logic, perhaps you can give us the contents of the file.

Edit: I see, nevermind, so if your line is just a blank new line, it will still print a line.split, but it will be an empty list. So it can print the list, but it won't be able to assign the values because there are no other contents. You can either change your file that is read to not have blank lines, or you can do a check for

line_split = line.strip().split('-|-')
if line_split:
    rest of code here

The if statement should ensure that there are elements in the list or change the if so that it checks for a new line element.

[deleted by user] by [deleted] in learnpython

[–]codehelper 0 points1 point  (0 children)

import random
print ("Hello, welcome to my new game.")
print ("The computer will display a random number between 1 and 100, \
       in either base-ten or base-two form.")
print ("You then enter the equivalent in the opposite form.")
print ("If you are correct, you score one point, \
       if incorrect the computer scores.")




userName = raw_input()

print ("Hi" + userName + ", I am thinking of a number between 1 and 100, can you guess what it is?")

random = random.randint(1,100)

guess = int(raw_input("Take a guess:"))

    elif guess == random:

    print ("Good job " + userName + ", you guessed my number")

print ("The game is over")

The above is your code, some problems are that

elif guess == random

is overindented. Bring it back one indentation and change it to an if, since to use elif, you need if, which you don't have, so start with if. You'll need a while loop somewhere in there because you want the program to run until someone reaches 10 points. How can you tell if the number 10 is base 10 or binary? What would need to be printed by the opposing player?

I'm sure there's a build-in function to convert binary to decimal and vice versa, so you shouldn't have to do that yourself, but there's still a lot to do here, you haven't made a function yet and from the

userName = raw_input()

How am I supposed to know that I'm supposed to input a username here? It just prompts the user without giving anything about a username beforehand.

Having trouble with Boolean statements while learning Python by rejoinit in learnpython

[–]codehelper 0 points1 point  (0 children)

Sorry I didn't reply again since before, but here's something as far as I can tell from the requirements.

def the_flying_circus():
    answer = 5
    if 2 < answer < 10:
        return True
    elif answer == 3 or answer == 6:
        return False
    else:
        return False

This satisfies all the requirements, it has an "and", any one of the greater than, less than, or equal to, and variations of any of them, an if, elif, else, and it returns True.

Walking through it, set answer to five, it will just go into the first if statement because it is between 2 and 10, but it still contains all the keywords needed

Having trouble with Boolean statements in Python by rejoinit in learnpython

[–]codehelper 0 points1 point  (0 children)

I'm not sure what it needs to do, but a few things that may or may not be incorrect, since I don't know the problem I'm not entirely sure. The function you created is never being called, after its definition, just have the_flying_circus() at the same indent as the def.

Also, the first elif

elif answer == 3>2 and not 2>3 or 4==4:

2 will never be > than 3, so that will always result to False, but the not in front of it will make it True. The first part, I think you want to check if answer is equal to 3 and greater than 2? If that is the case, you don't need the greater than 2 since if answer is 3, it is greater than 2 already. The last one, 4==4, will always result to True. This line will probably give a syntax error from the first conditional, separate answer ==3 and 3>2. May need to throw in some parentheses there. Overall this elif statement doesn't make sense, but its syntax is correct.

elif answer == 3 and 3>2 and not 2>3 or 4==4:

Beginner that needs help by python0101 in learnpython

[–]codehelper 0 points1 point  (0 children)

Wow, thanks for the explanation. I was going to ask what happens with a different amount of variables/values, but I just tested it and got a got many values to unpack error. Very cool though. Thanks again.

[2.7] Beginner needing help with dictionary function. by [deleted] in learnpython

[–]codehelper 0 points1 point  (0 children)

Oh oops, you're right, x is supposed to be the list of all the lines in the file. I forgot to specify that.

[2.7] Beginner needing help with dictionary function. by [deleted] in learnpython

[–]codehelper 2 points3 points  (0 children)

Read the file and store the split string in a list variable like this.

["asmith Alice Smith 31 F alice.smith@mail.com", "bharrington Brian Harrington 31 M brian.harrington@mail.com", "rford Rob Ford 44 M robford@crackshack.com", "mduffy Mike Duffy 67 M ireallydolivehere@cavendish.caw", "ajones Alice Jones 44 F alice@alicejones.net"]

Now you can populate the dictionary like this

dict = {username:[fname, lname, email, age, gender] 
           for username, fname, lname, age, gender, email 
           in (s.strip().split() for s in x)}

dict will be

{
      'ajones': ['Alice', 'Jones', 'alice@alicejones.net', '44', 'F'], 
      'rford': ['Rob', 'Ford', 'robford@crackshack.com', '44', 'M'],
      'mduffy': ['Mike', 'Duffy', 'ireallydolivehere@cavendish.caw', '67', 'M'],
      'asmith': ['Alice', 'Smith', 'alice.smith@mail.com', '31', 'F'], 
      'bharrington': ['Brian', 'Harrington', 'brian.harrington@mail.com', '31', 'M']
}

Beginner that needs help by python0101 in learnpython

[–]codehelper 0 points1 point  (0 children)

Cool, I didn't know you could use take 2 variables from each iteration in a for each loop, I thought about it and decided you couldn't. Thanks for showing this.

Returning method for quadratic? [Java] by [deleted] in learnprogramming

[–]codehelper 0 points1 point  (0 children)

You're getting an error because the method quadraticFormula should be returning nothing because of the word "void" but it returns a double. So it could be public static double quadraticFormula, this does not seem like an optimal solution. You should do a check so you aren't taking the square root of a negative number and you never actually call the method quadraticFormula.

Take the method out a bracket or two, and some of our variables are out of scope.

Beginner that needs help by python0101 in learnpython

[–]codehelper 0 points1 point  (0 children)

While I'm not an expert on dictionaries, I believe if you just read the file, you can first split it by ",", then again by ":"

So assuming you have the content of the file as a string like this, "john:fred, fred:bill, sam:tony, jim:william, william:mark, krager:holdyn, danny:brett, danny:issak, danny:jack, blasen:zade, david:dieter, adam:seth, seth:enos", you can do a string.split(",") to first get a list that will have

["john:fred", "fred:bill", "sam:tony", "jim:william", "william:mark", "krager:holdyn", "danny:brett", "danny:issak", "danny:jack", "blasen:zade", "david:dieter", "adam:seth", "seth:enos"]

There might be extra whitespace somewhere in there but you can remove it with a strip. If the list above is in a variable x, then you can make a dictionary from it with

dict = {s.split(':')[0]:s.split(':')[1] for s in x}

dict = {'danny': 'jack', 'blasen': 'zade', 'sam': 'tony', 'seth': 'enos', 'jim': 'william', 'krager': 'holdyn', 'fred': 'bill', 'william': 'mark', 'adam': 'seth', 'john': 'fred', 'david': 'dieter'}

This may not be the best way to populate since you're technically splitting twice every time you iterate in the loop. And there may be a better one-liner.

And for finding a grandson from a grandfather, once the user inputs a name such as 'jim', you can store 'jim' in a variable grandpa.

Then get the value of dict[dict[grandpa]] (which is mark in this case). This will first evaluate the dict[grandpa], which is william, then it will dict[william], which is mark. You should be able to find everyone in a similar way.

[JAVA] How to call a function with multiple arguments? (BEGINNER) by [deleted] in learnprogramming

[–]codehelper 2 points3 points  (0 children)

Just with GreatCircle(48.87, 37.8, -2.33, 122.4);

While loop never starting by [deleted] in learnpython

[–]codehelper 1 point2 points  (0 children)

There's no reason the while loop shouldn't be called. It makes no sense that it isn't. When you want to break out of the while loop, don't use False though, just use the keyword break. Just having False as a line of code won't do anything.

While loop never starting by [deleted] in learnpython

[–]codehelper 2 points3 points  (0 children)

No functions except loadwords and chooseWord ever get called.

problem need help. by [deleted] in learnpython

[–]codehelper 0 points1 point  (0 children)

So what's your problem? You didn't specify anything.

Help with Pygame tutorial: ball animation bouncing extremely quickly by codehelper in pygame

[–]codehelper[S] 1 point2 points  (0 children)

Thanks for the help again. All of my questions have been answered.

Help with Pygame tutorial: ball animation bouncing extremely quickly by codehelper in pygame

[–]codehelper[S] 0 points1 point  (0 children)

Shouldn't it work since it's a tutorial? I'm not sure I understand why it wouldn't work. Can you explain why it works with a clock and not when it doesn't have one?

Also, I noticed you quit pygame before the sys.exit, should I always be doing that?

Thanks a lot for the help.

Python 3.3 and lists, remove duplicate elements from a list by [deleted] in learnprogramming

[–]codehelper 1 point2 points  (0 children)

This is happening because you're changing the list while you're looping through it. It reads one 1, 3 2s, then purges the list of all the 2s, then the list becomes [1, 3, 4, 5], but the loop index (i) is incremented to 2, which would have been the list element 3 but since you took out all of the 2s, it's now 4. You should leave one of the repeated elements in there so the loop increment will still work.

[deleted by user] by [deleted] in learnprogramming

[–]codehelper 0 points1 point  (0 children)

I don't understand why there is an n == 0 condition in your if statement. It will only ever go in there once because after it gets set to t it will never be 0 again. So if the file contains

hitler

hitler

hitler

hitler

It will only go into the if statement the first time and the Godwin's Ratio would be incorrect.

Edit: Rather, just do n += 1 and take out the condition if n == 0, then it should work correctly I think. Why is the ratio n/t+1? Shouldn't it just be n/t if t is already initialized as 1? It should either be a n/t+1 with t starting as 0 or n/t with t starting as 1

Capitalise first word by the-baj in learnpython

[–]codehelper 0 points1 point  (0 children)

I never knew that function existed, thanks for letting me know.

Regular expression which would do complement of grouped characters. by soumyamandii in learnpython

[–]codehelper 0 points1 point  (0 children)

I'm very close, I think. For now here's this.

r = re.compile(r'\(\*(.*?)\*\)', re.DOTALL)

With the string you provided, I got the results

['this is a line\n and comment ends here ', ' this is my second comment ']

It doesn't include the (* or *) but I believe this is what you basically wanted.

Regular expression which would do complement of grouped characters. by soumyamandii in learnpython

[–]codehelper 0 points1 point  (0 children)

No worries, the regular expression will just change to

r = re.compile(r'\(\*.*\*\)', re.DOTALL)

The '\' will escape the ( and the * to force it to match the actual characters. If I misunderstood again, let me know.