Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Python Beginner coding exercise confusion

  1. Oct 1, 2016 #1
    #mark contains personal comments and thoughts

    # BTW this assignment was a beginner exercise at codeacademy intended to test the usage of if-structures

    # I was wondering about whether or not if-structure was going to work, or if I needed a loop-structure becauses I wanted to interrogate the input, whether or not it passes the criteria (not contains numbers).
    And only in such cases where the criteria is passed then you would execute program for translating. Otherwise keep asking for input until it is correctly written into the program.

    """ requirements of the code are shown in, as they are described below"""
    1. ask for input, which must be not be allowed to be numbers. Neither reals nor integers allowed in the input word.
    2. interrogate whether or not the input word is letters only. Essentially it would also be good if only the standard letters a-z can be contained in input.
    3. the printout answer must be the letters of the input word rearranged as follows:
    • the last two letters of the printout are always "ay"
    • the first letter of the input word is moved into immediately in front of the "ay" at the printout stage
    • the printout begins with the second letter of the input word
    • printout must be in lowercase
    • printout must be one-mashed-together-word -no empty spaces allowed etc....
    Code (Python):

    answer = input("which word can I translate into pyg latin btw give only letters")
    while  str.isalpha(answer) == False:     #  I had to google this function str.isalpha()
        answer = input(" tell me only letters so we can begin")

    # in the cases when str.isalpha() gives False,  then you are stuck in loop as you should be
    # in the case of True, then you proceed as below into printout stage, out of the loop I think this is what goes on

    lowerAnswer = answer.lower()
    start=lowerAnswer[1 : len(lowerAnswer)]
    mid=lowerAnswer[0]
    finish="ay"
    print("\n{}{}{}".format(start, mid,finish))   #it was quite difficult to get this string printout properly done also in python 3
     
     
    Last edited by a moderator: Oct 1, 2016
  2. jcsd
  3. Oct 1, 2016 #2
    Yes,, I tried that same code with an if- structure variation

    if containLettersOnly(answer ) == False:
    print("you cant do that")
    else:
    execute translation
    print(translation)


    program ends though, so that was the difference between the structures I suppose. Function looked like it return boolean true or false
     
  4. Oct 1, 2016 #3

    jedishrfu

    Staff: Mentor

    I dont see your confusion. You either loop until right or loop until x tries or simply exit with an error when the input isnt right.

    If you want to do what isalpha does then loop on the string and if not right return a false. Your programs input loop then decides whether to give up or ask again forever or for x tries.
     
  5. Oct 1, 2016 #4

    I did have one confusion remaining the ending part about printing the start mid and finish variables as a singular block of text.

    Can you describe off the top of your head what does the .format() actually do there with the final printing stage.

    Im using python 3 but Ive seen some other type of structure with " %s "inside the quotes doing something similar.

    My goal is to essentially smash those strings together as one word and print that word.
     
  6. Oct 1, 2016 #5

    jedishrfu

    Staff: Mentor

    You should be able to find examples of python string formatting via google. Most programmers do this as a matter of course.

    The format takes a format string containing %s and other descriptors and variables to be formatted and combines them together.

    As an example in C code you might see a printf("%3d %10s",123,"helloworld everyone")

    It would print 123 helloworld and would chop off the everyone because you said only 10 characters in the string format descriptor.

    For your case, you should add/concatenate the strings to make a bigger string.
     
  7. Oct 14, 2016 #6

    ChrisVer

    User Avatar
    Gold Member

    if you wanted to use an if, you could do something else (like recursion) instead of iteration...
    i.e. this program does exactly the same thing:
    Code (Python):

    def myprogram(answer):
        if not str.isalpha(answer):
            new_answer=input("tell me only letters so we can begin")
            myprogram(new_answer)
        else:
            #do the rest

    ans = input("which word can I translate into pyg latin btw give only letters")
    myprogram(ans)
     
    recursion needs however something to be repeated as the function myprogram..
    the logic is that if now you give an unacceptable answer, the if will ask for new input and will rerun the program with this new input, recheck it and so on...

    tips/extra:
    1. since the myprogram() is only going to print out what you want, it returns void (if you want its type).
    2. you can create the final printout string by using the "+" operator for strings... if you have two strings s1="abc" and s2="d", then s1+s2 returns "abcd".
    So you could have written
    print("\n"+start+mid+finish).
    or define
    printoutstring = start+mid+finish
    print("\n"+printoutstring)

    I don't know it's up to you I guess? I prefer having as short code in python as possible (especially for those kind of exercises).
    3. if you want to take the rest of the string (like you do for your mid variable), although it's ok to write the len(...) to help you get used with counting, you can also emit it...
    so write lowerAnswer[1:]
    or use -1 for the last char:
    lowerAnswer[1:-1]
    saves typing, is simpler and clearer.
    4. For the booleans you don't need to write ==False or ==True...
    A method that returns true/false or their equivalents, can be used as a boolean expression in whiles and ifs... then you only need to use the logical expressions like not (which in C is equivalent to !). The isalpha() returns either T or F, so you say. Let's say it returns True (so you want to run the translation):
    if not True ===> if False ===> goes to else
    again what you wrote is not wrong, but it's unnecessary ;)
    it's like you tell it to check if True==False or False==False...
    True==False ise equivalent to False
    False==False is equivalent to True
    so your boolean is exactly equivalent to: not "boolean"
     
    Last edited: Oct 14, 2016
  8. Oct 14, 2016 #7
    Please explain further "recursion" as it pertains to python 3 and to this exercise and your proposal. I only started programming 7 weeks ago, and to be honest that was not on our course materials.
    does recursion mean that INSIDE the myprogram() function, you have the local variable new_answer which gets the value from input question. Then you somehow decided to call the same myprogram() function, the same function inside of which we currently are already executing.... And you decide to place the value from new_answer local variable into the myprogram() function. It looks like myprogram() funciton then decides to place the data from new_answer into the str.isalpha( placement into here)

    I have to say I thought that this type of shenanigans was not allowed.... but I guess it is allowed... That's why I kept to using tried and practiced structure such as while loop :woot:

    I don't understand what do you mean it returns void
    String concatenation (sp?) I did understand though.

    If I want the type (lets say...
    • I wanted the type of the global variable ans, in all cases, then print the type of ans variable in all cases.
    • but only execute translation code for pyglatin, in such cases where the only characters are letters.
    • if there is some other characters than letters, ask for new input probably
    to my understanding the types in python 3 are as follows, or it should be said that these types I was taught about at school.
    1. int
    2. float
    3. string
    4. boolean
    5. complex numbers (surely they should merit their own type, but I havent worked with these yet ?)
    please explain your usage of indexes and the usage of sub-interval notation.
    I'm a little bit confused about this subject at the moment.

    Is the sub-interval notation different interval logic, when indexing through strings, instead of lists? Is the notation logic differing between string indexing and list indexingg?

    I came up with an example in python code through which I attempt to voice my confusion
    Code (Python):
    list = ["citrus", "mango", "kiwi", "apple", "banana", "grape", "pineapple"]

    if list[1:-1] == list[1:len(list)]:
        print("now im confused about the logic of sub intervals")

    else:
        print(
    "i undeerstood that  len(list) probably outputs a natural number because "
    "that is raelly the normally understood length of the list because there exist 7 elements "
    "therefore the length probably is 7. So effectively speaking the subinterval "
    "probably becomes list[1:7] "
    )

        print(
            "on the other hand, we have the case of list[1:-1] "
    "in practical terms this means that we count the indexes "
    "list[1:6] and that 6 is the final index in the list, therefore it will be placed into the notation."
            )
           



    if I use notation such as
    lowerAnswer[1:-1]

    why would the string sub-interval include the final letter (rather than exclude the final letter)?

    My teacher's note which he gave us, also contained confusing information about list indexes.
    My teacher said something to the efffect that
    how can my teacher be correct on that note... I thought that when I use the fruit list. Lets say that I want to compare two lists
    Code (Python):

    list = ["citrus", "mango", "kiwi", "apple", "banana", "grape", "pineapple"]

    print(fruit[0:7])
    print(fruit)
    those should be identical using my own coding example.
    fruit only contained indexes from 0,1,2,3,4,5,6 (clearly seven is not included there?? so seven should be outside the range, but also, there is no error at all, program runs in this example quite well???)
     
  9. Oct 14, 2016 #8

    ChrisVer

    User Avatar
    Gold Member

    recursion is when a function is called within itself... and it's called recursion because it allows to break a problem into smaller instances (i see it better from recursion formulas in maths). Recursions allow you to repeat something and at least [in all the cases I've seen so far] they can replace a for or while loop (without meaning that you get a better performance)...
    Well I don't know but the logic of learning in all kind of programming courses I've seen teaches iteration together with recursion (or leaves recursion for after functions).

    as I said it means that within the function the same function is being recalled (maybe altered to avoid infinite loops)...
    myprogram function is called once in the main body of the code... when it enters it checks the if case, and depending on the result it either continues doing what it's meant to do, or it calls for a different input and within the myprogram function, the myprogram function is being called with different input.
    Sometimes recursion is way more helpful than whiles... because it can be a more clever way to deal with a problem... it's like you have a problem built up of very small tiny similar problems and by solving the small ones the bigger one is solved (obviously I think while is way better for your current problem, but I just told you that if you wanted to use if cases you could)... for example the factorial [itex]a_n = n \times a_{n-1}[/itex]...

    as a function it does

    n't return anything- it is just executed until it prints your output and is over... void is taken as a word from C++, I think in python void is equivalent to None... so if you tried instead of just calling the function in the main body to print it, you'd get None as an output...


    I don't understand the questions about the indices....
    I guess I got carried away with the [1:-1]
     
  10. Oct 14, 2016 #9
    yea, my understanding is that list[0:-1]
    that one returns the elements from the list such that:
    all elements between first element (first element included), until the second last element (including that second last element.) So, you disregard the actually last element...

    at least I think it works like that.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted



Similar Discussions: Beginner coding exercise confusion
  1. Confused java HW code (Replies: 9)

Loading...