#1 Posted by Aegon (5398 posts) -

So I've done all the questions on this assignment, but there's one left where I can't use an if statement which is making this really hard to figure out. What I have to do is create a function, let's call it months, and make it output three letter strings of the months when you input the number of the month. So if you input 4, it give you 'Apr'.

Here's where the problem comes in. If the number inputted is out of the 1-12 range, the function has to output a message telling you that you've entered a number out of the range. How do I do this without an if statement?

#2 Posted by Baillie (4032 posts) -

I have no idea about Python, but in spreadsheets, you can do this with just by reference cells.

#3 Posted by bushpusherr (762 posts) -

I'm not versed in Python at all, but if it has anything equivilant to the switch statment in c or c++, you could use that with a default case for the out of range check.

#4 Posted by glacialhelmnun (52 posts) -
#5 Posted by Aegon (5398 posts) -
#6 Posted by Ubersmake (754 posts) -
#7 Posted by Baillie (4032 posts) -
Month NumberMonth (Abbreviated)
User Input (1-12)"Reference to Table Below*
Column HeadColumn Head
1January
2February
3March
4April
5May
6June
7July
8August
9September
10October
11November
12December

This is kind of what I mean, is there not a way to incorporate that into Python? Like I said, I have no idea.

#8 Posted by Aegon (5398 posts) -
#9 Edited by FoolishChaos (431 posts) -

A switch statement is basically just another, cleaner way of doing if/else if, when you have a decent number of things to check.

If you guys haven't learned switch statements, or arrays, and your professor wants you to do this without an if statement, then its probably a python specific thing (and I'm not at all familiar with python, sorry :( ).

edit: A quick google search shows that python doesn't exactly have switch statements, but you do have dictionaries. Have you learned about those? In this case its alot like using the array method Ubersmake suggested.

#10 Posted by sir_gunblade (117 posts) -

Yeah, you can do a switch/case statement in Python. What text book have you been working out of, and what chapter have you gotten to?

#11 Posted by Dagbiker (6939 posts) -
def f(x): return { 'a': 1, 'b': 2, }.get(x, 9)
#12 Posted by Praab_NZ (280 posts) -

@FoolishChaos

A switch statement is basically just another, cleaner way of doing if/else if, when you have a decent number of things to check.

If you guys haven't learned switch statements, or arrays, and your professor wants you to do this without an if statement, then its probably a python specific thing (and I'm not at all familiar with python, sorry :( ).

Python doesnt have a switch like Java or C# unfortunately.

#13 Posted by Ubersmake (754 posts) -

@Aegon said:

@Ubersmake said:

Little/no Python here, but you could stuff all of your values into an array, and then use a number to get a specific index in that array: http://www.dreamincode.net/forums/topic/82900-working-with-arrays-in-python/

This is another method that we haven't learned in class and I think it would be pretty suspicious if I used it.

What have you actually gone over? Is string manipulation on there? The only other stupid-easy way I can think of doing this is to put all the months into one big string, "JanFebMarApr...", and then use a number to get a substring between ((n - 1) * 3) and (((n - 1) * 3) + 2), inclusive.

And if you're wondering where I got that equation, it's:

((Number of Month - 1 for Zero Index) * (Length of Month String)) + (Characters to end of Month String)

Of course, my math could be completely wrong, but that's the only other way I can think of doing this without if statements, or more standard data structures.

#14 Posted by mwjeffcott (40 posts) -

You could set up a dictionary, which maps from keys to values (like words to definitions in a book-style dictionary).

Example:

a = dict({1:"January", 2:"February", 3:"March"...........12:"December"})

You can do lookups on the dictionary of the form a[n], i.e. b = a[3], which will set b to "March"

More info: http://docs.python.org/2/library/stdtypes.html#mapping-types-dict

#15 Posted by Aegon (5398 posts) -

Ok, maybe the answer to this is dictionaries, but I'm just realizing that one of my answers to another question is wrong and I'm struggling to figure that out now.

#16 Edited by Paco (113 posts) -

It's been a while since I've done any python, but maybe you could use a while loop to keep asking for a number if it's outside the range, like so:

num=int(raw_input("enter a number: "))
while (num > 12) or (num < 1) :
  print "please enter a number between 1 and 12"
  num=int(raw_input("enter a number: "))
 
Pretty rudimentary, but does exactly what you need without an if statement. Hope that helps.

#17 Posted by Praab_NZ (280 posts) -

@jhardcopy said:

You could set up a dictionary, which maps from keys to values (like words to definitions in a book-style dictionary).

Example:

a = dict({1:"January", 2:"February", 3:"March"...........12:"December"})

You can do lookups on the dictionary of the form a[n], i.e. b = a[3], which will set b to "March"

More info: http://docs.python.org/2/library/stdtypes.html#mapping-types-dict

Still a problem of numbers out of range, even using the 'in' and 'not in' requires an if test to change the output.

#18 Edited by RollingZeppelin (1914 posts) -

This works for everything but numbers from 0 to -11. This is because python interprets a negative number as the item starting from the last and going backwards in the list. This seems like a silly question, an if statement would work perfectly for this situation. I'm not sure what your prof is trying to teach here, how to impose arbitrary frustrating limitations on oneself?

def getmonth(N):

try:

months=['jan','feb','mar','apr','may','jun','jul','aug','sep','oct','nov','dec']

f = months[N-1]

return f

except:

return 'num out of range'

u = getmonth(15)

I'm not sure how you could get around the negative number problem without an if statement.

Edit: apparently you cant indent on this forum, note that the try: and except: are indented once and the lines starting with months, f, and return are indented twice.

#19 Posted by Aegon (5398 posts) -

@Praab_NZ said:

@jhardcopy said:

You could set up a dictionary, which maps from keys to values (like words to definitions in a book-style dictionary).

Example:

a = dict({1:"January", 2:"February", 3:"March"...........12:"December"})

You can do lookups on the dictionary of the form a[n], i.e. b = a[3], which will set b to "March"

More info: http://docs.python.org/2/library/stdtypes.html#mapping-types-dict

Still a problem of numbers out of range, even using the 'in' and 'not in' requires an if test to change the output.

Yeah, the out of range part is the problem.

#20 Posted by Praab_NZ (280 posts) -

@RollingZeppelin: That's the one thing i really dislike about python, the indentation is quite hassling if you aren't used to it.

#21 Posted by mwjeffcott (40 posts) -

@Aegon: You could figure out what sort of exceptions doing so would cause, and handle them gracefully.

#22 Posted by RollingZeppelin (1914 posts) -

@Praab_NZ said:

@RollingZeppelin: That's the one thing i really dislike about python, the indentation is quite hassling if you aren't used to it.

I don't mind it, you can highlight many rows of text and tab once to indent them all. Plus it makes the program look really clean.

#23 Posted by Praab_NZ (280 posts) -

@RollingZeppelin: Thats true, but a language like Java or C can have the same tidy look without a need for consistent indentation. I just auto format all my stuff in a program like eclipse though anyway so they are roughly the same haha.

#24 Posted by RollingZeppelin (1914 posts) -

@Praab_NZ: True, lol.

#25 Posted by YOU_DIED (702 posts) -

your teacher is a jerk

#26 Edited by TyCobb (1945 posts) -

You can do it in 2 lines of code.... You could also do it in 1 line of code if you combine your dictionary {....} and the .get() method.

def get_month(key):
....months = {1: 'JAN', 2: 'FEB', 3: 'MAR'}
....return months.get(key, 'NOT FOUND!')
print(get_month(2))
def get_month(index):
....return {1: 'JAN', 2: 'FEB', 3: 'MAR'}.get(key, 'NOT FOUND!')

Python dictionaries have a get method that you can supply a returned value if the key is not found.

#27 Posted by psylah (2162 posts) -
#28 Posted by TyCobb (1945 posts) -

@RollingZeppelin said:

@Praab_NZ said:

@RollingZeppelin: That's the one thing i really dislike about python, the indentation is quite hassling if you aren't used to it.

I don't mind it, you can highlight many rows of text and tab once to indent them all. Plus it makes the program look really clean.

I love the indentation aspect of python. It's no different than having to use brackets. If anything it makes you format your code properly. There is no reason I should have to look at C# or Java code and see a line of code at the same tab level as the method brackets; that is just disgusting. Also any decent IDE will automatically put you on the correct indentation level (PyCharm is an awesome Python IDE)

#29 Posted by Praab_NZ (280 posts) -

@TyCobb said:

@RollingZeppelin said:

@Praab_NZ said:

@RollingZeppelin: That's the one thing i really dislike about python, the indentation is quite hassling if you aren't used to it.

I don't mind it, you can highlight many rows of text and tab once to indent them all. Plus it makes the program look really clean.

I love the indentation aspect of python. It's no different than having to use brackets. If anything it makes you format your code properly. There is no reason I should have to look at C# or Java code and see a line of code at the same tab level as the method brackets; that is just disgusting. Also any decent IDE will automatically put you on the correct indentation level (PyCharm is an awesome Python IDE)

Yeah no doubt, but Python is somewhat more difficult to read when you dont have the bracketing system, yeah its less convoluted but its often hard to tell with nested operations exactly what is going on.

#30 Posted by SoylentGreen (254 posts) -

@Aegon said:

This is another method that we haven't learned in class and I think it would be pretty suspicious if I used it.

I'm a little curious here: how would it be suspicious?

Programming isn't about having memorized every answer to every single problem out there, it's about being able to go out and find an answer yourself. Unless your teacher/professor is a complete jerk, going out and finding a solution that hasn't been covered in class yet should just prove that you're eager to learn.

On-topic: a dictionary sounds like your best bet. Switch statements are fugly.

#31 Edited by Aegon (5398 posts) -

@TyCobb said:

You can do it in 2 lines of code.... You could also do it in 1 line of code if you combine your dictionary {....} and the .get() method.

def get_month(key):
....months = {1: 'JAN', 2: 'FEB', 3: 'MAR'}
....return months.get(key, 'NOT FOUND!')
print(get_month(2))
def get_month(index):
....return {1: 'JAN', 2: 'FEB', 3: 'MAR'}.get(key, 'NOT FOUND!')

Python dictionaries have a get method that you can supply a returned value if the key is not found.

Thanks, he barely even glazed over that in class. I'm not sure if he even mentioned get. It'll have to do.

My last problem is trying to make a function that returns a string with all its vowels multiplied by 4. I've gotten close. I got it to multiply one of the vowels, or some other crazy thing, but not all the vowels. Any ideas? Anyone? I've been working on this one question for longer than the rest of the assignment.

I wanna listen to the bombcast :(

@SoylentGreen said:

@Aegon said:

This is another method that we haven't learned in class and I think it would be pretty suspicious if I used it.

I'm a little curious here: how would it be suspicious?

Programming isn't about having memorized every answer to every single problem out there, it's about being able to go out and find an answer yourself. Unless your teacher/professor is a complete jerk, going out and finding a solution that hasn't been covered in class yet should just prove that you're eager to learn.

On-topic: a dictionary sounds like your best bet. Switch statements are fugly.

Yes the dictionary is what I'm using. Even then, we didn't even go over the get option. From what I can gather, he really wants us to do this with no outside help. Which would mean using only the book and whatever he's taught us in class.

#32 Edited by TyCobb (1945 posts) -

@Aegon said:

@TyCobb said:

You can do it in 2 lines of code.... You could also do it in 1 line of code if you combine your dictionary {....} and the .get() method.

def get_month(key):
....months = {1: 'JAN', 2: 'FEB', 3: 'MAR'}
....return months.get(key, 'NOT FOUND!')
print(get_month(2))
def get_month(index):
....return {1: 'JAN', 2: 'FEB', 3: 'MAR'}.get(key, 'NOT FOUND!')

Python dictionaries have a get method that you can supply a returned value if the key is not found.

Thanks, he barely even glazed over that in class. I'm not sure if he even mentioned get.

My last problem is trying to make a function that returns a string with all its vowels multiplied by 4. I've gotten close. I got it to multiply one of the vowels, or some other crazy thing, but not all the vowels. Any ideas? Anyone?

I wanna listen to the bombcast :(

Not quite sure what you are asking. You take a string ("GIANT BOMB") and then multiply the vowels by 4? Multiply what exactly; the index of the vowel in the input string?

def multiply_vowels_by_four(input):
....vowels = ['A', 'E', 'I', 'O', 'U', 'Y']
....counter = 0
....index = -1
....for char in input:
........index += 1
........if char in vowels:
............counter += index * 4
....return counter

print(multiply_vowels_by_four("GIANT BOMB"))
#33 Edited by Aegon (5398 posts) -

@TyCobb: multiply the vowel itself, as in

input 'vowel'

output 'vooooweeeel'

#34 Edited by TyCobb (1945 posts) -

@Aegon said:

@TyCobb: multiple the vowel itself, as in

input 'vowel'

output 'vooooweeeel'

Easy:

def multiply_vowels_by_four(input):
....vowels = ['A', 'E', 'I', 'O', 'U', 'Y']
....output = ''
....index = -1
....for char in input:
........index += 1
........if char in vowels:
............output += char * 4
.........else:
............output += char
....return output

print(multiply_vowels_by_four("GIANT BOMB"))
output -> GIIIIAAAANT BOOOOMB
#35 Posted by Aegon (5398 posts) -

@TyCobb said:

@Aegon said:

@TyCobb: multiple the vowel itself, as in

input 'vowel'

output 'vooooweeeel'

Easy:

def multiply_vowels_by_four(input):
....vowels = ['A', 'E', 'I', 'O', 'U', 'Y']
....output = ''
....index = -1
....for char in input:
........index += 1
........if char in vowels:
............output += char * 4
............else:
........output += char
....return output

print(multiply_vowels_by_four("GIANT BOMB"))
output -> GIIIIAAAANT BOOOOMB

Alright I'm gonna try it and see what I did wrong. I can already see I was close.

#36 Edited by Aegon (5398 posts) -

@TyCobb: Yup, it works. Thank you! I was indeed very close. I think the problem was that I didn't need a nested loop and could've gotten around it. Hmmm...

Also, you don't need the index in there, lol.

#37 Posted by TyCobb (1945 posts) -

@Aegon: No prob. It was fun.

#38 Edited by Aegon (5398 posts) -

@TyCobb said:

@Aegon: No prob. It was fun.

Are you some sort of coder by profession?

said:

def f(x): return { 'a': 1, 'b': 2, }.get(x, 9)
That was so cryptic, yo.
#39 Posted by TyCobb (1945 posts) -

@Aegon said:

@TyCobb said:

@Aegon: No prob. It was fun.

Are you some sort of coder by profession?

Yea. Mainly just code in C# nowadays. I don't really have the free time anymore to play with other languages, but I dabbled in Python for a little while last year and still had PyCharm installed on my system so I figured I would see what I could remember (internet was my best friend). hehe