Question

I am trying to add an item, insert and sort to a list without using built...

I am trying to add an item, insert and sort to a list without using built in functions such as .append or insert or extend I have to write def function. I want to add maria to the student name list. and write another def function to sort it using index.

studentname=["kay","joe"]

def addname(studentname):

newlist = studentname[0]

for i in range(name):

name=input("enter name")

newlist =studentname +[name]

print(studentname)

addname(newlist)

Homework Answers

Answer #1

Here is the completed code for this problem. Though the question is not completely clear, I understood that the major goals are to add an element to list without using append or insert and sort a list without using built in sort methods. So I have updated the code to fulfil above requirements and a main method that asks the user to enter student names, add to the list and display it in sorted order when student enter ‘exit’ to finish the entry process. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

Note: Please maintain proper code spacing (indentation), just copy the code part and paste it in your compiler/IDE directly, no modifications required.

#code

''' method to add a name to a list without using append, insert or extent'''
def addName(student_list, name):
    #using += operator, appending name to student_list and storing in student_list
    student_list+=[name]

''' method to sort the student list '''
def sortList(student_list):
    #using bubble sort algorithm
    for i in range(len(student_list)):
        for j in range(len(student_list)-1):
            #comparing elements at index j and j+1
            if student_list[j]>student_list[j+1]:
                #swapping elements at index j and j+1
                student_list[j],student_list[j+1]=student_list[j+1],student_list[j]

''' main method for testing '''
def main():
    #creating a list with initial values 'kay' and 'joe'
    studentnames = ["kay", "joe"]
    #loops infinitely
    while True:
        #reading a name from user
        name=input('Enter a name to add or "exit" to finish: ')
        #if input if 'exit', exiting the loop
        if name=="exit":
            break
        #otherwise adding the name to list using addName method
        addName(studentnames,name)
    #after the loop, sorting the list
    sortList(studentnames)
    #printing the sorted list.
    print(studentnames)

#running main()
main()

#output

Know the answer?
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for?
Ask your own homework help question
Similar Questions
In python: I am trying to construct a list using enumerate and takewhile from a Fibonaci...
In python: I am trying to construct a list using enumerate and takewhile from a Fibonaci generator. So far the code I have is the following: def fibonacci(): (a, b) = (0, 1) while True: yield a (a, b) = (b, a + b) def createlist(n, fib): return [elem for (i, elem) in enumerate(takewhile(lambda x: x < n, fib)) if i < n] I only get half the list when I do: print(createlist(n, fibonacci())) Output: [0, 1, 1, 2, 3,...
how do i insert a given item into list without destroying non decreasing order using a...
how do i insert a given item into list without destroying non decreasing order using a if else statement and node ? c++
Hello I need a flowchart made for reference I am using flowgorithm Here is the python...
Hello I need a flowchart made for reference I am using flowgorithm Here is the python code that I need a flowchart for def get_user_input_validated(): """ Module Name: get_user_input_validated Parameters: None Description: Defence program validates input as rock, paper or scissors returns input in lowercase making input case insensitive """ choice=["rock","paper","scissors"] while True: user_choice = input("Please enter your choice (rock/paper/scissors):") if user_choice.lower() in choice: break else: print("Sorry - that selection is not valid.",end="") return user_choice.lower()
Using C++ / provide code comments so I can understand. Create a simple linked list program...
Using C++ / provide code comments so I can understand. Create a simple linked list program to create a class list containing class node { void *info; node *next; public: node (void *v) {info = v; next = 0; } void put_next (node *n) {next = n;} node *get_next ( ) {return next;} void *get_info ( ) {return info;} }; Be able to initially fill the list. Provide functions to insert/append nodes and remove nodes from the linked list. Be...
I am working on exercise 5.30 from Introduction to Computing using python (Author: Perkovic). I was...
I am working on exercise 5.30 from Introduction to Computing using python (Author: Perkovic). I was looking at the solution and was able to understand what to do. However, when I implement the temp function as indicated, I keep getting this error "ValueError: the first two maketrans arguments must have equal length". However, it seems my two arguments are equal length, so I'm not sure what I am doing wrong! print('Exercise 5.30') def many(file): infile = open(file) content = infile.read()...
Using Python (pandas as pd) I am trying to use the split, apply, combine method but...
Using Python (pandas as pd) I am trying to use the split, apply, combine method but am getting an "invalid syntax" error at the end of the line that says "for days_name, days_df in grouped_by_day" I declared grouped_by_day in the split function but did not get any errors so I am not sure what happened or how to fix it. Below is a copy of the split, apply, combine section of my code. mean_data_ser = pd.Series() #split grouped_by_day= days_df.groupby("Day of...
I am a student taking python programming. Can this problem be modified using the define main...
I am a student taking python programming. Can this problem be modified using the define main method, def main()? import random #function definition #check for even and return 0 if even def isEven(number): if(number%2==0): return 0 #return 1 if odd else: return 1 #count variables even =0 odd = 0 c = 0 #loop iterates for 100 times for i in range(100): #generate random number n = random.randint(0,1000) #function call val = isEven(n) #check value in val and increment if(val==0):...
Binary Search Tree with multiple structs? Hi, I am having an issue with trying to create...
Binary Search Tree with multiple structs? Hi, I am having an issue with trying to create a binary search tree while having multiple structs. The struct code provided is provided for us. #define CAT_NAME_LEN 25 #define APP_NAME_LEN 50 #define VERSION_LEN 10 #define UNIT_SIZE 3 struct app_info{ char category[CAT_NAME_LEN]; // name of category char app_name[APP_NAME_LEN]; // name of application char version[VERSION_LEN]; // version number float size; // size of application char units[UNIT_SIZE]; // GB or MB float price; // price in...
This is my code, python. I have to search through the roster list to find a...
This is my code, python. I have to search through the roster list to find a player using their number. it says list index out of range. it also says there is error in my main. def file_to_dictionary(rosterFile): myDictionary={}       with open(rosterFile,'r') as f: data=f.read().split('\n')       for line in data:    (num,first,last,position)=line.split() myDict=[first, last, position] myDictionary[num]=myDict print (myDictionary) return myDictionary file_to_dictionary((f"../data/playerRoster.txt"))    def find_by_number(number): player=None    second=[] foundplayer= False myDictionary=file_to_dictionary((f"../data/playerRoster.txt")) for p in myDictionary: fullplayer=p.split() second.append([fullplayer[0], (fullplayer[1]+" "+...
I am having some trouble trying to create a linked list from a text file input...
I am having some trouble trying to create a linked list from a text file input from user The three lines respectively represent a long integer ID of a person, the name of the person, and an integer ranging from 0 to 5 indicating the threat level posed by a person. 389114 Paul Bunion 5 399012 John Doe 0 685015 Johnny Appleseed 3 179318 Tom Sawyer 2 284139 Ebenezer Scrooge 5 The full connection is: Paul Bunion -> John Doe...
ADVERTISEMENT
Need Online Homework Help?

Get Answers For Free
Most questions answered within 1 hours.

Ask a Question
ADVERTISEMENT