简体   繁体   中英

User inputs and sorted lists in Python 3

I need help producing an output like this:

1. Enter a member: samantha 
Names: ['Samantha']
2. Enter a member: susan 
Names: ['Samantha', 'Susan']
3. Enter a member: billy 
Names: ['Billy', 'Samantha', 'Susan']
4. Enter a member: billy
4. Enter a member: samantha
4. Enter a member: Jason 
Names: ['Billy', 'Jason', 'Samantha', 'Susan']
5. Enter a member: 

Members:
1. Billy
2. Jason
3. Samantha
4. Susan

I've made an effort to create a program which does this, but to no avail. I will be commenting in my questions in the code itself. Thanks in advance for the help.

def function():

    x = []
    #a = "1." # I tried to number the questions by adding these but it doesnt work
    while True:
        #a += 1
        name = input("Enter name: ").title()
        x.append(name)

        print("Names:", x)
        #if name == name: # this condition is made so that an input that is typed in again doesn't get included in the list
            #name = input("Enter name: ").title()

            # where should I add an insert() here to have the list alphabetically ordered?

        if not name: # pressing enter prints out the second half of the output, listing the members
            #print("\nMembers:", x).sort()
            break

function()

You did almost everything correct but the problem is where you are breaking from the loop. You are first appending the name and then checking if the input was just an enter. So, first check the input and then append it to list. Here is my code:

def fun1():
    l = []
    while True:
        s = input("Enter a member: ")
        if not s:
            break
        l.append(s.title())
        print("Names:", l)
    l.sort()
    print("Members:")
    for i in range(0, len(l)):
        print(i+1,end = '')
        print(".", l[i])
fun1()

Hope it helps.

This is one way you can implement your logic.

def function():

    x = []

    while True:

        name = input('{0}. Enter a member: '.format(len(x)+1)).title()

        if not name in x:
            x.append(name)
            x.sort()
            print('Names:', x)

        if len(x) == 4:
            break

    print('Members:')
    print('\n'.join(['{0}. {1}'.format(i, j) for i, j in enumerate(x)]))

Explanation

  • Only use list.append , list.sort and print names when name is not in x .
  • It appears you want a maximum for 4 names. In that case, break when len(x) reaches 4.
  • You can use a list comprehension with str.format for your final output.

The getPositionByBinarySearch is not implemented so that you can implement it yourself.

def getPositionByBinarySearch(arr, name):
    """
    implement binary search to find the index at which insertion should happen)
    return -1 if insertion is not needed (exact match is found)
    """

def func():
    arr = []
    while True:
        name = input(str(len(x)+1) + '. Enter a number: ')
        if not name:
            print "Members:"
            for i, member in enumerate(members):
                print(str(i+1) + '. ' + member)
            break;
        pos = getPositionByBinarySearch(arr, name)
        if (pos != -1):
            arr = arr[:i] + [name] + arr[i:]

You don't need many changes to your code. Main restructuring involves to move all exceptions like repetition of names and no input to the top of the loop. More explanations are integrated in the comments.

def function():
    x = []
    #no need to keep track of the number of members, the list length will give us this information
    #infinite loop that will be interrupted, when no input is given 
    while True:
        #determine length of list, +1 because Python index starts with 0
        n = len(x) + 1
        #ask for input, format prints the number into the bracket position
        name = input("{}. Enter a member: ".format(n))
        #check if name already in list
        if name in x:
            #if name in list, ignore the input and start while loop again
            continue
        #no input - print out members and stop
        if not name: 
            print("Members:")
            #get for each member the index number i
            for i, member in enumerate(x):
                #print index in position {0} and member name in position {1}
                print("{0}. {1}".format(i + 1, member))
            #leave function()
            return
        #append name and sort list
        x.append(name)
        x.sort()        
        #print list
        print("Names:", x)


function()

I'd personally prefer to use a set to avoid duplicates in a cleaner manner, and I'd also consolidate the two printing sections into a separate function. So my suggestion is for the following, which acts a bit differently from yours, but is (in my opinion) simpler:

def print_members(members):
    numbered_members = enumerate(sorted(members), 1)
    print("Members:", ", ".join(
        "{}. {}".format(*tup) for tup in numbered_members))


def collect_members():
    members = set()
    while True:
        next_member_num = len(members) + 1
        name = input("{}. Enter a member: ".format(next_member_num)).title()
        if name:
            members.add(name)
            print_members(members)
        else:
            print_members(members)
            return

Note that the sorting (only needed here for the print_members function) will become very expensive if the number of members grows too much, and in that case I'd suggest using a binary search tree instead of a set.

I kept much of your structure, but fixed quite a few things. To get the numbering, I used the % string formatting operator. You could also use str.format, which many seem to prefer .

You can sort a list in place (the list is replaced with the sorted list) by using x.sort() . To check if something is/is not in a list use thing is in mylist or thing is not in mylist

def function():

    x = []
    a = 1
    while True:
        prompt = '%d. Enter a member: ' % a
        name = input(prompt)
        name = name.title() # convert first letter to uppercase

        if name.strip() == '':  # enter or empty string entered
            print()
            print('Members:')
            for idx, item in enumerate(x):
                print('%d. %s' % (idx+1, item))
            break
        elif name not in x:
            x.append(name)
            x.sort()  # sort x in place
            print("Names: ", x)
            a += 1


function()

and my output:

1. Enter a member: samantha
Names:  ['Samantha']
2. Enter a member: susan
Names:  ['Samantha', 'Susan']
3. Enter a member: billy
Names:  ['Billy', 'Samantha', 'Susan']
4. Enter a member: Jason
Names:  ['Billy', 'Jason', 'Samantha', 'Susan']
5. Enter a member:

Members:
1. Billy
2. Jason
3. Samantha
4. Susan


------------------
(program exited with code: 0)

Press any key to continue . . .
def fun1():
    l = []
    while True:
        s = input("Enter a name or '-1' to quit: ")
        if s=='-1':
            break
        l.append(s)
    l.sort()
    print("The sorted names or numbers(whatever) are:")
    print(l)
fun1()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM