This function is supposed to take an integer, generate the list of triangular numbers within range of that integer, check that list for the longest list of numbers whose sum == number and return them in a list, otherwise if there is no such list within that range of triangular numbers, return an empty list. I thought I had it somewhat, and it runs on python tutor.com, but when I run it in IDLE, nothing happens.
def checkio(number):
x = 4
lst = [1, 3, 6]
new = []
if number == 0:
return []
elif number == 1:
return [1]
elif number == 3:
return []
elif number == 6:
return []
elif number == 4:
return [1, 3]
elif number == 7:
return [1, 6]
elif number == 10:
return [1, 3, 6]
elif number > 10:
while number > lst[-1]: # Generates a list of all the triangular numbers up to number
for item in range(lst[-1]):
lst.append(x + lst[-1])
x += 1
go = []
start = 0
end = 0
count = 0
while count < len(lst) * 2:
if sum(lst[start:end+1]) < number:
end += 1
count += 1
elif sum(lst[start:end+1]) > number:
start += 1
count += 1
elif sum(lst[start:end+1]) == number:
go.append(lst[start:end+1])
break
return go
if count >= len(lst) * 2:
return []
In the code you post you are just declaring a function. In order to run it, you have to make a call to that function. In your case, it receives one argument, so you have to pass it inside the parentheses ():
number = 5 # for example
checkio(number) # this is the function call
As Bakuriu commented: If you want to get a result change the order of this lines:
elif sum(lst[start:end+1]) == number:
go.append(lst[start:end+1])
break
return go
To :
elif sum(lst[start:end+1]) == number:
go.append(lst[start:end+1])
return go
break
This will return a value before escaping the while loop. As noted in the comments (thanks Andrea Corbellini) you can also remove the break statement and it will work well. Because after the return statement by definition escapes the function.
Also to run in idle once defined (you copied the code and pressed return), call it as Christian says.
This way you will check if works.
Note that you don't check in the ifelse clauses for the numbers 2, 5, 8 and 9. If you call this function with checkio(5), like suggested by Crhistian, it will not return anything because it doesn't have anything to return!
Related
I'm trying to see if the Collatz Conjecture is really true, it says that every integer number which is divided per 2 if it's even and multiplied by 3 and added 1 if it's odd, will eventually come to a loop of 4, 2, 1. But it gets stuck in a while loop and doesn't break or gets inside the if statement that I want
integers = [5]
#Returns true if a number is even and false if it's odd
def even(num):
if (num % 2 == 0):
return True
else:
return False
#Returns true if a list of a number is in a loop
def loop(numbers):
for x in numbers:
if (numbers.count(x) > 1 or 4 in x == True):
return True
break
else:
return False
continue
#Print a list of numbers that agree with the Collatz conjecture
def collatz(list):
for x in list:
collatz_nums = []
l = loop(collatz_nums)
list.append(list[-1] + 1)
#Add the first number to the "collatz_nums" list
if (even(x) == True):
collatz_nums.append(x / 2)
elif (even(x) == False):
collatz_nums.append(x * 3 + 1)
#Adds numbers to the collatz_nums variable
while (l != True):
print("Start")
if (l == False):
if (even(collatz_nums[-1]) == True):
collatz_nums.append(collatz_nums[-1] / 2)
print("/2")
else:
collatz_nums.append(collatz_nums[-1] * 3 + 1)
print("*3+1")
else:
print("Exit")
break
print(F'{x} = {collatz_nums}')
collatz(integers)
Let's start here
collatz_nums = []
l = loop(collatz_nums)
You're passing an empty list to a function with only return statements in the event that you have data to loop over, so the function returns, setting l = None
Now while (None!=True) is an infinite loop since you're never modifiying value of l
Perhaps you should move the "add first number" if statements (which really only need to call even function once using if-else) above those two lines? Or above for x in list so that you only add the first number once?
I'd also recommend removing 4 in x == True since I doubt that does what you want
I am writing a program that will print a list of numbers 1:n. However, every number divisible by 2 should be replaced with 'x' and every number divisible by 3 should be replaced with 'y'. Lastly, every number both divisible by 2 and 3 should be replaced with 'xy'. This is my code so far, I can get the function to print the correct result with my input. But it wont print the entire list of numbers. Instead I am just getting the end result (x,y, or xy) for the given input. Here is my code thus far with the output.
def replace(n):
for i in range(n):
print(i)
if n%2== 0 and n%3 == 0:
return 'xy'
elif n%2==0:
return 'y'
elif n%3 == 0:
return 'x'
else:
print(i)
replace(12)
This is my output:
0
'xy'
I would like the output to be something like:
1
x
y
x
5
xy
7
x
y
x
11
xy
Any advice would be appreciated, you guys rock!
Your code has multiple errors:
At line 4, you print(i) - this means that each number will be printed
At lines 6, 9 and 12 you are using the n variable instead of i in the modulo operation
You want to check for numbers [1, n], but your loop checks for [0, 11]
You return instead of printing - the return keyword will stop the function's execution (and thus the loop) and return the value you specified. In case you are confused, consider the following example:
def get_number():
return 5
print("This will never print, as the function has already returned")
number = get_number() # number now equals 5, since it was returned
get_number() # 5 still gets returned, but is never assigned to a variable
Here is the code that gives the output that you mention above:
def replace(n):
for i in range(1, n + 1):
if i%2 == 0 and i%3 == 0:
print('xy')
elif i%2 == 0:
print('x')
elif i%3 == 0:
print('y')
else:
print(i)
replace(12)
So I have been having this issue with a simple python script I'm working on for an assignment. I am to make a small script simulating a lottery, and have written this code:
import random
def drawNumbers(nlist, n):
drawnlist = []
i = 0
while i < n:
if i == 0:
drawnlist.append(nlist[random.randint(0,33)])
i+=1
else:
r = random.randint(0,33)
dup = False
for x in drawnlist:
if x == r:
dup = True
if dup == False:
drawnlist.append(nlist[r])
i+=1
return drawnlist
def compList(drawlist, guesslist):
count = 0
for j in drawlist:
for h in guesslist:
if j == h:
count +=1
return count
def winnings(right, altright):
altcorrect = False
if altright > 0:
altcorrect = True
if right == 7:
return 2749455
elif right == 6:
if altcorrect:
return 102110
else:
return 3385
elif right == 5:
return 95
elif right == 4:
if altcorrect:
return 45
else:
return 0
a=0
tot = 0
while a <100:
numbers = []
i = 1
while i <= 34:
numbers.append(i)
i+=1
myGuess = []
i = 0
while i <7:
if i == 0:
myGuess.append(random.randint(1,34))
i+=1
else:
r = random.randint(1,34)
dup = False
for x in myGuess:
if x == r:
dup = True
if dup == False:
myGuess.append(r)
i+=1
tot += winnings(compList(drawNumbers(numbers,7),myGuess),compList(drawNumbers(numbers,3),myGuess))
a+=1
print(tot)
And it seems to be working fine for one iteration, however, when I increase a like now with a value of 100, I get an error saying that I cannot sum an "int" object and a "None" objects. When I tinkered with the code and printed "winnings" instead of the summed total for each iteration, it looks like the function sometimes returns "None" instead of a number. I can however not seem to recreate that with a smaller amount of iterations, so my question: Is this code related, or might it be that by calling the functions "too fast" it does not create a number? I know this question might seem odd, but I am new to programming as a whole and python itself, and I have no clue how to debug this.
The winnings function can return None as there is no else to the inner if. In this case, it does not trigger the final else and returns None by default. To fix it, add an else to the if, or just remove the final else in winnings:
def winnings(right, altright):
altcorrect = False
# ...
elif right == 4:
if altcorrect:
return 45
# maybe add an else here?
# or if you get to this point, _always_ return 0
return 0
Your winnings function sometimes returns None. It's because it's not catching some cases. Python returns None if it reaches the end of a function without any other returns being hit.
Specifically, if right is 4 and altright is 0, none of the if cases will get caught and the function returns None.
I need to define a recursive function that receives a list of
non-negative integers numbers, and a positive integer m, and returns the largest number from the list that divides by m with no remainder.
I can't use loops or python's max function on a list.
I tried:
def find_max_mod(numbers, m):
mx = 1
mxn = -1
if len(numbers) == 1 and numbers[0] % m == 0:
if mx > numbers[0]:
mx = numbers[0]
return mx
if len(numbers) == 1 and numbers[0] % m != 0:
return -1
elif len(numbers) == 0:
return -1
elif numbers[-1] % m == 0 and numbers[-1] > mx:
mx = numbers[-1]
numbers = find_max_modulo(numbers[:-1], m)
return mx
I can't figure how to save my largest number. Every recursive cycle it over-write on my mx number.
I think I have a problem with the base condition but it is the smallest problem.
You're close, you just need to modify the return statements
elif numbers[-1] % m == 0 and numbers[-1] > mx:
mx = numbers[-1]
numbers = find_max_modulo(numbers[:-1], m)
return mx
to:
elif numbers[-1] % m == 0 and numbers[-1] > mx:
return numbers[-1]
return find_max_modulo(numbers[:-1], m)
This works:
def find_max_mod(list_numbers, large_number, current_max_valid=0):
if list_numbers[0] % large_number == 0:
if current_max_valid < list_numbers[0]:
current_max_valid = list_numbers[0]
if len(list_numbers) > 1:
return find_max_mod(list_numbers[1:], large_number, current_max_valid)
return current_max_valid
list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
print(find_max_mod(list_numbers, 5))
If you want to work on recursion, you should try to find exercises that fits your theme. For instance, Fibonnacci function for recursion is a good start.
Now as for your question, usually, for a recursive function, you need an if-statement that will stop your program from iterating. That condition may be a variable that will need to be passed thoughout the process as a parameter, or it might be a hard-coded condition to-be-met.
As you need to go through all the list, you need to think about a stop condition in the end of your list. You have multiple choices but I suggest you pop an item at each iteration : item that will be checked if it respects your requirements.
Now, you want to keep the largest number ?
You simply need to check if the item you received from further computations is a better fit than the one you have in your current recursive session : so that you can keep the one that best fits your needs.
Good luck. :)
I am new to python and we were given an assignment to create a linear search program that does not use "in" or index. The program compiles but says that every number I input is not in the list. I also have to do the same thing for a binary search but I'm doing things one at a time ha. Any help is appreciated!
PS: How could I show what index it is in without using the "index" function?
def linearSearch(intList,target):
found = False
position = 0
while position < len(intList) and not found:
if intList[position] == target:
found = True
position = position + 1
return found
linearList = [3,5,9,7,6,12,15,9,1]
numInput = input("What number are you looking for? ")
numFound = linearSearch(linearList, numInput)
if numFound:
print("The number is in index: ")
else:
print("The number is not in the list")
1) Start position = -1
2) return position
3) You want to position+=1 before if intList[position] == target: and you want to break when you do find the element. You then don't need found
Something is found when linearSearch(linearList, numInput) > 0
Then, your code just doesn't work because the list contains ints whereas input will always return a string. You must use int(input(".."))
This method uses list comprehension, and it will account for any duplicates in the list as well. It assigns a list of index/indices where the key occurs in the list. Read more about list comprehension here.
l = [1, 2, 3, 4, 4, 6]
el = 4
search = [i for i in range(len(l)) if el==l[i]]
print(search)
output:
[3, 4]
alternatively,
def LinSearch(target, intList):
search = [i for i in range(len(intList)) if target==intList[i]]
return search
def linearSearch(intList,target):
#print (target)
found = False
position = 0
while position < len(intList):
#print(intList[position])
if intList[position] == target:
found = True
break
position = position + 1
return found
linearList = [3,5,9,7,6,12,15,9,1]
numInput = int(input("What number are you looking for? "))
numFound = linearSearch(linearList,numInput)
if numFound:
print("The number is in index: ")
else:
print("The number is not in the list")
Please take care of type conversion...
Linear Search :
// funtion which rturns true if item found inside list.
def linearSearch(list, value):
for i in range(len(list)):
if i == value:
return True
// Call above function pass list of values and item to search
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
item = 10
print(linearSearch(list, item)) // item to search
def target(list,num):
for x in list:
if x == str(num):
print("match found:"+x)
break
else:
print('no match found')
list1 = ['6','4','7','9','0','2','3','1']
inp = input('Enter number to search:')
target(list1,inp)
def linear_search(list, key):
for i, item in enumerate(list):
if item == key:
return i
return -1
print(linear_search([4,5,2,7,1,8],7))
#If key is in the list returns its position in the list, otherwise returns -1.
n=int(input("Enter the number:"))
list,n=[10,11,12,13,14,15],n
if n in list:
print("Element found at",list.index(n))
else:
print("Not Found")
Advice: In python index starts from 0. To start from 1 format the code like this: list.index(n)+1
def linearSearch(array,k):
flag = False
position = 0
while position < len(intList) and not flag:
if array[position] == k:
flag = True
else:
position += 1
return position
array = [3,5,9,7,6,12,15,9,1]
numInput = int(input("What number are you looking for? "))
numFound = linearSearch(linearList,numInput)
if numFound:
print("The number is in index: ")
else:
print("The number is not in the list")