This is the program for bubble sort. It is not displaying the correct output. I don't understand why.
numbers = input("enter nos.: ")
my_list = list(numbers)
def bubble(list):
length = len(list) - 1
sorted = False
while sorted == False:
for i in range(length):
if list[i] > list[i+1]:
sorted = False
list[i], list[i+1] = list[i+1], list[i]
sorted = True
bubble(my_list)
print "Sorted list is: ",my_list
OUTPUT:
enter nos.: 1,454,867,43,421,0,8,43,121,45656,76,4,34,1
Sorted list is: [1, 454, 43, 421, 0, 8, 43, 121, 867, 76, 4, 34, 1, 45656]
your while loop will terminate after a single pass because sorted is always set to true. try putting that statement before your for loop.
Alright I found your problem : the While loop is only executed once.
Your While condition is sorted == False, and you set sorted = False if you do an inversion. You have to change that :
numbers = input("enter nos.: ")
my_list = list(numbers)
def bubble(list):
length = len(list) - 1
sorted = True
while sorted == True:
sorted = False
for i in range(length):
if list[i] > list[i+1]:
list[i], list[i+1] = list[i+1], list[i]
sorted = True
bubble(my_list)
print "Sorted list is: ",my_list
Related
Here is what I have tried
c = ['8781' ,'2740', '1413', '3060', '5074']
d = ['8853' ,'2812', '1355', '2986', '5107']
start = map(int, c)
end = map(int, d)
for n,m in zip(start,end):
if n < m:
preS = map(lambda x:x-21, start)
preE = map(lambda x:x+20, end)
print (preS, preE)
else:
preS = map(lambda x:x-20, end)
preE = map(lambda x:x+20, start)
print (preS, preE)
Here my else part of loop is not executing and I got multiple lines of same output. Whats wrong here?
I am expecting in following way:
preS preE
8760 8873
2719 2832
1433 1335
3080 2966
5053 5127
I get the following output:
([8760, 2719, 1392, 3039, 5053], [8873, 2832, 1375, 3006, 5127])
([8739, 2698, 1371, 3018, 5032], [8893, 2852, 1395, 3026, 5147])
([8719, 2678, 1351, 2998, 5012], [8913, 2872, 1415, 3046, 5167])
([8719, 2678, 1351, 2998, 5012], [8913, 2872, 1415, 3046, 5167])
([8718, 2677, 1350, 2997, 5011], [8913, 2872, 1415, 3046, 5167])
I would really appreciate for answers.
You are updating and printing the whole result lists in each iteration. The result from the last iteration "wins", and all elements in the result from the earlier iterations are overwritten.
Instead, you need to handle the elements individually, and only print the result once at the end:
preS = []
preE = []
for n, m in zip(start, end):
if n < m:
preS.append(n - 21)
preE.append(m + 20)
else:
preS.append(n - 20)
preE.append(m + 20)
print preS, preE
The whole thing can be expressed more concisely by a list comprehension:
preS, preE = zip(*[(n - 21, m + 20) if n < m else (n - 20, m + 20)
for n, m in zip(start, end)])
It uses the zip(*list) idiom to transpose the list of pairs.
I'm trying to return the factors of a number which are prime numbers in this code. For example, if someone enters in n = 55, they'll get back 5 and 11. I believe I have the first part correct in checking for the factors, but somehow I'm not sure what I'm missing in the second part of checking for prime numbers.
When I run the code for 55, I only get 5 (11 is missing).
Can someone please help review my code and provide feedback?
l = []
primefactors = []
def factor(n):
count = 0
print 'These are the factors:'
for num in range(2,n+1):
if n%num == 0: #checks that it is a factor
print num #These are the factors
l.append(num)
for i in l:
if i == 2 : #checks for two
primefactors.append(i)
else:
for x in range(3,i+1,2): #checks for odd numbers
if i%x == 0:
count += 1
if count == 1:
primefactors.append(i)
print "These are the prime factors:"
print primefactors
You can get all the factors by simply removing all unnecessary stuff, but that will not guaranty, that the number is prime number:
l = []
primefactors = []
def factor(n):
count = 0
for num in range(2,n+1):
if n%num == 0 and num != n: #checks that it is a factor
primefactors.append(num)
print ("These are the prime factors:")
print (primefactors)
del l[:]
del primefactors[:]
try this one, I added an additional check to see if number is a prime before appending to primefactors list.
primefactors = []
def factor(number):
for i in range(2,int(number//2)+1):
prime = True
for j in range(2,int(i**.5)+1):
if i%j == 0:
prime = False
break
if prime and number%i == 0:
primefactors.append(i)
print (primefactors)
factor(92)
factor(55)
output:
[2, 23]
[2, 23, 5, 11]
got stuck in a exercise and could need som help!
Exercise: Create a function that takes the list:
[123, 4, 125, 69, 155]
as argument. The function should multiply all even numbers by 1 and
add 6 to all odd numbers. Answer with the modified list sorted in
numerical order, descending.
my code so far is.
list1 = [123, 4, 125, 69, 155]
def multi():
for num in list1:
if num % 2 == 0:
num * 1
else:
num + 6
return list1
In the answer i put `def multi():
the answer i get is
[123, 4, 125, 69, 155] <class 'list'>
and the correct answer is [161,131,129,75,4]
could anyone please point me in the right way?
Thank you.
You are modify the for loop variable num itself and not the original list value
Code below should do the job
list1 = [123, 4, 125, 69, 155]
def multi():
for i,num in enumerate(list1):
if num % 2 == 0:
num *= 1
else:
num += 6
list1[i] = num # modify list value
return sorted(list1)[::-1] # this do sorting then reverse from large to small
No need to multiply by 1. just check if number is odd add 6.
list1 = [123, 4, 125, 69, 155]
def multi():
for i,num in enumerate(list1):
if num % 2 != 0:
num +=6
list1[i] = num
return sorted(list1)[::-1]
I have a question on how to get the following output in python 2.7.
>> bubble(['abe','Ada','bak','bAr'], False)
['Ada', 'bak', 'bAr', 'abe']
['bak', 'bAr', 'Ada', 'abe']
['bAr', 'bak', 'Ada', 'abe']
>> bubble(['Adm','abe','bAr','bak'], False)
['Ada','bAr','bak','abe']
['bArt','bak','Ada','abe']
The input for the functions are the following.
A list of strings (L) and a Boolean value which represent ascending alphabetical order (asc=True) or descending alphabetical order (asc=False). In both cases, it is in dictionary order. I want to print out the state of the list every time there is a pass.
def bubble(L, asc):
n = len(L)
if asc == False:
for i in range(1,n):
for ii in range(n-i):
if L[ii].upper()<L[ii+1].upper():
tmp=L[ii]
L[ii]=L[ii+1]
L[ii+1]=tmp
print L
if asc == True:
for i in range(1,n):
for ii in range(n-i):
if L[ii].upper()>L[ii+1].upper():
tmp=L[ii]
L[ii]=L[ii+1]
L[ii+1]=tmp
print L
In addition, can I replace the way I am currently accessing item of list to i-1 and i and not i,i+1 ?
Print it after the inner loop gets over.
def bubble(L, asc):
n = len(L)
if asc == False:
for i in range(1,n):
for ii in range(n-i):
if L[ii].upper()<L[ii+1].upper():
tmp=L[ii]
L[ii]=L[ii+1]
L[ii+1]=tmp
print L
if asc == True:
for i in range(1,n):
for ii in range(n-i):
if L[ii].upper()>L[ii+1].upper():
tmp=L[ii]
L[ii]=L[ii+1]
L[ii+1]=tmp
print L
For the second part of your answer, you can use your inner loop to be
for ii in range(n-1,i,-1). // This runs the loop in reverse order.
for i in range(1,n):
for ii in range(n-1,0,-1):
if L[ii-1].upper()<L[ii].upper():
tmp=L[ii-1]
L[ii-1]=L[ii]
L[ii]=tmp
You meant this, right?
Use feature of range method which allow you to iterate in reverse order
print range(1,3) # [1,2]
print range(3-1, 0, -1) # [1,2]
By the way you can avoid code duplication of loops ( if asc == False and if asc == True remove conditions).
To do it use function below(i've added comments):
def bubble(L, asc=False):
n = len(L)
# passing -1 as lest argument of range is allow to iterate in reverse order
for i in range(n-1, 0, -1):
for ii in range(n-1-i, 0, -1):
# you assign boolean value which depends on `asc` param to comparison_result
comparison_result = L[ii-1].upper() > L[ii].upper() if asc else L[ii-1].upper() < L[ii].upper()
# check bool of comparison_result
if comparison_result:
tmp=L[ii-1]
L[ii-1]=L[ii]
L[ii]=tmp
print L
print bubble(['1', 'a', 's'])
Line
comparison_result = if asc else L[ii-1].upper() < L[ii].upper()
is equivalent of:
if asc:
comparison_result = L[ii-1].upper() > L[ii].upper()
else:
comparison_result = L[ii-1].upper() < L[ii].upper()
I am trying to implement the merge sort algorithm using the following code but am getting a list index is out of range error.
def mergeSort (unSortedList):
if len(unSortedList) == 1 :
return unSortedList
else:
midpoint = len(unSortedList)//2
A = mergeSort (unSortedList[:midpoint] )
B = mergeSort (unSortedList[midpoint:] )
i = 0
j = 0
C = []
for k in range(len(unSortedList)):
if A[i] >= B[j]:
C.append(A[i])
if i == len(A):
C.append(B[j:])
else:
i += 1
elif A[i] < B[j] :
C.append(B[j])
if j == len(B):
C.append(A[i:])
else:
j += 1
return C
testlist = [2,1,4,2,5,6,8,9]
print (mergeSort(testlist))
Any help would be appreciated.
Here is my version of your mergeSort, with the merge function extracted:
def mergeSort (unSortedList):
if len(unSortedList) == 1 :
return unSortedList
else:
midpoint = len(unSortedList)//2
A = mergeSort (unSortedList[:midpoint] )
B = mergeSort (unSortedList[midpoint:] )
return merge(A, B)
def merge(a, b):
i = 0
j = 0
c = []
while True:
if a[i] < b[j]:
c.append(b[j])
j += 1
elif a[i] >= b[j]:
c.append(a[i])
i += 1
if i == len(a):
c.extend(b[j:])
break
if j == len(b):
c.extend(a[i:])
break
return c
Output:
>>> testlist = [2,1,4,2,5,6,8,9]
>>> mergeSort(testlist)
[9, 8, 6, 5, 4, 2, 2, 1]
Couple of things to note:
Appending a list to a list. When you do C.append(A[j:]) you end up with nested lists. That is because A[j:] always returns a list. You either need to use list addition - C += A[j:] - or call extend - C.extend(A[j:])
Missing breaks. When your i or j got to the end of their lists you correctly appended the rest of the other list but you did not terminate the loop. That is what caused the range error because in the next iteration (which should not happen) you tried to get an item at the index equal to the length of the list which is out of range.