Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
list - 2 questions:
#31
(Jul-31-2021, 01:36 PM)ndc85430 Wrote: Unfortunately, if you're unable to break down and solve problems in a structured way, I think you're going to find programming quite frustrating.

In any case, good luck!

Thanks, but wait.
Just tell me, I dont understand what will help me what you are saying.
what do you mean structured way, writing with a pen on a notebook or something like that.
I didnt understand...
you mean write the code on a notebook with a pen? instead of at pycharm? you talk about it?
Reply
#32
I don't mean code at all. I mean describing the solution to the problem in plain human words (whether English, or whatever your language is). Imagine you're explaining to a 5 year old how to solve this problem (or any problem really).
Reply
#33
(Jul-31-2021, 02:05 PM)ndc85430 Wrote: I don't mean code at all. I mean describing the solution to the problem in plain human words (whether English, or whatever your language is). Imagine you're explaining to a 5 year old how to solve this problem (or any problem really).

but how will i explain the solution if i dont know how to code it.
or you mean like that:
you make a list >>> you make a new list and take only the even index of the list >> you add to the new list the last index of the old list >> to the last index you add before "and" >>> for example: 1 2 3 4 5 6 >>> old: 1 2 3 4 5 6, new: 1 3 5 >> new with "and": 1, 3, 5, and 6.
Reply
#34
And don't forget that the function has to return the string "hydrogen, lithium and boron". Once you have the list of items ["hydrogen", "lithium", "boron"] you still need to compose the string.

Writing things down with pencil and paper does not always directly translate to code, but it is a good step for understanding the problem. My first pass would look like this:

items = ["hydrogen", "helium", "lithium", "beryllium", "boron", "magnesium"]

Then I would ask myself "How do I remove the odd items in the list?" This is rather difficult because when you remove the first odd item how do you remember which was the next odd item?

items = ["hydrogen", "lithium", "beryllium", "boron", "magnesium"] Which is next odd??

After pondering that for a while I would probably look back at the original problem and try a different approach:

items = ["hydrogen", "helium", "lithium", "beryllium", "boron", "magnesium"]

Selecting even items is easier that removing odd items. I want items 0, 2, 4, 6, 8... Notice the index starts at zero and increases by 2. I want to stop when I run out of items.
even_items = []
i = 0
while i < len(items)-1:
    even_items.append(items[i])
    i := i + 2
I've noticed that there are a lot of for loops in Python examples and not that many while loops. I wonder if I can use a for loop? I remember seeing for loops using "range()" a lot. What does range() do?

https://docs.python.org/3/library/stdtypes.html#range
Quote:class range(start, stop[, step])
The arguments to the range constructor must be integers (either built-in int or any object that implements the __index__ special method). If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. If step is zero, ValueError is raised.

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.
even_items = []
for i in range(0, len(items), 2):
    even_items.append(items[i])
I might use that solution, or I might do some more investigation. I could use a list comprehension:

https://docs.python.org/3/tutorial/datas...prehension
even_items = [items[i] for i in range(0, len(items), 2)]
Or I might use a slice:

https://docs.python.org/3/library/functi...lice#slice
even_items = items[0:len(items):2]
And reading a bit more I would see that the 0 and len(items) can be left out.
even_items = items[::2]
Now use the same approach to converting the even_items list to a string. Start with writing down the solution on a piece of paper.

even_items[0] + ', ' + even_items[1] + ' and ' + even_items[2]

How can you make a generic solution for lists of varying lengths? What would it be for a list of length 2? length 5? length 1?
ben1122 likes this post
Reply
#35
WOW.
First of all, thanks for the huge explanation, really, much appreciation.
Secondly, I actually almost managed to solve it.
I mean, I got the evens out ( as you can see in my code ):
def format_list(my_list):
    """
    This function returns the words in the list which is in the even side.
    :param my_list: The list of the project.
    :type my_list: str, int, float
    :rtype: str, int, float
    :return: The result of the list on the even only.
    """

    if len(my_list) % 2 == 0:
        global joined_list
        joined_list = [my_list[-1]]
        return my_list[0::2]

new_list = format_list(my_list=["hydrogen", "helium", "lithium", "beryllium", "boron", "magnesium"])
print(new_list)
['hydrogen', 'lithium', 'boron']
is the output.

about using in range and for loops, its a little tricky, the course im learning says to use only options which are learnt untill this time. since this course didnt teach for loop, we cant use it, it also says ( atleast in my laungage at the site ) to use only while loop.

about what you said with the items ::2
I know about it, the problem is with def.
My problem with the exercise is mostly about the definition, as I am pretty bad at it. I know how to solve it without definitions, its not that hard that way, but since the course is saying def is a must, I have to use definitions for it ( cus it will make my coding more easier and good, something like that ).

about this: How can you make a generic solution for lists of varying lengths? What would it be for a list of length 2? length 5? length 1?
I didnt really understand what you said here ( mostly cus of english, but even if i translate it to my laungage its not that understandable to me ).

but anyway, I managed to 90% solve the first exercise with the modulo.
the only problem now is getting the "and" inside the list.


also, just to make sure, I just read again the question, I think i dont need to put the words inside a list, am i right? but even if i dont, i want to know how to answer it regarding making it inside a list and without a list ( both ways )
Reply
#36
For loop or while loop doesn't matter. If you can write code using a for loop you can write code to do the same thing using a while loop. I started with the while loop and progressed through the for loop because it naturally leads to the range() function and the range function is a lot like slicing a list.

You do not need to put the words in a list. You need to put the words in a string. The function returns a string. The only reason for putting the words in a list is it makes it easier to make the string if you only have to worry about the even words.

Getting the even words is only half the solution. According to your first post the function is supposed to return a string like "hydrogen, lithium and boron". Now that you have the even words, how are you going to make the string?

This is easy if you know there are 3 words in the list:
def format_list(my_list):
    even_words = my_list[::2]
    return even_words [0] + ', ' + even_words [1] + ' and ' + even_words [2]
But your function cannot be written to only work if my_list has 6 or 7 words, it has to work for any length my_list.
Reply
#37
Confusion!

my_list=["hydrogen", "helium", "lithium", "beryllium", "boron", "magnesium"]
slice my_list in steps of 2

newlist = my_list[0::2] # returns ['hydrogen', 'lithium', 'boron']
Your function format_list is not needed at all! You just need the above. Forget your function!

If you write your function like this:

def format_list(my_list):    
    alist = my_list[0::2]
    return alist
then pass it any list:

my_list=["hydrogen", "helium", "lithium", "beryllium", "boron", "magnesium", "chewing gum"]
# pass my_list to format_list
newlist = format_list(my_list)
You will get the slice of my_list you want, for any list!
Reply
#38
Shift a list.

You can do it like this:

my_list = [1, 2, 3]

def shift_left(alist):   
    list2 = alist[1:]
    list2.append(alist[0])
    return list2

newlist = shift_left(my_list)
Reply
#39
Just thought of this while I was ironing the clothes.

There is almost always more than 1 way to solve a programming problem.

my_list = [1, 2, 3]
order = [1, 2, 0]
list2 = [my_list[x] for x in order]
# returns [2, 3, 1]
Reply
#40
(Jul-31-2021, 03:31 PM)ben1122 Wrote: How can you make a generic solution for lists of varying lengths? What would it be for a list of length 2? length 5? length 1?

the only problem now is getting the "and" inside the list.
Now you have soliton for even list which i guess should add string and for last element.
So for odd list can for now just return list without and for last element.
Also in doc string explain types and return,here can instead use type hints
Example.
def format_list(my_list: list[str]) -> list:
    """
    This function returns the words in the list which is in the even side.
    """
    if len(my_list) % 2 == 0:
        return my_list[0::2], my_list[-1]
    return my_list[0::2]

if __name__ == '__main__':
    # Even list
    my_list = ["hydrogen", "helium", "lithium", "beryllium", "boron", "magnesium"]
    # Odd list
    #my_list = ["hydrogen", "helium", "lithium", "beryllium", "boron", "magnesium", 'carbon']

    result = format_list(my_list)
    #print(result)
    if len(result) == 2:
        print(f"{', '.join(result[0])} and {result[1]}")
    else:
        print(result)
Output:
# Even list hydrogen, lithium, boron and magnesium # Odd list ['hydrogen', 'lithium', 'boron', 'carbon']
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Discord bot that asks questions and based on response answers or asks more questions absinthium 1 34,389 Nov-25-2017, 06:21 AM
Last Post: heiner55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020