why my bubble sort does not function propertly? [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
i'm trying to use an optimized way of a bubble sort using the (while True ..loop) but can't see why it still prints out [5, 6, -5, 2, 7, 8, 9]
def tree_bulle(l):
n=len(l)
while True :
new_tour=False
for i in range(n-1):
if l[i]>l[i+1]:
l[i],l[i+1]=l[i+1],l[i]
new_tour=True
n-=1
if new_tour==False or n==0:
break
list=[5,8,6,-5,2,7,9]
tree_bulle(list)
print(list)

There is extra indent in n-=1. So when the for circulation execute first time, the n will get smaller. so the next time, the while circulation will only execute for i in range(2-1), then you code can not sort the remain elements anymore.
change your code to:
def tree_bulle(l):
n=len(l)
while True :
new_tour=False
for i in range(n-1):
if l[i]>l[i+1]:
l[i],l[i+1]=l[i+1],l[i]
new_tour=True
n-=1 # n is changed after the for circulation
if new_tour==False or n==0:
break
list=[5,8,6,-5,2,7,9]
tree_bulle(list)
print(list)

Related

function that produces a list with range as parameter [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
why do the following lines of code:
def every_three_nums(start):
lst = []
for x in range(start,100,3):
lst.append(x)
return lst
when asking print(every_three_nums(91)) just returns 91 as output
thank you in advance for your support
This is because your return is in the for, when a return is called the function ends, try this :
def every_three_nums(start):
lst = []
for x in range(start,100,3):
lst.append(x)
return lst
Wrong indentation of return, so it will returen a list with just one element [91].
Actually you don't need that function, see below
def every_three_nums(start):
lst = []
for x in range(start,100,3):
lst.append(x)
return lst
print(every_three_nums(91))
print(list(range(91,100,3)))
The output is
[91, 94, 97]
[91, 94, 97]

why is my recursion not returning the desired output? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am writing a recursion function that simply returns x^n:
def myPow(x,n) -> float:
def recurs_n(x,n):
if n==1:
return x
if n>1:
result = myPow(x,n-1)
return result
return recurs_n(x,n)
print(myPow(2,5))
The output that I am getting for the above is 2, which isn't correct obviously. Any idea where I am going wrong?
Your inner function calls the outer function, that should not be allowed. Furthermore, there is no logic applied anywhere for the multiplication when going to the n-1 step. So when n>1 you need to return x*myPow(x,n-1)
I should also mention, that in your case there is no real need to have an inner and outer function, one function should be enough. Like so;
def myPow(x,n) -> float:
if n == 1:
return x
if n > 1:
return x*myPow(x,n-1)
print(myPow(2,5))
Your code runs until power n=5 reaches 1, where it activates the first if condition where x is returned (here x=2) without continuing onwards.
An alternative is presented below:
def power(N, P):
# if power is 0 then return 1
if P == 0:
return 1
# if power is 1 then number is
# returned
elif P == 1:
return N
else:
return (N*power(N, P-1))

basic question about python for loop and enumerate [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to build a function that will return the sum of the first item in the data list and every tenth item after, so I write the script below, however, the result is always the first data in my list. How should I modify my code and fix it?
def Sum10th(data):
sum=0
for i,d in enumerate(data):
if (i % 10 == 0): sum = sum+d
return sum
p = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
print(Sum10th(p))
The desired result should be 31, however the computer only returns the value of 1.
You can try
p = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
def Sum10th(data):
return sum([v for i, v in enumerate(p) if (i + 1) % 10 == 0 or i == 0])
print(Sum10th(p))
Output
31
By using the list comprehension with an if, at the end of it, you can get all the first item with the tenth item following it from a list.
Try this way:
def sum10thdata(data):
sum = 0
l = len(data)
for i in range(0,l,10):
sum+=data[i]
return sum

Syntax error when assigning a variable Python [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I keep getting a syntax error in this code on answer += rom_val[s[x]] - rom_val[s[x - 1]]:
def roman_to_decimal(s):
answer = 0
rom_val = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
for x in range(len(s)):
if rom_val[s[x]] > rom_val[[s[x - 1]]:
answer += rom_val[s[x]] - rom_val[s[x - 1]]
else:
answer += rom_val[s[x]]
return answer
print(roman_to_decimal('IV'))
I get the error when assigning the variable answer. I don't see a problem in that
Remove the extra [:
if rom_val[s[x]] > rom_val[[s[x - 1]]:
# ^
In the line rom_val[s[x]] > rom_val[[s[x - 1]], count the number of opening and closing brackets. You will see there is an extra opening bracket in rom_val[[s.
Note: These errors are easy to spot if your IDE/text editor code formatting. Because of the missing closing bracket the next line would be formatted with the wrong indentation and you would easily notice that something was off.

Trying to average a list of numbers using functions [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
First and foremost, I am new to python. As of such, I only know for loops, range, lens, and sum to do this problem. I am having difficulty trying to make a function that can average list of numbers.
This is my code so far:
def ave(L):
L = list(range(len(L))
for a in range(len(L)):
if len(L) == 0: return 0
else: return float((sum(L))/len(L))
So far, I am getting a syntax error on my third line with range(L).
All you need to do is return the sum of L divided by the length of L:
def ave(L):
if not L:
return 0
return sum(L) / len(L)
No range() or float() or for required.
In Python 3, / always produces a floating point number. sum() will do all the looping for you. The only thing you need to take care of, is returning 0 if the list is empty.
Following line is missing a ):
L = list(range(len(L)))
^
Because average of empty list is undefined, you should rather return None instead of '0'.
And instead checking for length, it is better to catch potential error, according to EAFP principle. It makes also more clear what are you doing, as error is self-descriptive.
def ave(L):
try:
return sum(L) / len(L)
except ZeroDivisionError:
return None

Categories

Resources