My goal is to try to return all the value in the list which has even position as well. The following is my python code. I don't know which part should I update. Please help!! Thanks
def evenValue(numbers):
results = []
for x in numbers:
if results.index(x) %2 ==0:
results.append(x)
return results
My error message is
> Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
evenValue([1,2,3,4,5,6])
File "<pyshell#6>", line 4, in evenValue
if results.index(x) %2 ==0:
ValueError: 1 is not in list
Try this. The slice takes even numbered elements.
def evenValue(numbers):
return numbers[0::2]
or shorter:
evenValue=lambda numbers: numbers[0::2]
def evenValue(numbers):
results = []
for x in numbers:
if numbers.index(x) %2 ==0: #Use 'numbers' list instead of 'results' list
results.append(x)
return results
print(evenValue([1,2,3,4,5,6,7]))
Output:
[1, 3, 5, 7]
Using list comprehension:
lst = list(range(50))
even_indexes = lambda numbers: [lst[i] for i in range(len(lst)) if i%2==0]
even_indexes(lst)
Related
n = int(input())
arr = map(int, input().split())
setA = set(arr)
for x in setA:
x.sorted()
print(x)
Here is the error that I am facing
5
9 8 7 4
Traceback (most recent call last):
File "C:\Users\jnnim\OneDrive\Desktop\hacker rank\practice\untitled1.py", line 6, in <module>
x.sorted()
AttributeError: 'int' object has no attribute 'sorted'
Requirements for the program
You are given n scores. Store them in a list and find the score of the runner-up.
The first line contains n elements. The second line contains an array of integers each separated by a space.
In this program for loop, I have tried that within setA, because we have to sort setA.
I had made the array in set because it does not keeps duplicate element.
Finally when I have to find out the runner up score then I will call [-1] index and make it print as runner up score.
If you need to know more about question please comment, I will tell you anything you need.
Please help me solve this error in this program only within these lines. Don't give a full solution
First off, it's sorted(x), not x.sorted. Second of all, you can sort a list, not a number.
You need to do this: x = sorted(setA).
This code will work:
n = int(input())
arr = map(int, input().split())
arrset = set(arr)
runnerup = 0
for index, val in enumerate(sorted(arrset), start=1):
if index == len(arrset) - 1:
runnerup = val
print(runnerup)
n = int(input())
arr = (int, input().split())
arrlist = []
for t in arr:
arrlist.append(t)
num=arrlist[1]
test_list = [int(i) for i in num]
test_sorted= (sorted(test_list, reverse=True))
List = []
for i in test_sorted:
if i != max(test_sorted):
List.append(i)
print(max(List))
I'm trying to call a function that creates matrices from user input, but it says that i haven't defined something.
lstA = []
lstB = []
lstC = []
def get_list(data):
lst = []
for i in range(4):
aux = []
for j in range(4):
aux.append(data)
lst.append(aux)
return lst
lstA = get_list(int(input(f'A i[{i}] j[{j}]: ')))
lstB = get_list(int(input(f'B i[{i}] j[{j}]: ')))
lstC = get_list(lstA[i][j] + lstB[i][j])
The program should take two 4x4 matrixes from user, by putting each informed number inside the lstA[i][j] and lstB[i][j].
Finally, lstC is used to sum A and B.
Error message:
Traceback (most recent call last):
File "<string>", line 13, in <module>
NameError: name 'i' is not defined
[Program finished]
How can I solve this?
To read the data into the matrices, make a function like this:
def get_lst():
mat = [[]] * 4
for i in range(4):
mat[i] = [0] * 4
for j in range(4):
mat[i][j] = int(input(f'mat[{i}][{j}]: '))
return mat
This function will ask the user for input for each element of the matrix and populate that position with what the user entered.
Now this is how you use it:
lstA = get_lst()
lstB = get_list()
As for summing the elements of the matrices, refer to this answer
I am aware of what it means to be out of range when indexing, but I am struggling to see why my code is generating this error...
import random
howMany = random.randint(1,3)
oldList = [['a',1,2,3], ['b',1,2,3], ['c',1,2,3], ['d',1,2,3], ['e',1,2,3], ['f',1,2,3], ['g',1,2,3], ['h',1,2,3], ['i',1,2,3]]
newList = []
for i in range(0, howMany):
newList[i] = oldList[random.randint(0, len(oldList)-1)] # subtract one
You are getting the error because newList is empty (its length is 0). You are trying to access elements in it using an index, but there are no indices. Here's a simpler example of what's happening:
>>> newList = []
>>> i = 0
>>> newList[i] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
What you want to do is use append():
import random
howMany = random.randint(1,3)
oldList = [['a',1,2,3], ['b',1,2,3], ['c',1,2,3], ['d',1,2,3], ['e',1,2,3], ['f',1,2,3], ['g',1,2,3], ['h',1,2,3], ['i',1,2,3]]
newList = []
for i in range(0,howMany):
newList.append(oldList[random.randint(0, len(oldList)-1)]) # subtract one
My code is giving me the error of:
list_subs[n][4] = np.random.normal(list_subs[n][1], list_subs[n][2])
IndexError: list assignment index out of range.
I have searched for this error and i still can't find what is the problem.
Edit: Full Traceback
Traceback (most recent call last):
File "", line 420, in run_nodebug
File "C:\Documents and Settings\jhsilva\Desktop\Monte carlo\Teste.py", line 71, in
generateRandomNumbers(list_subs)
File "C:\Documents and Settings\jhsilva\Desktop\Monte carlo\Teste.py", line 41, in generateRandomNumbers
list_subs[n][4] = np.random.normal(list_subs[n][1], list_subs[n][2])
IndexError: list assignment index out of range
The Code
def generateRandomNumbers(list_subs):
for n in range(len(list_subs)):
string = list_subs[n][3]
string = string.lower()
if(string == "normal"):
list_subs[n][4] = np.random.normal(list_subs[n][1], list_subs[n][2])
print("Numero gerado:",list_subs[n][4])
variables = [v for v in variables if v not in special]
list_subs=[[0 for col in range(6)] for row in range(len(variables)-1)]
#This prints fine
print(len(list_subs))
#this prints fine too
print(list_subs[0][4])
for n in range(len(variables)):
if n>0:
(media,desviopadrao,distribuicao) = eval(input("For variable "+variables[n]+" input: median, std, distr \n"))
list_subs[n-1] = [variables[n], media, desviopadrao, distribuicao]
N = eval(input("Qual o numero de iteracoes que deseja:"))
Var = []
for n in range(N):
generateRandomNumbers(list_subs)
Var.append(calcEq(formula))
list_subs[n-1] = [variables[n], media, desviopadrao, distribuicao]
You are setting list_subs to be a list of lists of length 4. This means that the valid indeces are 0, 1, 2, 3. In generateRandomNumbers you access index 4, which is invalid.
Security note: Don't use eval(input(...)). If you want to parse numbers/tuples etc simply use ast.literal_eval, which is a safe alternative.
from string import Template
from string import Formatter
import pickle
f=open("C:/begpython/text2.txt",'r')
p='C:/begpython/text2.txt'
f1=open("C:/begpython/text3.txt",'w')
m=[]
i=0
k='a'
while k is not '':
k=f.readline()
mi=k.split(' ')
m=m+[mi]
i=i+1
print m[1]
f1.write(str(m[3]))
f1.write(str(m[4]))
x=[]
j=0
while j<i:
k=j-1
l=j+1
if j==0 or j==i:
j=j+1
else:
xj=[]
xj=xj+[j]
xj=xj+[m[j][2]]
xj=xj+[m[k][2]]
xj=xj+[m[l][2]]
xj=xj+[p]
x=x+[xj]
j=j+1
f1.write(','.join(x))
f.close()
f1.close()
It say line 33,xj=xj+m[l][2]
has index error,list out of range
please help
thanks in advance
Suppose i is 10 then on the last run of the while loop j is 9, now you have l = j + 1 so l will be 10 but your 10 lines in m are indexed 0..9 so m[l][2] will give an index error.
Also, you code would look a lot better if you just added the elements to your list in one go i.e:
x = x + [j, m[j][2], m[k][2], m[l][2], p]
Spaces are an eyes best friend!
The IndexError exception (list index out of range) means that you have attempted to access an array using an index that is beyond the bounds of the array. You can see this in action using a simple example like this:
>>> a = [1, 2, 3]
>>> a[2]
3
>>> a[3]
Traceback (most recent call last):
File "<stdin>", line 1, in ?
IndexError: list index out of range
I can't exactly follow your code, but what that error means is that either:
l exceeds the bounds of m, or
2 exceeds the bounds of m[l]