Problems in create function - python

That's my first question, I'm new at programming, sorry about any inconvinience !
I need to finish an exercise that consists in create a fuction to find the higher number and another function to find the lower number on a List, but when I print the results, it keeps giving me a wrong answer.
Here is my code:
lista_numeros = [1593, 200, 72, 8, 423, 2, 39, 293, 20120]
def menor_numero(arg1):
colector1 = arg1[0]
print(coletor1) # - Checking value added to COLECTOR1
for a in range(len(arg1)):
print(arg1[a]) # - Checking if the A argument is running through the list.
if colector1 < arg1[a]:
colector1 = arg1[a]
return colector1
resultado2 = menor_numero(lista_numeros)
print("menor ", str(resultado2)) # Result is the last position of the list, must be the 6th position.
Thank you very much.

Fist of all indentation is very important in python to tell it the order to execute your code and also to define where code sits within a loop etc.
Now you say you want to make a function that finds the smallest and largest number from the output of another function, for this I will assume this output is a list.
Please see code below with comments.
Mylist = [1, 2, 3, 4, 5, 6, 7, 8, 9] #assume this is output from other funtion
def func(alist): #define function
collector1 = 100 #keeping your collector idea
for i in alist: #iterate through input
if i < collector1: #check if the item you are currently looking at is smaller than the item currently stored in collector
collector1 = i #if is smaller overwitre colletor with new item
print(collector1) #after iterating through all items in input print final value of colletor
func(Mylist) #call function with input
This outputs,
1
Simply change this,
if i > collector1:
And it will now find the largest in input, so output is now.
9
Edit: if you are looking for the smallest number start collector1 at a large number, if you are looking for the largest start collector1 at = 1.

assuming your input is a list and not a string or some sort you can just use the min()/max() methods:
myList = [1,2,3,4,5]
print(max(myList)) >> 5
print(min(myList)) >> 1
you can find more info here :
https://www.tutorialspoint.com/python3/list_max.htm
https://www.tutorialspoint.com/python3/list_min.htm

Your function is finding the maximum instead of the minimum value. Changing the < to > should do what you want.
Python also has builtin methods min() and max() which should do what you want.

#! python3
import random
numbers = []
max = 1000
min = 0
for i in range(40):
numbers.append(random.randint(min,max))
maxNum = min
minNum = max
for num in numbers:
if num > maxNum:
maxNum = num
elif num < minNum:
minNum = num
print(maxNum, minNum)
This is my code, I use the random library in python to generate a random list of numbers, then I set max to equal the maximum number in that list.
The following for loop generates 40 random numbers and appends them to my list.
I then set maxNum to equal zero, so everything will be greater than it, thereby the initial value will not influence the outcome, and then I set minNum to equal max, so every number will be less than it.
The last block of code loops through the numbers list, and compares every number with the current maxNum and minNum variables to see whether that number is greater than the max or less than the min. If it is, the maxNum (or minNum) number will be updated and the code will move on to the next number.
The last statement prints or minimum and maximum values.
I don't know what course you are taking, but I would advise you to familiarize yourself with this code and understand what it is doing, as it's pretty basic and the stuff you encounter in the future will be much harder.

Related

Running multiline test cases

I have the following prompt:
We want you to calculate the sum of squares of given integers, excluding any negatives.
The first line of the input will be an integer N (1 <= N <= 100), indicating the number of test cases to follow.
Each of the test cases will consist of a line with an integer X (0 < X <= 100), followed by another line consisting of X number of space-separated integers Yn (-100 <= Yn <= 100).
For each test case, calculate the sum of squares of the integers, excluding any negatives, and print the calculated sum in the output.
Note: There should be no output until all the input has been received.
Note 2: Do not put blank lines between test cases solutions.
Note 3: Take input from standard input, and output to standard output.
Specific Rules for Python Solution:
Your source code must be a single file, containing at least a main function
Do not use any for loop, while loop, or any list / set / dictionary comprehension
I have written my square_sum function as:
def square_sum(arr):
if not arr:
return 0
value = arr[0]
if value < 0:
value = 0
return value**2 + square_sum(arr[1:])
square_sum([9, 6, -53, 32, 16])
However, I cannot figure out how to run the multiline test cases on my function and display the result in the aforementioned format. Interestingly, there can be any number of test cases so how do I add the capability to accommodate them? I would like some guidance in this part, thank you.
Assuming that this assignment is to see how to replace all iteration with recursion, and withholding all judgement on the wisdom of doing so, here is a sample solution.
You have already implemented the inner loop. My suggestion would be to add the parsing to that loop, since otherwise you have to either use map or replace it with another recursion.
def square_sum(lst):
if not lst:
return 0
value = int(lst[0])
if value < 0:
value = 0
return value**2 + square_sum(lst[1:])
The outer loop will need to read two lines: the first (discarded) line will contain the number of elements. The second line will contain the strings that you will pass to square_sum. To control the depth of your recursion, use the first line of the input, which tells you how many samples there will be:
def run(n):
count = int(input())
print(square_sum(input().split()))
if n > 1:
run(n - 1)
def main()
n = int(input())
run(n)
Your question asks for a main function. If you need to run it in your module, go ahead and do that:
main()

Python Find the mean school assignment - What is a loop?

I have been working on this assignment for about 2 weeks and have nothing done. I am a starter at coding and my teacher is really not helping me with it. She redirects me to her videos that I have to learn from every time and will not directly tell or help me on how I can do it. Here are the instructions to the assignment (said in a video, but made it into text.
Find the mean
Create a program that finds the mean of a list of numbers.
Iterate through it, and instead of printing each item, you want to add them together.
Create a new variable inside of that, that takes the grand total when you add things together,
And then you have to divide it by the length of your array, for python/java script you’ll need to use the method that lets you know the length of your list.
Bonus point for kids who can find the median, to do that you need to sort your list and then you need to remove items from the right and the left until you only have one left
All you’re doing is you need to create a variable that is your list
Create another variable that is a empty one at the moment and be a number
Iterate through your list and add each of the numbers to the variable you created
Then divide the number by the number of items that you had in the list.
Here's what I've done so far.
num = [1, 2, 3, 4, 5, 6];
total = 0;
total = (num[0] + total)
total = (num[1] + total)
total = (num[2] + total)
total = (num[3] + total)
total = (num[4] + total)
total = (num[5] + total)
print(total)
However, she tells me I need to shorten down the total = (num[_] + total) parts into a loop. Here is how she is telling me to do a loop in one of her videos.
for x in ____: print(x)
or
for x in range(len(___)): print (x+1, ____[x])
there is also
while i < len(___):
print(___[i])
i = i + 1
I really don't understand how to do this so explain it like I'm a total noob.
First of all, loops in python are of two types.
while: a while loop executes the code in a body until a condition is true. For example:
i = 0
while(i < 5):
i = i + 1
executes i = i + 1 until i < 5 is true, meaning that when i will be equal to 5 the loop will terminate because its condition becomes false.
for: a for loop in python iterates over the items of any sequence, from the first to the last, and execute its body at each iteration.
Note: in both cases, by loop body I mean the indented code, in the example above the body is i = i + 5.
Iterating over a list. You can iterate over a list:
Using an index
As each position of the array is indexed with a positive number from 0 to the length of the array minus 1, you can access the positions of the array with an incremental index. So, for example:
i = 0
while i < len(arr):
print(arr[i])
i = i + 1
will access arr[0] in the first iteration, arr[1] in the second iteration and so on, up to arr[len(arr)-1] in the last iteration. Then, when i is further incremented, i = len(arr) and so the condition in the while loop (i < arr[i]) becomes false. So the loop is broken.
Using an iterator
I won't go in the details of how an iterator works under the surface since it may be too much to absorb for a beginner. However, what matters to you is the following. In Python you can use an iterator to write the condition of a for loop, as your teacher showed you in the example:
for x in arr:
print(x)
An iterator is intuitively an object that iterates over something that has the characteristic of being "iterable". Lists are not the only iterable elements in python, however they are probably the most important to know. Using an iterator on a list allows you to access in order all the elements of the list. The value of the element of the list is stored in the variable x at each iteration. Therefore:
iter 1: x = arr[0]
iter 2: x = arr[1]
...
iter len(arr)-1: x = arr[len(arr)-1]
Once all the elements of the list are accessed, the loop terminates.
Note: in python, the function range(n) creates an "iterable" from 0 to n-1, so the for loop
for i in range(len(arr)):
print(arr[i])
uses an iterator to create the sequence of values stored in i and then i is in turn used on the array arr to access its elements positionally.
Summing the elements. If you understand what I explained to you, it should be straightforward to write a loop to sum all the elements of a list. You initialize a variable sum=0 before the loop. Then, you add the element accessed as we saw above at each iteration to the variable sum. It will be something like:
sum = 0
for x in arr:
sum = sum + x
I will let you write an equivalent code with the other two methods I showed you and do the other points of the assignment by yourself. I am sure that once you'll understand how it works you'll be fine. I hope to have answered your question.
She wants you to loop through the list.
Python is really nice makes this easier than other languages.
I have an example below that is close to what you need but I do not want to do your homework for you.
listName = [4,8,4,7,84]
for currentListValue in listName:
#Do your calculating here...
#Example: tempVar = tempVar + (currentListValue * 2)
as mentioned in the comments w3schools is a good reference for python.

How is this for statement true?

number = [1,2,3,4,63,2]
max = number[0]
for large in number:
if large > max:
max = large
print(max)
This Python code prints the largest number in a list and it works, but I am not sure how it works. On the 5th line when max = large I am not quite sure that this if statement is true in the first place because the first item in the list is not bigger than max but it is equal to it.
number = [1,2,3,4,63,2]
max = number[0]
for large in number:
if large > max:
max = large
print(max)
Explanation:
First iteration: max=1 and large=1 so if 1>1 then max=large else the max will the previous number as we assigned 1 initially.
2nd iteration: max will have 2.
.
.
.
4nd iteration: max will have 4.
5nd iteration: max will have 63.
6th iteration: max will have still 63 since 2 is not > 63.
I think I understood your confusion. The statement for large in number: assigns each element of number to large successively no matter what happens in the loop. Python for loops do not have a condition, unlike C-like for loops.
The statement if large > max: is not the condition for the loop to continue. It is totally independent of the loop statement. As you observed correctly, it is False for the first iteration, but that has no effect on what the for loop is doing. Only the value of max is not updated.
It's conventional not to use names like max that shadow built-in names. Something like max_ or max_value is better.
I am not quite sure that this if statement is true in the first place because the first item in the list is not bigger than max but it is equal to it.
Your current loop works perfectly fine and in fact omits useless reassignment of the max variable.
number = [1,2,3,4,63,2]
max = number[0]
for large in number: # For every item in the list of numbers
if large > max: # if a currently selected item is larger than the current maximum
max = large # assign that value of that item to be the new maximum
print(max)
For the first iteration you will get a False. For the given list all other iterations will yield a True. However if you add items that are equal like
[ 1, 1, 2, 3, 4, 4, 4, 4, 5 ]
you will soon discover that the current check you have is quite efficient. Why? Because if you add equality to the check (in which case your IF condition will return more times True including the first iteration)
if large >= max:
max = large
you will end up with pointless reassignment of max every time you get to a value that is equal to the current maximum. So for the list I've given above as an example you will go through 4 reassignments that are completely useless - one for the second 1 and three for the three 4 after the first 4 (marked with * below):
[ 1, 1, 2, 3, 4, 4, 4, 4, 5 ]
| | | |
* * * *
There is one thing I would add to solution and that is omitting the first item:
for large in number[1:]:
...
For your comparison of numbers you will not see much of a difference but if you compare larger objects it will.

How can I improve my code to avoid memory based error?

I wrote a python function largestProduct(n) which returns the largest number made from product of two n-digit numbers. The code runs fine for n untill 3, but shows memory error for n>3. Is there a way I can improve my code to avoid this error?
def largestProduct(n):
number_lst = []
prod_lst = []
count = 0
for i in range(10**(n-1),(10**n)):
number_lst.append(i)
while count!= len(number_lst):
for i in range(len(number_lst)):
prod_lst.append(number_lst[count]*number_lst[i])
count +=1
prod_set = list(set(prod_lst))
return max(prod_lst)
Well, you don't need any storage to loop through what you need:
def largestProduct(n):
range_low = 10**(n-1)
range_high = 10**n
largest = 0
# replace xrange with range for Python 3.x
for i in xrange(range_low, range_high):
for j in xrange(range_low, range_high):
largest = max(largest, i*j)
return largest
But why would you want to do this? The largest product of two n-long numbers is always the largest number you can write with n digits squared, i.e.:
def largestProduct(n):
return (10**n-1)**2
You should consider creating a generator function. In the end you can iterate over the output of your function which only processes each element one by one instead of holding the whole list in memory.
see https://wiki.python.org/moin/Generators

Unsorted numeric list creates improper output in histogram calculation

I am making a function which will make a list which includes a histogram of a requested list and requested values to use as the values of the histogram. Values above the requested value are included last.
The program is working with a list that is sorted in ascending order numerically, but when a list that is not sorted is used as input, the program seems to discard random values and not evaluate in the same way.
the code:
def histogram(sample, binBoundaries):
c=0
if not binBoundaries:
li = [len(sample)]
return print(li)
for x in sample:
if x > binBoundaries[-1]: #if the value is greater than last bin
c = c+1 #number of values greater increases
for eachbin in binBoundaries: #for each bin
dic[eachbin] = 0 #initial value = 0 to account for no number
for x in sample: #for each value wanted to calculate for
if x <= eachbin: #if the number falls into the bin
dic[eachbin] += 1 #the number of values in the bin increases
sample.remove(x)
for i in dic:
listofvalues.append(dic[i])
listofvalues.append(c)
print(listofvalues)
histogram([5, 4, 2, 3], [3])
this will result in an output of [1, 2], where the real output should be [2,2]
Is there something I'm just not seeing that is making the number not be calculated? Let me know where I have gone wrong if you could!
Your problem is that you are removing items from the list sample while you are iterating over it, this is a bad idea because it will result in skipping some elements.
Try taking out the line sample.remove(x), you should get the expected result. If you really do need to remove elements from the input list you should refactor to make sure you still check every element in the list. One option is to iterate over the list in reverse using for x in reversed(sample).
It also looks like you may be removing elements in the wrong place, sample.remove(x) looks like it should be inside of the if directly above it. Try the following code:
...
for eachbin in binBoundaries: #for each bin
dic[eachbin] = 0 #initial value = 0 to account for no number
for x in reversed(sample): #for each value wanted to calculate for
if x <= eachbin: #if the number falls into the bin
dic[eachbin] += 1 #the number of values in the bin increases
sample.remove(x)
...

Categories