[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y ] [Search | Free Show | Home]

Python assistance

This is a blue board which means that it's for everybody (Safe For Work content only). If you see any adult content, please report it.

Thread replies: 37
Thread images: 2

I would like some help with a programming assignment I have for python. I do not want someone to simply give me the source code. just please guide me in the right direction as I am reaching a mental block for some reason today.

I need to:
Implement a print_menu() function, which has a string as a parameter, outputs a menu of user options for analyzing/editing the string, and returns the user's entered menu option and the sample text string (which can be edited inside the print_menu() function).

Each option is represented by a single character.

If an invalid character is entered, continue to prompt for a valid choice.
Hint: Implement the Quit menu option before implementing other options.
Call print_menu() in the main section of your code.
Continue to call print_menu() until the user enters q to Quit.

Basically, I need a selection menu that is part of a function and when called it will display the selection menu like below and also accept an argument for the menu regarding a particular task. Like, print_menu(c) would remove whitespace.
MENU
c - task 1
w - task 2
f - task 3
r - task 4
s - task 5
q - Quit


If you do attach source code, please explain why you used this method...as in if you have a for loop or while loop, why did you use that instead of another method if there was another method. Thanks for any assistance.
>>
>>348622
Well, what part in particular are you stumped on?

The basic idea is to have some sort of user input variable, a list of allowed options ['c','f','s',etc], and a while loop that ends when the user inputs 'q'. How about getting us started with some pseudocode? BTW,
> print_menu(c) would remove whitespace.
I think the idea is that you type print_menu('example StRing '), then the menu is displayed and that's where your while loop starts. The description is kind of weird though.
>>
>>348627
Right.
(1) Prompt the user to enter a string of their choosing. Store the text in a string. Output the string. (1 pt)

if __name__ == '__main__':
string = input('Enter a sample text:\n')
print('You entered:',string)

I understand prompting a user and creating a function. I guess what gets me is it is requiring that i call the function as part of the body of the program while (no problem). But, it is requiring me to define each of the choices as functions within the print_menu() function...I have not defined functions within a function before.
>>
(2) Implement a print_menu() function, which has a string as a parameter, outputs a menu of user options for analyzing/editing the string, and returns the user's entered menu option and the sample text string (which can be edited inside the print_menu() function). Each option is represented by a single character.

If an invalid character is entered, continue to prompt for a valid choice. Hint: Implement the Quit menu option before implementing other options. Call print_menu() in the main section of your code. Continue to call print_menu() until the user enters q to Quit. (3 pts)

Part of number (2):


def print_menu(usrStr):
menuOp = ' '
print('\nMENU')
print('c - Number of non-whitespace characters')
print('w - Number of words')
print('f - Fix capitalization')
print('r - Replace punctuation')
print('s - Shorten spaces')
print('q - Quit\n')
print('Choose an option:')
return menuOp, usrStr
>>
This problem has 7 parts, so I have resorted to making it simpler by tackling the first 2 parts independently so that I can understand it better, these parts being: (1)Create a variable that is a string input by the user---print that string. (2) Create a function that allows modification of that string.

We have not discussed pseudocode, so I apologize for not having prepped any.
>>
File: image.jpg (35KB, 749x332px) Image search: [Google]
image.jpg
35KB, 749x332px
>>348635
They only need to be called inside print_menu; you can define them in the global scope.

What you're looking to do, more generally, is implement a switch statement, which is a shorter way of writing

if (a="a") then do something
else if (a="b") then do something else
else if (a="c") then do something else again
else..........

With switch, you can just

switch(a):
a: do something
b: do something else
c: do something else again
...

Python doesn't actually support switch statements, see https://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python for discussion on the subject.

I really like the solution in pic related (wherein value is the variable you're switching on, and x is a parameter being passed into the functions being called).
>>
>>348656
Thanks. I was actually working on something similar at the moment.

def print_menu(usrStr):
menuOp = ' '
# Complete print_menu() function
ans=True
while ans:
print("""
MENU
c - Number of non-whitespace characters
w - Number of words
f - Fix capitalization
r - Replace punctuation
s - Shorten spaces
q - Quit
""")
ans=input("\nChoose an option:")
if ans=="c":
##PRINT NONWHITESPACE CHARCTERS
elif ans=="w":
##PRINT NUMBER OF WORDS
elif ans=="f":
##FIX CAPITALIZATION
elif ans=="r":
##REPLACE PUNCTUATION
elif ans=="s":
##SHORTEN SPACES
elif ans=="q":
print("\n Goodbye")
ans = None
else:
print("\n Not Valid Choice Try again")
return menuOp, usrStr
>>
>>348660
Oh, look into using the break statement.

For code that does "do this over and over unless this happens", it's often neater to break the loop when it happens than it is to manipulate the loop condition so it will stop next time round.

https://www.tutorialspoint.com/python/python_break_statement.htm
>>
>>348668
So far the first two parts are taken care of...at least the print statements and the input as well as the menu as displayed. I am working on the first option (c)...

I have this code below, but I am not sure about defining the global function get_num_of_non_WS_characters and calling it inside of the print_menu function after c is the input for ans....

# Type all other functions here
def get_num_of_non_WS_characters(string):
y = string.replace(" ","")
x = len(y)
return x

def print_menu(usrStr):
menuOp = ' '
# Complete print_menu() function
ans=True
while ans:
print("""
MENU
c - Number of non-whitespace characters
w - Number of words
f - Fix capitalization
r - Replace punctuation
s - Shorten spaces
q - Quit""")
ans=input("\nChoose an option:\n")
if ans=="c":
print(get_num_of_non_WS_characters(string))
elif ans=="w":
x = 1
elif ans=="f":
x = 1
elif ans=="r":
x = 1
elif ans=="s":
x = 1
elif ans=="q":
ans = None
else:
print("\n Not Valid Choice Try again")
#return menuOp, usrStr


if __name__ == '__main__':
# Complete main section of code
string = input('Enter a sample text:\n')
print('\nYou entered:',string)
print_menu(string)
>>
Ignore the x = 1 in those elif statements. that is there as just a placeholder for the indention in my code. i put that there to make it easier for me to see lol
>>
>>348673
You can use "pass".

It behaves like a statement (so the interpreter doesn't complain there's nothing there), but it doesn't do anything.
>>
>>348671
You don't need to make a separate function for counting non-spaces. Just put the code right there.
>>
>>348671
Generally you define functions in the global scope of your source file.

Functions defined inside other functions are called "nested functions" and they behave slightly differently: because they're only visible to the function they're nested in, they can only be called by the function they're nested in*, so they also get to access all the variable names in the function they're nested in.

Generally you don't use nested functions unless you need the special features of nested functions.
>>
>>348685
You don't need to wipe your ass after you shit.

>>348691
* this is not actually true: you can pass them around them as function pointers, at which point they keep the references to anything they reference, even after the enclosing function terminates. These things are called "closures" and are used in functional programming. For example, you could make
def subtractor_factory(amount):
....def subtract(value):
........return(value - amount)
....return subtract

and then if you call
s = subtractor_factory(7)

you get a function that subtracts seven from things. Even though amount was in the enclosing function, subtract can access it, and because subtract does and subtract was passed out, amount is reachable and stays alive so long as s does.
>>
>>348685
Actually, this problem requires I do so.

(3) Implement the get_num_of_non_WS_characters() function. get_num_of_non_WS_characters() has a string parameter and returns the number of characters in the string, excluding all whitespace. Call get_num_of_non_WS_characters() in the print_menu() function. (4 pts)

Ex:

Number of non-whitespace characters: 181
>>
Thanks again for the comments everyone. It has been helpful. I now have to do the fourth part:

(4) Implement the get_num_of_words() function. get_num_of_words() has a string parameter and returns the number of words in the string. Hint: Words end when a space is reached except for the last word in a sentence. Call get_num_of_words() in the print_menu() function. (3 pts)

Ex:

Number of words: 35
>>
I am thinking I can use string.split() to do this?
>>
>>348706
Hint: I would implement the shorten_spaces function first, because if you just count the spaces and add one in "this example", you'd say it had eleven words, not two.
>>
>>348710
Or it would if 4chan didn't automatically shorten spaces.
>>
This worked!

def get_num_of_words(string):
x = len(string.split())
return x

elif ans=="w":
get_num_of_words(ans)
>>
>>348697
I was gonna argue, but then I realized you're someone who would actually make a "subtractor factory" and I understand what you are now.
>>348706
So... number of spaces +1? I feel like the hint literally told you the best way to do it.
>>
>>348716
Well no, because if you used your dumbfuck algorithm on a string with a word on each end and thirty spaces between them, it would tell you that string had thirty-one words in it.
>>
>>348716
Well I just turned the string into a list by removing spaces and assumed the list elements were words. after that I find the length of the list. probably not the best method, but it passes the program check for now.
>>
The next part is below:
Capilization....I will have to look up these functions it mentions as I have never used them.

(5) Implement the fix_capilization() function. fix_capilization() has a string parameter and returns an updated string, where lowercase letters at the beginning of sentences are replaced with uppercase letters. fix_capilization() also returns the number of letters that have been capitalized. Call fix_capilization() in the print_menu() function, and then output the number of letters capitalized and the edited string. Hint 1: Look up and use Python functions .islower() and .upper() to complete this task. Hint 2: Create an empty string and use string concatenation to make edits to the string. (3 pts)
>>
>>348720
It's better than his method.

In general, you should strive to use the library whenever you can, because the library code will have considered all the corner cases, including the ones you haven't thought of.
>>
>>348721
The way it wants you to do it is in a loop that eats one character at a time, starts armed, and:

- if it encounters a lowercase letter and is armed, adds one to the count, disarms, and appends an uppercase version of it
- if it encounters an uppercase letter, disarms and appends it
- if it encounters a full stop, rearms and appends it
- otherwise just appends it

Essentially, they want a state machine.
>>
>>348719
Someone's getting tense.
>>348720
That's fine.
>>348722
You can use the library to detect multiple spaces too.
>>
>>348737
I'm not the one that acted all smart then fucked up a Programming 101 question. Just sayin'.
>>
>>348740
Your idea of "fucked up" is a specifically-crafted input meant to favor one method. We could flip this around and decide to feed in a textbook's worth of data, something that begins to have a memory and performance impact if you want to turn the entire thing into a Python object.

>You're the one that acted all smart
I think you're offended because I said counting spaces was the "best" way without backing it up, when that's not the idea you came up with.
>>
>>348902
You fucked up. Your proposal got an incorrect answer on an obvious testcase that you yourself should have thought of without being told, especially given the very next question is about removing multiple spaces.

You fucked up. You're now saying that a string with two spaces between two words is a "specially-crafted input meant to favour one method", when it's the expected input for the very next question.

You fucked up. You proposed an algorithm that objectively does not work, and now you're getting booty-blasted that a single sentence showed it didn't.

You fucked up. Own it.
>>
>>348996
Okay, this is getting funny now. Do you have a micropenis or something?
>>
>>348996
Didn't the problem say it was for sentences?
>>
>>349065
You were wrong, you were shown you were wrong, but rather than deal with it like a grownup, you're all "b-baka it's not like I wanted to count strings with more than one space between words anyway!".

Why do you keep trying to defend a wrong answer? It's obviously a wrong answer, there's no way that it can be right, so your only real complaint is that you weren't told it was wrong in a nice enough way.

Well tough shit. This isn't your safe space.
>>
>>349072
It's a right answer, given a normal sentence. You assumed an arbitrary string, then used that to show why one approach wouldn't work. Well that's right, bur then you start tossing around insults which is the weird part to me. Like, how do you even know what OP's test cases are for this specific function?
>>
>>349084
It's not a right answer, and you can't just wave that away by saying that the inputs it gets wrong are "not normal sentences". Aside from anything else, the question doesn't say "normal sentence", it says "text string", and the inputs your solution fucks up on are certainly "text strings".

The question was to count the number of words, and the number of words in a sentence with two words and four spaces is two. If you say a sentence with two words in it has five words in it, then you are wrong.

One of the other questions in the very same exercise is "write a function that removes double spaces", so you can't even claim it's reasonable to not have thought of this.
>>
>>349103
The fact that you consider it 'mine' vs 'yours' just proves how petty you are. Im not even the same guy.
>>
>>349109
You're the one defending it, it's "yours".

Do you have anything to offer of substance, or are you just going keep complaining that people are mean?
Thread posts: 37
Thread images: 2


[Boards: 3 / a / aco / adv / an / asp / b / bant / biz / c / can / cgl / ck / cm / co / cock / d / diy / e / fa / fap / fit / fitlit / g / gd / gif / h / hc / his / hm / hr / i / ic / int / jp / k / lgbt / lit / m / mlp / mlpol / mo / mtv / mu / n / news / o / out / outsoc / p / po / pol / qa / qst / r / r9k / s / s4s / sci / soc / sp / spa / t / tg / toy / trash / trv / tv / u / v / vg / vint / vip / vp / vr / w / wg / wsg / wsr / x / y] [Search | Top | Home]

I'm aware that Imgur.com will stop allowing adult images since 15th of May. I'm taking actions to backup as much data as possible.
Read more on this topic here - https://archived.moe/talk/thread/1694/


If you need a post removed click on it's [Report] button and follow the instruction.
DMCA Content Takedown via dmca.com
All images are hosted on imgur.com.
If you like this website please support us by donating with Bitcoins at 16mKtbZiwW52BLkibtCr8jUg2KVUMTxVQ5
All trademarks and copyrights on this page are owned by their respective parties.
Images uploaded are the responsibility of the Poster. Comments are owned by the Poster.
This is a 4chan archive - all of the content originated from that site.
This means that RandomArchive shows their content, archived.
If you need information for a Poster - contact them.