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))
Related
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
Question :
To find the percentage of 2 sentences matching.
If 100%, Print "Exact Match!"
Ignore the difference of 1 character between any 2 words being checked. (1 character error margin)
Program :
from difflib import SequenceMatcher
def difWord(s1, s2):
m = len(s1)
n = len(s2)
if abs(m - n) > 1:
return false
count = 0
correct = 0
i = 0
j = 0
while i < m and j < n:
if s1[i] != s2[j]:
count+=1
if count==1:
return true
def seqMatch(a,b):
rat = SequenceMatcher(None,a,b).ratio()
if rat==1 :
print("Exact Match!")
else :
print(rat*100)
splitted1 = a.split()
splitted2 = b.split()
c=0
for x,y in splitted1.iteritems(),splitted2.iteritems() :
if difWord(x,y) :
c+=1;
per = (count*100)/4
print(per)
if __name__ == "__main__":
a = "He is a boy"
b = "She is a girl"
c = "He is a boy"
seqMatch(a,b)
Error :
Traceback (most recent call last):
File "C:\Users\eidmash\Documents\Demo-Project\Day0.py", line 59, in <module>
seqMatch(a,c)
File "C:\Users\eidmash\Documents\Demo-Project\Day0.py", line 43, in seqMatch
for x,y in splitted1.iteritems(),splitted2.iteritems() :
AttributeError: 'list' object has no attribute 'iteritems'
According to your traceback, the error is in the line:
for x,y in splitted1.iteritems(),splitted2.iteritems():
The method str.split() returns a list, thus it isn't a dictionary that would provide the iteritems function. However you can just iterate through the two list at a time with the help of the zip function. Modify that line to:
for x, y in zip(splitted1, splitted2):
Otherwise, without the use of that zip function to bundle the items of the two lists together, Python will interpret that as iterating through the two items which happen to be the two lists, yielding them for use in the for loop (actually will cause an error if the lists themselves don't have exactly two items as they will be unpacked into x and y), which is not what you want.
try
for x,y in zip(splitted1,splitted2)
I have to take input from the user in the following format and make a nested list from it. The first line is the number of rows.
3
Sourav Das 24 M
Titan Das 23 M
Gagan Das 22 F
The nested list should be like :
parentlist = [
['Sourav', 'Das', '24', 'M']
['Titan', 'Das', '23', 'M']
['Gagan', 'Das', '22', 'M']
]
I have written the following code :
k = int(raw_input())
parentlist = [[]]
for i in range(0, k):
str1 = raw_input()
parentlist[i] = str1.split()
But it gives some index out of bound exception after entering the 2nd row (as shown below). What's wrong in the code for which it is giving this exception ?
3
Sourav Das 24 M
Titan Das 23 M
Traceback (most recent call last):
File "nested.py", line 5, in <module>
parentlist[i] = str1.split()
IndexError: list assignment index out of range
(I am new to Python. So point out any other mistakes too if you find any in my code.)
When your reading the second line, you attempt to store the splitted line into parentlist[1]. But your parentlist has only one element (parentlist[0]).
The solution is to append the list.
k = int(raw_input())
parentlist = []
for i in range(0, k):
str1 = raw_input()
parentlist.append(str1.split())
Your parentlist is a list with one element. On the second iteration for your for loop, you try to access the second element of parentlist, that causes the IndexError. Lists in Python work different from e.g. arrays in JavaScript or PHP.
What you actually want to do is create an empty list and then append the result of str1.split() to it.
k = int(raw_input())
parentlist = []
for i in range(0, k):
str1 = raw_input()
parentlist.append(str1.split())
You should simply use list comprehension as code will be shorter and faster.
k = int(raw_input())
l = []
print [raw_input().split() for i in range(0, k)]
In Python 3:
l= [[input(), float(input())] for _ in range(int(input()))]
print l
Input:
5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39
Output:
[[Harry,37.21],[Berry,37.21],[Tina,37.2],[Akriti,41],[Harsh,39]]
You were quite close
k = int(raw_input())
parentlist = []
for i in range(k):
str1 = raw_input()
parentlist.append(str1.split())
initialize parentlist to an empty list, it is important because later we want to extend it
read an input line
split the input line -> a list
tell the parentlist to append the new list to what it has already got
If you want to go in a bad direction, you can do, similar to your code
parentlist = [[]]*k
for i in range(k):
parentlist[i] = raw_input().split()
Exercise, find what the syntax [[]]*k stands for...
Size of your parentlist [[]] is 1, where on 0 position empty list.
Your code would be work if you put into parentlist k lists:
parentlist = [[]] * k
Or use append instead, but with append additional look up of method name is necessary.
l=[]
for _ in range(int(input())):
name = input()
score = float(input())
l.append([name,score])
print(l)
scorelist =[]
n = int(input())
for i in range(n):
name.append(str(input()))
score.append(float(input()))
for i in range(n):
scorelist.append([name[i],score[i]])
print(scorelist)
k = int(input())
parentlist = [None]*k
for i in range(0, k):
str1 = input()
parentlist[i] = str1.split()
print(parentlist)
You can also use something like this :-
k = int(input())
parentlist = []
for i in range(k):
parentlist.append([j for j in input().split()])
print(parentlist)
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]