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]
Related
This is a recursive function that attempts to return how many times an item appears in a list. Following is the code:
def count (item, l_ist2): # function that returns the number of times item appears in l_ist
# Base case: item appears 0 times
print (item in l_ist2)
if item in l_ist2 == False:
return 0
# Recursive case
elif item in l_ist2 == True:
l_ist2.remove(item)
print (l_ist2, "\n")
return count (item, l_ist2) + 1
list_for_task_2 = [5,56,2,57,2,46,5,345,5,56,2,56,56,345]
item = int (input ("Choose an item in the list [5,56,2,57,2,46,5,345,5,56,2,56,56,345]: "))
print ("The item", item, "appears", count(item,list_for_task_2), "time(s) in the list above.\n")
Somehow, the output is always: "The item 5 appears None time(s) in the list above."
Thanks in advance to anyone who can help me answer this question!
P.S. This assignment of mine specifically ask for the code to be written recursively.
There is one case in your recursive function that silently returns None; this is what is creating the issue.
Further, your recursion uses python in that scans the entire sequence each time the function is called... this is probably not what you intended to do.
I replaced this with a mechanism that pops an element from the sequence and compares it to the item to be counted. This implies that the recursive case is now whether or not the sequence is empty or not.
def count (item, seq):
"""returns the number of times item appears in seq
"""
if not seq: # is the sequence empty or not
return 0
elif seq.pop() == item: # if not, pop an element and compares it to the item
return count(item, seq) + 1 # add 1 if found
else:
return count(item, seq) # do not add 1 if not found
list_for_task_2 = [5, 56, 2, 57, 2, 46, 5, 345, 5, 56, 2, 56, 56, 345]
item = int(input ("Choose an item in the list [5, 56, 2, 57, 2, 46, 5, 345, 5, 56, 2, 56, 56, 345]: "))
print("The item", item, "appears", count(item,list_for_task_2), "time(s) in the list above.\n")
I have a query relating to return only the last results, so here is my code:
import random
def Step_1():
Start_Game = raw_input("Enter \'Start' to continue \n")
if Start_Game == 'start':
print "Let the Lottery begin"
else:
return Step_1()
#-------------------------------------------------------------------
def Step_2():
random_list = []
for i in range(10):
while len(random_list) < 6:
random_number = random.randint(1,59)
while random_number not in random_list:
random_list.append(random_number)
print random_list
Step_1()
Step_2()
When i run this it gives me the below result,
Enter 'Start' to continue
start
Let the Lottery begin
[56]
[56, 20]
[56, 20, 32]
[56, 20, 32, 2]
[56, 20, 32, 2, 23]
[56, 20, 32, 2, 23, 30]
However how can i just display the last result generated and discard the previous 5. I know i need to change the last bit "print" within my Step_2 function, but what do I need to add?
Thanks .
A one liner:
random.sample(range(1, 59), 6) # genrates 6 unique random no's in the range
OR to modify existing code, use a list to store previously generated random no's
def Step_2():
random_list=[]
for i in range(6):
random_number = random.randint(1,59)
while random_number in random_list:
random_number = random.randint(1,59)
print random_number
list.append(random_number )
For your step2() function you will probably want to use a while loop, since you do not really know, how many random numbers you need to generate until you have 6 unique numbers.
def step2():
# Declare an empty list to hold the random numbers
numbers = []
# While we do not have 6 numbers in our list
while len(numbers) < 6:
# Generate a random number
rndnum = random.randint(1,59)
# If that random number is not yet in our list
if rndnum not in numbers:
# Append it to the list
numbers.append(rndnum)
return numbers
Here is my original function.
def f(n):
if n<0:
print("Error.Bad input")
elif n==0:
return 1
elif n==1:
return 1
else:
return f(n-1)+f(n-2)
Is it possible to modify Fibonacci Python function so that not only does it have to calculate f(n) but also it prints f(0), f(1), f(2),....,f(n) in the function?
Instead of using a recursive function you could do this:
def f(n):
if n < 0:
print("Error.Bad input")
elif n <= 1:
return 1
else:
result = [1, 2]
print(1)
print(2)
for i in range(n - 2):
result = [result[1], result[0] + result[1]]
print(result[1])
return result[1]
def fib(n):
pred, curr = 0, 1
k = 1
while (k<n):
pred, curr = curr, curr + pred
print(curr)
k = k + 1
Probably the optimal "pythonic" way to create a sequence (a list) of fibonacci numbers of arbitraly size n is to define a function which does so, than to call that function with size as an input argument. For example:
def fibonacci_sequence(n):
x = [0, 1]
[x.append(x[-1] + x[-2]) for i in range(n - len(x))]
return x
fibonacci_sequence(15)
The result is:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
Bottom-up approach. Complexity is O(n):
def fib(n):
if n in (1, 2):
return 1
i = z = 1
for _ in range(3, n+1):
z, i = i + z, z
return z
I need to complete this code for school.
The program should find an index of sequence split in the list.
For example for input which is a list like this
[66, 81, 83, 96, 13, 19, 30, 41, 44, 57]
the correct output should be 4 (index of number where the sequence is interrupted - 96)
My function is able to find the split but I don't know how to return an index of that split. It always return incorrect answer.
Here is my code:
def findSplit( list ):
if len(list)%2 == 0:
if list[(len(list)//2)-1] == list[0]:
return 1
elif list[(len(list)//2)-1]<list[0]:
return findSplit(list[:(len(list)//2)]) - len(list)//2
elif list[(len(list)//2)-1]>list[0]:
return findSplit(list[(len(list)//2)-1:]) + len(list)//2
elif len(list)%2 != 0:
if list[(len(list)//2)]<list[0]:
return findSplit(list[:(len(list)//2)+1]) - len(list)//2
elif list[(len(list)//2)]>list[0]:
return findSplit(list[(len(list)//2):]) + len(list)//2
if __name__ == "__main__":
list = [ 66, 81, 83, 96, 13, 19, 30, 41, 44, 57 ]
line = input().strip().split()
if line != []:
list = []
for x in line:
list.append( int( x ) )
print(findSplit( list ))
First and most importantly don't name any of your variables list as they overwrite the builtin function. I have changed the name to lst in my code below.
Your code is fine except for a small mistake, when ever you find out that the split is the first half, you need not subtract the length of the other half.
return findSplit(lst[:(len(list)//2)+1]) # THIS MUCH IS ENOUGH!
This is because you are returning the index in the first half, hence the indices start from this half itself. If you subtract you are going into the negative. In your particular case, you are subtracting 4 (the correct value) with 5 (the length of the other split) and hence you are getting the wrong answer -1 which is 4-5.
The edited code can be written as
def findSplit( lst ):
if len(lst)%2 == 0:
if lst[(len(lst)//2)-1] == lst[0]:
return 1
elif lst[(len(lst)//2)-1]<lst[0]:
return findSplit(lst[:(len(lst)//2)])
elif lst[(len(lst)//2)-1]>lst[0]:
return findSplit(lst[(len(lst)//2)-1:]) + len(lst)//2
elif len(lst)%2 != 0:
if lst[(len(lst)//2)]<lst[0]:
return findSplit(lst[:(len(lst)//2)+1])
elif lst[(len(lst)//2)]>lst[0]:
return findSplit(lst[(len(lst)//2):]) + len(lst)//2
Now when we print the output we get the correct value.
>>> findSplit([ 66, 81, 83, 96, 13, 19, 30, 41, 44, 57 ])
4
I don't understand the second part of your code though ;)
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