I'm fairly new to coding and just started this week. I'm attempting to order numbers such as test grades in ascending order. I've tried it and here's what I have (below) - it doesn't sort the list. What am I missing? I'm using Pyscripter to code python.
li=['75, 95, 65, 100, 10']
li.sort()
print(li)
li=['75,95,65,100,10'] reads one string only.
Either use
li=['75','95','65','100','10'] (list of strings)
or li=[75,95,65,100,10] (list of ints). That should work.
li=[75, 95, 65, 100, 10]
for i in range(len(li)):
for x in range (i+1, len(li)):
if li[i] > li[x]:
li[x], li[i] = li[i], li[x]
print(li)
I modified the list by removing the ' ' inside the li=[] because you have int numbers and not strings, if you want to understand much easy Python I recommend to start with the basic loops and not with predefined functions like sort().
li=[75, 95, 65, 100, 10]
li.sort(key=int)# ascending order.
For descending order add:
li.sort(key=int, reverse=True )
print (li)
Related
I am trying to sort an unsorted list [4, 5, 9, 9, 0, 1, 8]
The list has two repeated elements. I have tried to approach the question by having a loop that goes through each element comparing each element with the next in the list and then placing the smaller element at the start of the list.
def sort(ls:
ls[x]
x = [4, 5, 9, 9, 0, 1, 8]
while len(x) > 0:
for i in the range(0, len(x)):
lowest = x[i]
ls.append(lowest)
Please, could someone explain where I am going wrong and how the code should work?
It may be that I have incorrectly thought about the problem and my reasoning for how the code should work is not right
I do not know, if this is exactly what you are looking for but try: sorted(ListObject).
sorted() returns the elements of the list from the smallest to the biggest. If one element is repeated, the repeated element is right after the original element. Hope that helped.
Yes, you can try x.sort() or sorted(x). Check this out https://www.programiz.com/python-programming/methods/built-in/sorted. Also, in your program I don't see you making any comparisons, for example, if x[i] <= x[i+1] then ...
This block of code is just gonna append all the elements in the same order, till n*n times.
Also check this https://en.wikipedia.org/wiki/Insertion_sort
For a built-in Python function to sort, let y be your original list, you can use either sorted(y) or y.sort().Keep in mind that sorted(y) will return a new list so you would need to assign it to a variable such as x=sorted(y); whereas if you use x.sort() it will mutate the original list in-place, so you would just call it as is.
If you're looking to actually implement a sorting function, you can try Merge Sort or Quick Sort which run in O (n log n) in which will handle elements with the same value. You can check this out if you want -> https://www.geeksforgeeks.org/python-program-for-merge-sort/ . For an easier to understand sorting algorithm, Insertion or Bubble sort also handle duplicate as well but have a longer runtime O (n^2) -> https://www.geeksforgeeks.org/python-program-for-bubble-sort/ .
But yea, I agree with Nameet, what you've currently posted looks like it would just append in the same order.
Try one of the above suggestions and hopefully this helps point you in the right direction to if you're looking for a built-in function or to implement a sort, which can be done in multiple ways with different adv and disadv to each one. Hope this helps and good luck!
There are several popular ways for sorting. take bubble sort as an example,
def bubbleSort(array):
x = len(array)
while(x > 1): # the code below make sense only there are at least 2 elements in the list
for i in range(x-1): # maximum of i is x-2, the last element in arr is arr[x-1]
if array[i] > array[i+1]:
array[i], array[i+1] = array[i+1], array[i]
x -= 1
return array
x = [4, 5, 9, 9, 0, 1, 8]
bubbleSort(x)
your code has the same logic as below
def sorts(x):
ls = []
while len(x) > 0:
lowest = min(x)
ls.append(lowest)
x.remove(lowest)
return ls
x = [4, 5, 9, 9, 0, 1, 8]
sorts(x)
#output is [0, 1, 4, 5, 8, 9, 9]
a = [2, 5, 6, 12, 21, 25, 32, 41]
This is my list and I want to remove all the numbers which are not in difference of 7.
Before diving into the answers, let's go over what we're dealing with.
You got a list 'A', which you need to loop through to get a list of numbers that are greater than the previous value + 7
If you boil down the question, you get left with two main goals
We need a loop
and we have a list with the final answer
There are two generic ways of approaching this question. In a loop, we populate a new list. The second way is to manipulate the original list.
Although the First approach requires additional memory, I'll be using the First approach for simplicity.
a = [2, 5, 6, 12, 21, 25, 32, 41] # your original list
b = [] # Empty list that will contain final product
for i in range(len(a)):
if len(b) == 0: # if the list is empty, we add first item from 'a' (In our example, it'll be 2)
b.append(a[i])
else:
if a[i] > b[len(b)-1]+7 or a[i] < b[len(b)-1]-7: # for every value of a, we compare the last digit from list b
b.append(a[i])
As far as I have understood your question, in your output list, only those elements should be there whose sum is 7. So that can be achieved by
i=1;
while i<len(a):
if(a[i]-a[i-1] < 7):
a.remove(a[i])
else:
i+=1
print(a)
I have a code which reads all files in a directory and appends the highest value from each file into a list. The problem is that it does recognise the number 10, but recognises all numbers 0-9. Each file contains the last three scores of each person, from 1-10. However, if the person scores 10, the program does not read that as the highest value, and chooses the second highest from the file and appends that to the list instead. The code works fine if none of their scores are 10. The code should then sort the list according to each person's highest score, which does work, but because it appended the wrong score to the list, therefore it sorts it incorrectly as well.
For example:
[3, 6, 8], highest score is 8, no problem
[6, 10, 9], highest score is 9, why?
The relevant section of code is below. P.s. I have imported all modules and declared all variables at the start (just not visible here), so that is not the problem. Thanks for all help
scores = []
for file in os.listdir(path):
file = os.path.join(path, file)
if os.path.isfile(file):
with open(file, 'r') as txt_file:
scores.append(max(str(n.strip()) for n in txt_file))
results = list(zip(files, scores))
results.sort(key=operator.itemgetter(1), reverse=True)
student_list = [x + ": " + y for x, y in results]
the problem is specifically with this line:
scores.append(max(str(n.strip()) for n in txt_file))
you are grabbing the max str value, and strings compare the same way all other sequences do: compare first element, if they are the same compare next... so when you do:
max("10","9")
it first compares "1" against "9" and sees that "9" is considered greater so that is the string returned, you need to be converting them to ints for them to compare as ints:
scores.append(max(int(n.strip()) for n in txt_file))
# ^ right here
Although since you are opening every single file in a directory if any of the files contain anything other then valid numbers on every line this would fail, so you probably want a try/except, although I cannot give you an example without knowing how files is defined because scores and files need to be the same length.
Below is my code I have printing this in ascending order I now need to print it in descending order but don't know how?
list = [37,-59,4,0,15,-12,9,0]
Why don't you use the built-in sorted function?
>>> unsorted_list = [37,-59,4,0,15,-12,9,0]
>>> sorted(unsorted_list)
[-59, -12, 0, 0, 4, 9, 15, 37]
>>> sorted(unsorted_list,reverse=True)
[37, 15, 9, 4, 0, 0, -12, -59]
If you need the list both in ascending and descending order, you can get your list in reverse like so:
sorted_list_oldskool[::-1]
If you only need it in descending order, AMACB's answer is probably the most efficient.
If, for whatever reason you want to take your existing sorting logic and have it produce a list in descending order, you should change
if unsorted_list[i] <= sorted_list_oldskool[j]:
to
if unsorted_list[i] >= sorted_list_oldskool[j]:
If I understood you correctly
print("Old way : ",sorted(sorted_list_oldskool, reverse=True))
Basically we are given a list of numbers and we are asked to write an algorithm to find the largest number in the list, note: the numbers are not in order and may contain decimals and negative numbers.
this must be done using loop statements in python 3.2.3
Thanks.
alist=[3,10,90,5,-2,4,18,45,100,1,6]
largest=int()
for large in alist:
if large >= large+1:
largest=large
print(largest)
EDIT
IT WORKS!! Thanks!
alist=[-45,0,3,10,90,5,-2,4,18,45,100,1,-266,706]
largest=alist[0]
for large in alist:
if large > largest:
largest=large
print(largest)
there's also a built in function called max... works like a charm
This question was asked 9 years ago but I'm giving my answer because the question is still relevant today
we can do this for both numbers and strings
A) Finding the largest number in a given list:
your_list = [54, 26, 29, 48, 56, 32, 15, 17]
largest_num = -99999999 # Any value below zero is ok if you know there
# are larger numbers in the list
for i in your_list: # Checking every item in the list
print("current number:", i) # Printing every item in the list
# regardless of their value
if i > largest_num: # Is it larger than -99999999?!
largest_num = i # then value of largest number should be equal
# to the value of i(as integer)
print("largest number:",largest_num) # Let's print the result when
# we're done
B) Finding the largest string in a given list:
my_list = ["a", "b", "c", "A", "B", "C", " "]
largest_str = my_list[0]
for i in my_list:
print("current str:", i)
if i > largest_str:
largest_str = i
print("largest_str:", largest_str)