Errors trying to append specific number of floats from user input - python

x={}
continueQ=input("would you like to continue?"))
if (continueQ=="yes"):
#if there is less than 4
if x<4:
variable=float(input("Input a float to append to the array:")
x.append(variable)
print(x)
else:
print(x)
else:
print("Goodbye!")
There are a few errors in this code, could someone help me how to create an if statement to check if there are minimum than 4 values inside an array .
Also how to append to an array from an input.

Create a list with x = [], Use len(x) to get the length of list, use while loop with condition if x<4
x=[]
continueQ=input("would you like to continue?")
if (continueQ=="yes"):
#if there is less than 4
while len(x)<4:
variable=float(input("Input a float to append to the array:"))
x.append(variable)
print(x)
else:
print(x)
else:
print("Goodbye!")

The first thing you'll want to do is change that x={} to an x=[]. What you've done is create a dictionary rather than an array, and consequently will run into an assortment of issues as you're dealing with the wrong data structure.
Once you've done that, we can move on to how to check if there are less than 4 values inside an array. In Python, arrays carry a length attribute, which can be accessed by writing len(arrayName), or in your case, len(x). For example, if your array x contained the following values: [1,2,3], then len(x) would return 3, seems simple enough.
Now to check that the length is less than 4, you need to replace your if x<4: with if len(x)<4:.
You already have the correct code to append to your array, it likely wasn't working before because you created a dictionary instead of an array.

There are several errors in your code. Here's a working version:
x = []
continueQ = input('Would you like to continue?')
if continueQ.lower() == 'yes':
while len(x) < 4:
variable=float(input('Input a float to append to the array:'))
x.append(variable)
print(x)
print("Goodbye!")
Explanation
[] represents an empty list, while {} is use for an empty set.
Make sure your bracketing is consistent; all open brackets must be closed.
Use len(x) to find the number of entries in a list x.
Use a while loop to repeat logic until a criterion is satisfied.

Related

can't quite figure out what's not working (checkio excersise "Even the Last")

You are given an array of integers. You should find the sum of the integers with even indexes (0th, 2nd, 4th...). Then multiply this summed number and the final element of the array together. Don't forget that the first element has an index of 0.
For an empty array, the result will always be 0 (zero).
Input: A list of integers.
Output: The number as an integer.
Precondition: 0 ≤ len(array) ≤ 20
all(isinstance(x, int) for x in array)
all(-100 < x < 100 for x in array
result = 0
if array:
for element in array:
i = array.index(element)
if i%2 == 0:
result += element
else:
pass
else:
return 0
return result
Last_digit = array[-1]
final_result = result*Last_digit
return final_result
print(final_result)```
I've figured out the problem, that you've shared the array you're having problem with. Since you have this array :
[-37,-36,-19,-99,29,20,3,-7,-64,84,36,62,26,-76,55,-24,84,49,-65,41]
If you notice here, 84 appears twice, first at index 9 and then 16. The method you're using to get index of elements, .index returns the index of the first instance the element is found in the list.Therefore for the value of 84, the index is taken as 9 and not 16 which is an odd value, this does not add 84 to your sum. You should rather use enumerate for your code:
for idx, element in enumerate(array):
if idx %2 == 0:
result += element
First, I recommend reading the stackexchange guides on posting a well-formed question. You need to state what your goal is, what you've tried, what errors get thrown, and what the output should look like -- along with code examples and a minimal reproducible example as needed.
However, I'll help you out anyway.
You have a dangling return at line 11:
else:
return 0
return result
This makes no sense, as you've already returned 0. This is also apparently a snippet from a function, no? Post the whole function. But based on the instructions, you could try this:
import random
array = random.sample(range(-100, 100), 20)
def etl_func(arr):
arrsum = 0
for i, val in enumerate(arr):
if i%2 == 0: arrsum += val
return (arrsum * arr[-1])
answer = etl_func(array)
print(answer)
Note that importing random and using array = random.sample(range(-100, 100), 20) are not necessary if you're already GIVEN an array to work with. They're included here just as an example.
Also note that it's unnecessary to use an else: pass. If the condition evaluates to true (i.e. i%2 == 0), the if block will be executed. If i%2 != 0, the loop will short circuit automatically and move to the next iteration. Adding else: pass is like telling someone sitting in your chair to sit in your chair. You're telling the program to do what it's already going to do anyway. There's nothing necessarily wrong with including the else: pass, if it really want to... but it's just adding lines of meaningless code, which nobody wants to deal with.
EDIT: I don't know whether you were supposed to write a function or just some code (back to the "ask a well-formed question" issue...), so I went with a function. It should be trivial to turn the function into just plain code -- but you want to get into the habit of writing good functions for reusability and modularity. Makes everything run more smoothly and elegantly, and makes troubleshooting much easier.
This function also works for the array mentioned in the comments to your original post.
In addition, if you need a direct replacement for your code (rather than a function... I'm not familiar with checkio or how your answers are supposed to be formatted), and you already have the array of integers stored in the variable array, try this:
arrsum = 0
for i, val in enumerate(array):
if i%2 == 0: arrsum += val
print(arrsum * array[-1])
Since your question didn't say anything about using or defining functions, return statements shouldn't appear anywhere. There's nothing to return unless you're writing a function.

NameError on Python 3.7/ List assignment index Error

Before Anything this is my first time asking a question here so if there's Something wrong with the format of the question I'm sorry about that.
So basically This is a code that is supposed to get a list of numbers, and a number from user and check to see if the second input is equal to any of the elements of the list, then put those element index numbers in a new list and print it.
The thing is the error is saying 'a' is not defined but if I define it before the for loop like this:
a=[]
or
a=list()
I get this:
a[k]= c
IndexError: list assignment index out of range
Here's the code:
x = eval(input('list'))
y = eval(input('number'))
k=0
c=0
for i in x:
if y==i:
a[k]= c
k+=1
c+=1
print(a)
A list in python doesn't support index assignment. - Therefore the indices will always be numeric depending on the position 0, 1, n.
To add use append, to have a hash map use a dict.
Instead of
a[k]= c
You can use
a.append(c)

sub-sum from a list without loops

So i'm studying recursion and have to write some codes using no loops
For a part of my code I want to check if I can sum up a subset of a list to a specific number, and if so return the indexes of those numbers on the list.
For example, if the list is [5,40,20,20,20] and i send it with the number 60, i want my output to be [1,2] since 40+20=60.
In case I can't get to the number, the output should be an empty list.
I started with
def find_sum(num,lst,i,sub_lst_sum,index_lst):
if num == sub_lst_sum:
return index_lst
if i == len(sum): ## finished going over the list without getting to the sum
return []
if sub_lst_sum+lst[i] > num:
return find_sum(num,lst,i+1,sub_lst_sum,index_lst)
return ?..
index_lst = find_sum(60,[5,40,20,20,20],0,0,[])
num is the number i want to sum up to,
lst is the list of numbers
the last return should go over both the option that I count the current number in the list and not counting it.. (otherwise in the example it will take the five and there will be no solution).
I'm not sure how to do this..
Here's a hint. Perhaps the simplest way to go about it is to consider the following inductive reasoning to guide your recursion.
If
index_list = find_sum(num,lst,i+1)
Then
index_list = find_sum(num,lst,i)
That is, if a list of indices can be use to construct a sum num using elements from position i+1 onwards, then it is also a solution when using elements from position i onwards. That much should be clear. The second piece of inductive reasoning is,
If
index_list = find_sum(num-lst[i],lst,i+1)
Then
[i]+index_list = find_sum(num,lst,i)
That is, if a list of indices can be used to return a sum num-lst[i] using elements from position i+1 onwards, then you can use it to build a list of indices whose respective elements sum is num by appending i.
These two bits of inductive reasoning can be translated into two recursive calls to solve the problem. Also the first one I wrote should be used for the second recursive call and not the first (question: why?).
Also you might want to rethink using empty list for the base case where there is no solution. That can work, but your returning as a solution a list that is not a solution. In python I think None would be a the standard idiomatic choice (but you might want to double check that with someone more well-versed in python than me).
Fill in the blanks
def find_sum(num,lst,i):
if num == 0 :
return []
elif i == len(lst) :
return None
else :
ixs = find_sum(???,lst,i+1)
if ixs != None :
return ???
else :
return find_sum(???,lst,i+1)

Loop in a list (Python v3) beginner

I am stuck in making a loop that will eliminate the values(from the alist) that are below average.
Thanks for the help.
a=input("Enter a list of values separated by a coma : ")
alist=eval(a)
print("the list is : ",alist)
average = sum(alist)/len(alist)
print("the average is : ",average)
for i in alist:
if alist[i]<average:
alist.remove[i]
You are almost there. Instead of removing elements, select elements you want to retain instead:
alist = [a for a in alist if a>=average]
Your mistake here is that for i in alist: is iterating over list elements themselves, not indexes, so alist[i] is throwing an error (or returning nonsense).
For the "loop" you can use a filter and a lambda function.
above_average = list(filter(lambda x: x >= average, alist))
For the rest of your code, I suggest you clean it up to something which is safer (use of eval is very bad)
import ast
user_string = raw_input('input a list of numbers separated by a commas: ')
alist = list(ast.literal_eval(user_string)))
So, in all, I would write your code as something like this:
import ast
user_string = raw_input('input a list of numbers separated by a commas: ')
numbers = list(ast.literal_eval(user_string)))
average = sum(numbers)/len(numbers)
print('The numbers: {}'.format(numbers))
print('The average: {}'.format(average))
above_average = list(filter(lambda x: x >= average, numbers))
# now do what you want with the above_average numbers.
Other answers tell you how to do it. I'll tell you why it doesn't work:
You iterate over the list and, at the same time, modify it.
This leads to items being missed during the iteration.
Why?
Internally, the iteration works via an index to the list. So it is the same as doing
idx = 0
while True:
try:
i = alist[idx]
except IndexError:
break
idx += 1
if alist[i] < average:
alist.remove(i)
What happens if you are at the element #3, go to the next one and then remove #3? Right, the indexes of the remaining ones move down and you are pointing to the one which formerly was #5. The old #4 is skipped at this test.
(BTW, I don't know if you noticed, I have replaced your [] behind .remove with ().)
You are mixing two ways of iterating a list: By index, and by element. In your loop, i is not the index, but the element of the list itself, thus alist[i] won't work.
If you use the for x in somelist loop, then x is the element itself, not the index of the element. For iterating over the indices, you can use for i in range(len(somelist)), or you could use for i, x in enumerate(somelist) to loop over tuples of index and element.
Also note that removing elements from a list or other kinds of collections while you are looping them generally is a bad idea. Better create a copy of the list.
for x in list(alist): # creates a copy of alist
if x < average: # remember: x is the element itselt
alist.remove(x) # remove element x from list
But the way you do it (with eval of a comma-separated string of numbers), alist is a tuple, not a list, and thus has no remove method at all. Thus you either have to convert it to a list before (alist = list(eval(a)), or use one of the approaches given in the other answers, creating a new list using list comprehension or filter and retaining the "good" elements.
As a general principle for asking StackOverflow questions like this, you should always include example input and output -- show what happens, and what you expect to happen.
In this case, I believe there are two three problems with your code:
Edit: Third, but possibly most importantly, look at glglgl's answer. If you implement the two fixes I describe below, you'll still have one problem: your code won't necessarily remove all the items you want to remove, because it'll skip over some items.
First, you say alist[i], which grabs the element of alist at index i. But saying for i in alist makes i be successive elements in the list already. Example:
mylist = [1, 2, 4]
for i in mylist:
print(i)
Would give you the output:
1
2
4
If you instead said this (which is like what you wrote)
mylist = [1, 2, 4]
for i in mylist:
print(mylist[i])
It wouldn't work as you'd expect, because you'd get the element at index 1, the element at index 2, and then try to get the element at index 4, but that wouldn't exist. You'll get something like this:
2
4
IndexError: list index out of range
Second, your syntax for removing an element is wrong. You should use alist.remove(i) instead of alist.remove[i]. You want to call a function, so you use parentheses. The square brackets are for indexing and slicing.

Python truncating numbers in integer array

I am teaching myself Python and am running into a strange problem. What I am trying to do is pass a list to a function, and have the function return a list where elements are the sum of the numbers around it, but what I thought would work produced some strange results, so I made a debug version of the code that still exhibts the behavior, which is as follows:
When I make an integer array, and pass it to an function which then uses a for loop print the individual values of the list, the numbers following the first one in each int are truncated.
For example, the following input and output:
Please enter a number: 101
Please enter a number: 202
Please enter a number: 303
Please enter a number: .
1
2
3
This happens no matter the input, if its 10, 101, or 13453 - the same behavior happens.
I know I am probably missing something simple, but for the sake of me, no amount of googling yields me a solution to this issue. Attached below is the code I am using to execute this. It is interesting to note: when printing the entire list outside of the for loop at any point, it returns the full and proper list (ie ['101', '202', '303'])
Thanks!
temp = list()
def sum(list):
print list
for i in range(1, len(list)+1):
print i
return temp
L = list()
while True:
input = raw_input("Please enter a number: ");
if input.strip() == ".":
break
L.append(input);
print L
L2 = sum(L)
print L2
The loop
for i in range(1, len(my_list)+1):
print i
iterates over the numbers from 1 to len(my_list), not over the items of the list. To do the latter, use
for x in my_list:
print x
(I've renamed list to my_list to save you another headache.)
You are printing the counter, not the list item. This is what you want:
for i in list:
print i
list is itself iterable and you don't need a counter to loop it.

Categories

Resources