Python - How to sort through my list - python

Basically all I'm trying to do is get the list to sort and display in different ways. But it seems after I do the first print it will get "TypeError: 'int' object is not callable". I'm assuming that's because I'm at the end of the list and need to restart at the beginning? Not sure how to do that or if that's the reason.
##vars
Index = 0
NumSize = 0
NumInput = 0
ManNum = 0
##Asking for list size
NumSize = int(input("How many numbers would you like to enter?:\n====>"))
##Declaring list
Numbers = [0] * NumSize
##Collecting data
for Index in range(NumSize):
NumInput = int(input("Please enter a number:\n====>"))
Numbers[Index] = NumInput
##Getting highest number
MaxNum = max(Numbers)
##Printing list
print("::::The numbers you entered were::::")
for Numbers in Numbers:
print(Numbers)
##Sorting list small to large
Numbers.sort()
print("::::The numbers while sorted::::")
for Numbers in Numbers:
print(Numbers)
##Sorting list large to small
Numbers.reverse()
print("::::The numbers reversed::::")
for Numbers in Numbers:
print(Numbers)
##Printing largest number
print("::::Largest number::::\n",
MaxNum)

You use
for Numbers in Numbers:
print(Numbers)
You should not name your iterating variable the same name as your collection
try this
for number in Numbers:
print(number)

do not call the iterator with the same name as the collection, as you overwrite the later
for Numbers in Numbers:
this destroys "Numbers" array and after the loop "Numbers" is the last element of "Numbers" instead. Change all loops to
for number in Numbers:

Use anything instead of Numbers in your for loop,
so that
for i in Numbers:`
dosomething
If you print Numbers then you will see that it just carry last number you inserted in the list.
print Numbers
>>> #last Number of List

Use a different variable than Numbers in your loops. You can also use sorted(Numbers) and reversed(Numbers) to reduce the amount of variable assignments you have to do. If you don't plan to reuse MaxNum, you can do that directly in the print as well.
Here is the fully updated program:
##vars
Index = 0
NumSize = 0
NumInput = 0
##Asking for list size
NumSize = int(input("How many numbers would you like to enter?:\n====>"))
##Declaring list
Numbers = [0] * NumSize
##Collecting data
for Index in range(NumSize):
NumInput = int(input("Please enter a number:\n====>"))
Numbers[Index] = NumInput
##Printing list
print("::::The numbers you entered were::::")
for number in Numbers:
print(number)
##Sorting list small to large
print("::::The numbers while sorted::::")
for number in sorted(Numbers):
print(number)
##Sorting list large to small
print("::::The numbers reversed::::")
for number in reversed(Numbers):
print(number)
##Printing largest number
print("::::Largest number::::")
print max(Numbers)

The answer is already given above. But for the explanation purpose here is what is going wrong.
>>> Numbers = [1, 4 , 10, 8] #This is creating a list.
>>> for Numbers in Numbers: #Now when you are iterating it definately gives the result
... print(Numbers)
...
1
4
10
8
>>> Numbers #But now check what is in Numbers
8
>>>
You didn't wanted the above.
Note: >>> is the python interpretor prompt
As mentioned in the comment, please start writing code in pythonic way.
Which is:
You do not need to initialize variables like you did. You just need to assign them before you use them.
When you ask for the inputs. you do need to go do list[index] instead you could use append method.

Related

How to make Python choose the greatest number from 5 inputs(simple)way?

The problem is:
we write down a code
x = int(input("enter the number here"))
then we loop that 5 times with range and we want python to tell us which number is the greatest of all for example
1,10,100,1000
the greatest number is 1000
how can we do that?
I just do not know how to do it
Here is an easy approach:
nums = (input().split(','))
print(max(list(map(int, nums))))
As the input is taken as a string, when converting it to a list, the elements will be strings. The function map will convert each string in the list to an integer.
I don't know if it's exactly what you want but here is an input combined with a for loop in a range :
answers = []
for i in range(5):
x = int(input("enter the number here : "))
answers.append(x)
greatest_number = max(answers)
print("The greatest number is {}".format(greatest_number))
You can do it by splitting the input with respect to ",". After splitting the str should be turn into int using for loop. Now use max function with the new integer list to get the maximum number.
so your final code should be:
x = input("enter the number here: ")
list = x.split(",")
int_list = []
for s in list:
int_list.append(int(s))
max_num = max(int_list)

python:Write a program that keeps reading positive numbers from the user [duplicate]

This question already has answers here:
Storing multiple inputs in one variable
(5 answers)
Closed 2 months ago.
hi i am very new to programming and was doing my 6th assignment when i started to draw a blank i feel as thou its really simple but i cant figure out how to continue and would appreciate some advice
showing the correct code would be cool and all but i would really appreciate feed back along with it more so then what to do and if so where i went wrong
down below is what im supposed to do.
Write a program that keeps reading positive numbers from the user.
The program should only quit when the user enters a negative value. Once the
user enters a negative value the program should print the average of all the
numbers entered.
what im having trouble with is getting the number to remember okay user entered 55 (store 55) user entered 10 (store 10) user enter 5 (store 5) okay user put -2 end program and calculate. problem is its not remembering all previous entry's its only remembering the last input (which i guess is what my codes telling it to do) so how do i code it so that it remembers all previous entry's
and here is the code i have so far
number = 1
while ( number > 0):
number = int(input("enter a number. put in a negative number to end"))
if number > 0 :
print (number)
else:
print (number) # these are just place holders
If you really want to remember all previous entries, you can add them to a list, like so:
# before the loop
myList = []
# in the loop
myList = int(input("enter a number. put in a negative number to end"))
Then you can easily compute the mean of the numbers by iterating over the list and dividing by the length of the list (I'll let you try it yourself since its an assignment).
Or, if you want to save (a little) memory, you can add them each time to a variable and keep another variable for the count.
You can use a simple list in order to keep track of the numbers that have been inserted by the user. This list may then get processed in order to calculate the average when every number got read in ...
# This is a simple list. In this list we store every entry that
# was inserted by the user.
numbers = []
number = 1
while ( number > 0):
number = int(input("enter a number. put in a negative number to end "))
if number > 0 :
print (number)
# save the number for later usage.
numbers.append(number)
# calculate average
if len(numbers) == 0:
print("You have not inputted anything. I need at least one value in order to calculate the average!")
else:
print("The average of your numbers is: %s" % (sum(numbers) / len(numbers)))
What you need is an list which can store multiple values. It is often use with loops to insert/get value from it.
For instance,
number = 1
numbers = []
while ( number > 0):
number = int(input("enter a number. put in a negative number to end"))
if number > 0 :
numbers.append(number)
print (numbers)
What you get is a list of numbers like [4, 10, 17] in ascending order as append() will add number to the back of the list. To get individual numbers out of the list:
numbers[0]
Note that the index inside the bracket starts from 0, so for instance you have a list with [4, 10, 17]. You should use the below 3 to get each of them:
numbers[0]
numbers[1]
numbers[2]
Or even better, with a loop.
for x in numbers:
print (x)

Loop printing output multiple times

I created a random lottery number generator for COP1000 that passes a random number 0-9 to an array of 7 integers. However, when I print the array, I get the same output 7 times. It may be a problem with one of the loops but I am unsure of where it is coming from. Any help would be greatly appreciated.
Here is the code:
import random
print("Seven lucky numbers; are you ready?")
numbers = [0,0,0,0,0,0,0]
index = 0
while index<len(numbers):
numbers[index] = random.randint(0,9)
index = index + 1
for n in numbers:
print("\nYour random lottery number is:")
print(numbers[0],numbers[1],numbers[2],numbers[3],numbers[4],numbers[5],numbers[6])
With this:
for n in numbers:
print("\nYour random lottery number is:")
print(numbers[0],numbers[1],numbers[2],numbers[3],numbers[4],numbers[5],numbers[6])
You are printing the entire list in a loop. Either loop over the list or print the whole thing, but don't do both. The easiest way to solve this and produce your desired output is to replace the above code with the following:
print("\nYour random lottery number is:")
print(*numbers)
As stated by TigerhawkT3 it seems you are confused with how to print out the values once you have pushed them into your array. (Also you would not want to put the initial print statement inside the loop unless you want it to print for every item in the list)
This link shows how to use for loops in different capacities. One way to solve your problem would be:
print("\nYour random lottery numbers are:")
for n in numbers:
print n
If you want to loop through and print out each value with some kind of string in front of all or 1 item you can use:
print("\nYour random lottery numbers are:")
for index in range(len(numbers)):
if index == len(numbers) - 1:
print "power number: ", numbers[index]
else:
print index, ' : ', numbers[index]
Lastly if you are just trying to print all the numbers with a delimiter in one print statement then seems like this maybe a duplicate of this question or this one where the solution was:
print("\nYour random lottery numbers are:")
print ', '.join(map(str, numbers))

How do i order the numbers a user inputs?

I am basically wondering how i can store the users inputs and put them in order from least to greatest to help them find median mode or range.
from __future__ import division
amtnum = 0
sumofnums = 0
print "Hello, This program will help find the mean of as many numbers as you want."
useramtnum = input("How many numbers will you need to enter: ")#asks user to say how many numbers there are
while amtnum < useramtnum: #Tells program that while the amount of numbers is less than the users input amt of numbers to run.
amtnum = amtnum + 1 #Tells that each time program asks for number add one to amt of numbers
entnum = (int(raw_input("Enter a number:"))) #Asks user for number
sumofnums = entnum + sumofnums #Adds users number to all values
print "The amount of your numbers added up were:", sumofnums
print "The average/mean of your numbers were:", (sumofnums/useramtnum)
put 'em in a list and sort it
mylist = []
while ...
mylist.append(entnum)
mylist.sort()
print mylist
Utilize the basic data structure called a list!
Before your while loop, create a list (aka array)
user_input_list = []
After you get the individual number from the user in the while loop, add the input to the list (in the while loop)
user_input_list.append(entnum)
After the while loop, sort the list (it will sort in place)
user_input_list.sort()
Then the list has every input from the user in sorted order, least to greatest.
To access the last item in the list, use array accessors.
user_input_list[-1]
To access median, utilize the fact you can use the length of the list. Access the length(list)/2 item
user_input_list[int( len(user_input_list) / 2)] #int cast used to remove decimal points
I am by no means a Python expert (as in, this is like my third python program), but I think it's generally easier to call functions, be it in Python or in any other language. It makes code more readable.
These are all basic math functions, so I don't feel I deprived you of knowledge by just writing them. I did, however, leave the range function for you to write. (Since mylist is sorted, I'm sure you can figure it out.)
This allows the user to continually enter numbers and have the mean, median, and mode spit back at them. It doesn't handle non-integer input.
from collections import Counter
from decimal import *
def getMode(l):
data = Counter(l)
mode = data.most_common(1)
print "mode:", mode
def getMean(l):
length = len(l)
total = 0
for x in l:
total = total + x
mean = Decimal(total) / Decimal(length)
print "mean:", mean
def getMedian(l):
median = 0
length = len(l)
if (length % 2 == 0):
median = (l[length/2] + l[length/2 - 1])/2.0
else:
median = l[length/2]
print "median:", median
mylist = []
print "Enter numbers to continually find the mean, median, and mode"
while True:
number = int(raw_input("Enter a number:"))
mylist.append(number)
mylist.sort()
getMean(mylist)
getMedian(mylist)
getMode(mylist)
Solution to solve your problem :
Use a list : More on Lists
Example :
numbers = []
while amount < counter:
...
numbers.append(num)
print sorted(numbers)
You can take a look at modification of your code below.
numbers = []
print "Hello, This program will help find the \
mean of as many numbers as you want."
while True:
try:
counter = input("How many numbers will you need to enter: ")
except:
print "You haven't entered a number."
else:
break
amount = 0
while amount < counter:
try:
num = input("Enter a number: ")
except:
print "You haven't entered a number."
else:
amount += 1
numbers.append(num)
print "The amount of your numbers added up were:", (sum(numbers))
print "The average/mean of your numbers were:", ( (sum(numbers)) / counter)
print "My list not in order:", numbers
print "My list in order:", sorted(numbers)

I am trying to create a program that takes a list of numbers from the user and checks whether or not the first number given in repeated in the list

i know i can use the input function in conjunction with the eval function to input a list of numbers:
numbers = eval(input("enter a list of numbers enclosed in brackets: "))
Also, given a list named items, i can get the list of all the elements of items, except the first one, with
the expression:
items[1:]
im just not sure how to go about getting the program to do what i want it to do
If you have a list and you want to know if the first value appears again later in the list, you can use:
items[0] in items[1:]
That will return True or False depending on whether the first element in items appears again later in items.
Don't use eval, ast.literal_eval is safer
import ast
numbers = ast.literal_eval(raw_input("enter a list of numbers enclosed in brackets: "))
An easier solution will be
x = l[0]
l[0] = None
print x in l
l[0] = x
The advantage is that you don't need to recreate the list
There are two parts to your problem:
get a list of numbers from the user
check if the first number is repeated in this list
There are several ways to get a list of numbers from a user. Since you seem to be new to python, I will show you the easiest way to program this:
n = raw_input("How many numbers in your list?: ")
n = int(n) # assuming the user typed in a valid integer
numbers = []
for i in range(n):
num = raw_input("enter a number: ")
num = int(num)
numbers.append(num)
# now you have a list of numbers that the user inputted. Step 1 is complete
# on to step 2
first_num = numbers[0]
for n in numbers[1:]:
if n == first_num:
print "found duplicate of the first number"
Now, there are more elegant ways to accomplish step 1. For example, you could use a list comprehension:
numbers = [int(n) for n in raw_input("Enter a bunch of space-separated numbers: ").split()]
Further, step 2 can be simplified as follows:
if numbers[0] in numbers[1:]:
print "found duplicates of the first number"
Hope this helps

Categories