Sort an integer list in Python - python

I'm a beginner programmer and I'm trying to make an exercise.
I want to sort an integer list, but every time I run my code the list is not sorted. I've tried it in a couple of different ways with sorted() or .sort() but nothings seems to help.
def main():
_list1_ = []
_list2_ = []
print("Enter random numbers and enter Q to quit: ")
userInput1 = input("")
while userInput1.upper() != "Q":
_list1_.append(int(userInput1))
userInput1 = input("")
print("Enter random numbers and enter Q to quit:")
userInput2 = input("")
while userInput2.upper() != "Q":
_list2_.append(int(userInput2))
userInput2 = input("")
sorted(_list1_)
sorted(_list2_)
print(_list1_)
main()
Thanks!

sorted() doesn't sort the list in place. It returns the sorted list, so you will need to change the 2 sorted() calls to something like this:
_list1_ = sorted(_list1_)
_list2_ = sorted(_list2_)
It's always a good idea to read the documentation to get an understanding for how the functions work. Here is the docs for sorted
https://docs.python.org/2/library/functions.html#sorted

sorted returns the sorted list whereas sort performs the sort in place.
So you could either do:
_list1_ = sorted(_list_)
or:
_list1_.sort()
If you were to use sort (my preferred method) your code would look like this:
def main():
_list1_ = []
_list2_ = []
print("Enter random numbers and enter Q to quit: ")
userInput1 = input("")
while userInput1.upper() != "Q":
_list1_.append(int(userInput1))
userInput1 = input("")
print("Enter random numbers and enter Q to quit:")
userInput2 = input("")
while userInput2.upper() != "Q":
_list2_.append(int(userInput2))
userInput2 = input("")
_list1_.sort()
_list2_.sort()
print(_list1_)
main()

sorted(_list1_)
returns a list after sorting list1, It does not sort the list1. so write
print(sorted(_list1_))
or assign the sorted list1 to list1, like
_list1_ = sorted(_list1_)

Related

Taking user input and appending it to a tuple? Python

So basically I'm trying to create a list of movies with their budgets, but I don't know how to take the input and place it into a tuple
movie_list = ()
while True:
title = print("Enter movie: ")
budget = print("Enter budget: ")
movie_list.append(title, budget)
user = input("Would you like to add more movies? (y) or (n)").upper
if user == 'N':
break
if user != 'N' and 'Y':
print("Invalid entry, please re-enter!\nContinue? (y) or (n)")
print(movie_list)
Tuples don't handle appending well. But lists do:
movie_list = [] # make a list, not a tuple
while True:
title = print("Enter movie: ")
budget = print("Enter budget: ")
movie_list.append( (title, budget) ) # append a 2-tuple to your list, rather than calling `append` with two arguments
user = input("Would you like to add more movies? (y) or (n)").upper
if user == 'N':
break
if user != 'N' and 'Y':
print("Invalid entry, please re-enter!\nContinue? (y) or (n)")
print(movie_list)
You can’t add elements to a tuple due to their immutable property. You can’t append for tuples.
Tuples are immutable in Python. You cannot add to a tuple.
A tuple is not a data structure like a list or an array. It's meant to hold a group of values together, not a list of the same kind of values.
I think I get what you want, my guess would be that you want a list of tuples. In that case, just change the first line variable to be a list.
I improved your code so your logic works:
movie_list = [] # movie_list is a list
while True:
title = input("Enter movie: ") # Use input() to get user input
budget = input("Enter budget: ")
movie_list.append((title, budget)) # Append a tuple to the list
# movie_list is now a list of tuples
# Check if the user wants to add another movie
more = None
# Loop until the user enters a valid response
while True:
more = input("Add another? (Y/N): ").upper()
if more in ("Y", "N"):
break
print("Invalid input")
# If the user doesn't want to add another movie, break out of the loop
if more == "N":
break
# Else, continue the loop
print(movie_list)
Coding apart, to write any program, first one should know the purpose of the program and its outcome. It would be better, if you can show here what the exact output you want, out of the created or appended list. As far as I understood your requirement, you should go with dictionary concept so that you can store data as pairs, like, movie and its budget.
{"movie":budget}
While taking input of budget, be sure whether you want to restrict the input value to an integer or you want to allow this as a string, like in crores. Hope this will help you.

Extract items from 2D list

I have the following 2D list
listItem = [["Apple", "TP123", "67", "77"], [
"Orange", "TP223", "55", "66"], ["Banana", "TP777", "98", "88"], ["Cherry", "TP123", "98", "88"]]
I want to compare the user input with the second element in each list in the listItem and print out the whole list if the value matches. If the value doesn't match, I will ask the user to enter the value again and again.
Here is my code:
def repeat():
tp = input("Please enter your tp: ")
for i in range(len(listItem)):
if tp == listItem[i][1]:
print(listItem[i])
break
else:
repeat()
I am facing some problems here. In the listItem, there are two "TP123". However, if the user enters "TP123", it only prints out one result instead of two. But if I didn't use the break, the code will keep asking users to enter another value even though the value they enter matches.
I am a python beginner, can anyone help me to solve this problem, thank you very much.
Use an extra variable and set it to True if their are matches, and use an if statement to trigger the repeat function again if it's False:
And also better without range:
def repeat():
tp = input("Please enter your tp: ")
match = False
for i in listItem:
if tp == i[1]:
print(i)
match = True
if not match:
repeat()
You are breaking before it can find the next item. Also no need to use range just loop through the list.
def repeat():
tp = input("Please enter your tp: ")
print(*(i for i in listItem if i[1] == tp), sep='\n')
Or in full for loop:
def repeat():
tp = input("Please enter your tp: ")
for i in listItem:
if tp == i[1]:
print(i)

Can't figure out how to check my list and input with each other

I'm trying to make a simple wake up file in Python 3, but I can't seem to get my list and input to work with each other.
Here's the code:
from random import *
difficulty = (int(input("How many random numbers: ")))
list = []
for i in range(difficulty):
numbers = randint(0, 10)
list.append(numbers)
print(list)
answer = (input("Write the same numbers in the right order: "))
split = answer.split()
print(split)
if split == list:
print("Correct!")
else:
print("Wrong!")
You are comparing a list of strigns to a list of ints, use:
split = [int(a) for a in answer.split()]

Python Lists: .lower() attribute error

I am trying to create a program on python to do with manipulating lists/arrays. I am having trouble with an error:
lowercase = names.lower
AttributeError: 'list' object has no attribute 'lower'
I really need some help to fix this!
names = [] #Declares an array
print("Type menu(), to begin")
def menu():
print("----------------------------MENU-----------------------------")
print("Type: main() for core functions")
print("Type: delete() to delete a name")
print("Type: save() to save the code")
print("Type: load() to load the saved array")
print("Type: lower() to make all items in the list lower case")
print("-------------------------------------------------------------")
def main():
times = int(input("How many names do you want in the array? ")) #Asks the user how many names they want in the array
for i in range(times):
names.append(input("Enter a name ")) #Creates a for loop that runs for the amount of times the user requested, it asks the user to enter the names
choice = input("Would you like the array printed backwards? ") #asks the user whether they want the array backwards
if choice == "Yes":
names.reverse() #If the user says yes, the array is reversed then printed backwards
print(names)
else:
print(names) #Otherwise, the array is printed normally
number = int(input("Which item would you like to print out? "))
number = number - 1
print(names[number])
start = int(input("What is the first position of the range of items to print out? "))
start = start - 1
end = int(input("What is the last position of the range of items to print out? "))
print(names[start:end])
def delete():
takeAway = input("Which name would you like to remove? ")
names.remove(takeAway)
print(names)
def save():
saving1 = open("Save.txt", 'w')
ifsave = input("Would you like to save the array? ")
if ifsave == "Yes":
for name in names:
saving1.write("%s\n" % name)
saving1.close
else:
menu()
def load():
loadquestion = input("Would you like to load a list of names? ")
if loadquestion == "Yes":
saving1 = open('Save.txt', 'r')
print(saving1.read())
saving1.close()
else:
menu()
def lower():
lowerq = input("Would you like to make the array lowercase? ")
if lowerq == "Yes":
lowercase = names.lower
print(lowercase)
else:
menu()
The variable names is a list. You can't use the .lower() method on a list.
pp_ provided the solution:
lowercase = [x.lower() for x in names]
While not exactly equivalent to the previous example, this may read better to you and has, effectively, the same result:
lowercase=[]
for name in names:
lowercase.append(name.lower())
Alternate solution that may fit your needs:
print (str(names).lower())
Like the error message says, you can't use .lower() on lists, only on strings. That means you'll have to iterate over the list and use .lower() on every list item:
lowercase = [x.lower() for x in names]

regarding the use of input().split() with 3+ items

I'm currently working on a program that deals with user input and I came across a situation where I needed multiple returns under one input(), at first I didn't know what I was doing when I was getting a value error until I looked up how to do it, which it showed me and worked fine with 2 inputs with input().split()
class userinput():
def __init__(self, name,lista,listb,listc,listd):
self.name=""
self.lista=lista
self.listb=listb
self.listc=listc
self.listd=listd
def set_lists(self):
print("Do you want to create lists")
decision = input()
if decision == "yes":
print("how many lists would you like to create?(up to 4)")
decision2= int(input())
if decision2 == 1:
print("what would you like the list to be named")
self.lista=input()
print("you have created 1 list, with the name:"+ self.lista)
elif decision2 == 2:
print("what would you like your lists to be?")
self.lista,self.listb=input().split(",")
print("You have created 2 lists with the names," + self.lista ,self.listb)
elif decision2 == 3:
print("what name would you like your first 2 lists to be")
self.lista,self.listb = input().split(",")
print("finally, the name for your third")
self.listc = input()
print("you have created 3 lists with the names," +self.lista,self.listb,self.listc)
elif decision2 == 4:
print("what name would you like your first 2 lists to be")
self.lista,self.listb = input().split(",")
print("finally, for your last 2 lists")
self.listc,self.listd=input().split(",")
print("you have created three lists with the names of," +self.lista,self.listb,self.listc,self.listd)
else:
print("quitting")
return
else:
print("quitting")
My Question: it seems as if it isn't necessary to use 2 input().split() for 4 inputs, Is there anyway to clean that up?
You have a couple of problems, and a lot of duplication here. An approach with a couple of improvements:
decision = input("Do you want to create lists?")
if decision.lower() in ("y", "yes"):
list_count = int(input("How many lists?"))
names = input("Enter list names (separated by commas):").split(",")
if len(names) != list_count:
raise ValueError("Expected {0} names, got {1}".format(list_count,
len(names)))
self.lists = {name: [] for name in names} # dictionary of empty lists
print("Created {0} lists.".format(list_count))
(Note that Python 2.x uses raw_input).
split creates a list of as many items as the string could be split into, unless constrained by a second, optional argument maxsplit:
"a,b,c".split(",") == ["a", "b", "c"]
"a,b,c".split(",", 1) == ["a", "b,c"]
I think this code would be a bit cleaner.
print("Do you want to create lists")
decision = input()
if decision == "yes":
print("how many lists would you like to create?(up to 4)")
decision2= int(input())
print("What would you like the lists named?")
listnames = input()
lists = listnames.split()
print("you have created %i lists with the following names: %s"%(decision2, ",".join(lists)))
else:
print("quitting")
a, b, c, d = raw_input("what name would you like your 4 lists to be\n").split(',')
split can split string into more than two parts.
I'd just do this:
def set_lists(self):
print("Do you want to create lists")
decision = input()
if decision.lower().startswith("y"):
print("how many lists would you like to create? (up to 4)")
decision2 = int(input())
if decision2 == 1:
print("what would you like the list to be named")
self.lists = [input()]
print("you have created 1 list, with the name:"+ self.lists[0])
elif 2 <= decision2 <= 4:
print("Enter your lists' names, seperated by commas")
self.lists = input().split(",")
if len(self.lists) != decision2:
print("You didn't enter the right amount of names!")
else:
print("You have created {} lists with the names {}".format(decision2, ", ".join(map(str, self.lists)))
else:
print("quitting")
else:
print("quitting")
And then do self.lists[0], self.lists[1] etc. rather than self.lista, self.listb.

Categories