How to take Nested List as input in Python - python

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)

Related

How to iterate all item at once in python list?

let's say i have list
strs = ["dog","racecar","car"]
when I = 0 , then I want
d,r,c
when I = 1, then I want
do,ra,ca
when I = 2, then I want
dog,rac,car
like that
How can i do this ?
First Part
1.
strs = ["dog","racecar","car"]
l = 0
for a in strs:
print(a[:l+1],end=' ')
Output
d r c
Explanation.
First loop through all the strings in the list.
Then print the string only to the l index, I use l+1 because the end is excluded.
Means If you run print('hello'[0:3]) it will give all strings to the index 0 to 2 not 3/
set end=' ' so it will not ends with a new line.
2.
strs = ["dog","racecar","car"]
l = 0
lst = [a[:l+1] for a in strs]
print(*lst) # here *lst is same as print(lst[0],lst[1],...,lst[n])
Output
d r c
Second part
1.
strs = ["dog","racecar","car"]
for l in range(min(len(a) for a in strs)):
for s in strs:
print(s[:l+1],end=' ')
print()
Output
d r c
do ra ca
dog rac car
2.
strs = ["dog","racecar","car"]
for l in range(min(len(a) for a in strs)):
print(*[s[:l+1] for s in strs])
Output
d r c
do ra ca
dog rac car
Explanation for min(len(a) for a in strs)
Here inner comprehension(len(a) for a in strs) generates a list with the value as the length of the string inside the list.
Then min(len(a) for a in strs) returns the lowest number from the above list.
I hope my explanation is clear. If not please ask me in the comments.
First you need to find the minimum length and then loop through each size up to that length.
strs = ["dog","racecar","car"]
for l in range(min(len(w) for w in strs)):
print(",".join(s[:l+1] for s in strs))
strs = ["dog","racecar","car"]
def func(arr,n):
w=""
for i in range(len(arr)):
if n<=len(arr[0])-1:
w+=(arr[i])[0:n]+" "
else:
w+=arr[i]+" "
return w;
print(func(strs,2))
Keep on adding sliced portions of each string via loops,If the value of "l" [the variable you used to refer to the final pos] were to exceed the length of the string, the string would be added as a whole. (at least that's how I would handle that case).

For all sets in a list, extract the first number only

I have a list that looks like this:
b = [{'dg_12.942_ch_293','dg_22.38_ca_627'},
{'dg_12.651_cd_286','dg_14.293_ce_334'},
{'dg_17.42_cr_432','dg_18.064_cm_461','dg_18.85_cn_474','dg_20.975_cf_489'}]
I want to keep only the first number for each item in each set:
b = [{'12','22'},
{'12','14'},
{'17','18','18','20'}]
I then want to find the difference between the smallest and the largest number of each set and put it in a list, so in this case I would have:
b = [3,2,3]
Ugly and without any sanity check, but do the work.
import re
SEARCH_NUMBER_REGEX = re.compile("(\d+)")
def foo(dataset):
out = []
for entries in dataset:
numbers = []
for entry in entries:
# Search for the first number in the str
n = SEARCH_NUMBER_REGEX.search(entry).group(1)
n = int(n)
numbers.append(n)
# Sort the numbers and sustract the last one (largest)
# by the first one (smallest)
numbers.sort()
out.append(numbers[-1] - numbers[0])
return out
b = [
{'dg_12.942_ch_293', 'dg_22.38_ca_627'},
{'dg_12.651_cd_286', 'dg_14.293_ce_334'},
{'dg_17.42_cr_432', 'dg_18.064_cm_461', 'dg_18.85_cn_474', 'dg_20.975_cf_489'}
]
print(b)
# > [10, 2, 3]
This is giving o/p as [10,2,3]
(The difference b/w 22 and 12 is 10)
b = [{'12','22'},
{'12','14'},
{'17','18','18','20'}]
l = []
for i in b:
large ,small = -99, 99
for j in i:
j = int(j)
if large < j:
large = j
if small >j:
small = j
l.append(large - small)
print(l)
Here's yet another way to do it:
import re
ba = [{'dg_12.942_ch_293', 'dg_22.38_ca_627'},
{'dg_12.651_cd_286', 'dg_14.293_ce_334'},
{'dg_17.42_cr_432', 'dg_18.064_cm_461', 'dg_18.85_cn_474', 'dg_20.975_cf_489'}]
bb = []
for s in ba:
ns = sorted([int(re.search(r'(\d+)', ss)[0]) for ss in s])
bb.append(ns[-1]-ns[0])
print(bb)
Output:
[10, 2, 3]
Or, if you want to be ridiculous:
ba = [{'dg_12.942_ch_293', 'dg_22.38_ca_627'},
{'dg_12.651_cd_286', 'dg_14.293_ce_334'},
{'dg_17.42_cr_432', 'dg_18.064_cm_461', 'dg_18.85_cn_474', 'dg_20.975_cf_489'}]
bb = [(n := sorted([int(re.search(r'(\d+)', ss)[0]) for ss in s]))[-1]-n[0] for s in ba]
print(bb)
In your final product I see it was "[3,2,3]" but if I am understanding your question correct, it would be [10,2,3]. Either way the code I have below will atleast point you in the right direction (hopefully).
This code will iterate through each tuple in the list and split the str (since that is all we want to compare) and add them into lists. These numbers are then evaluated and subtracts the smallest number from the biggest number, and places it in a separate array. This "separate array" is the final one as shown in your question.
Goodluck - hopefully this helps!
import re
b = [('dg_12.942_ch_293','dg_22.38_ca_627'), ('dg_12.651_cd_286','dg_14.293_ce_334'), ('dg_17.42_cr_432','dg_18.064_cm_461','dg_18.85_cn_474','dg_20.975_cf_489')]
final_array = []
for tup in b:
x = tup
temp_array = []
for num in x:
split_number = re.search(r'\d+', num).group()
temp_array.append(split_number)
difference = int(max(temp_array)) - int(min(temp_array))
final_array.append(difference)
print(final_array)

How to find second runner up score?

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))

How to limit the user input in range?

2 inputs has to enter by the user. first number is How many elements you can enter?
Let's say 5, then user can only insert 5 elements
K = int(input())
L =[]
for i in range(K):
L.append(i)
K =5
we need to enter 5 values like 11 22 33 44 55
Desired out put
L = [11,22,33,44,55]
Can we do something like
k=int(input())
L = list(input().split()) for _ in range(k)
so that I can give the digits in one shot
All you're missing here is the second input that the for loop.
K = int(input())
L =[]
for i in range(K):
L.append(input())
print(L)
Can you be specific and clear.I cant understand what you are trying to ask.Limiting the range in input? You aldready limit you input by fixing a range.
If i understood your question correctly then here is my solution:
k=int(input())
print([input() for i in range(k)])
This is the easiest way rather than appending.
If you need to give space seperated input then you can use split funtion
K = int(raw_input())
print K
finalList = []
for i in range(K):
finalList.append(int(raw_input()))
print finalList
OUTPUT:
python test4.py
5
5
11
22
33
44
55
[11, 22, 33, 44, 55]
If I'm understanding the question correctly, you're just missing one line. You ask for the user to specify K, which they do. You follow it with a loop that runs K-times. However, you forgot to have the user input these K values into L
Adding that extra line would look something like this:
for i in range(K):
input_int = int( input() )
L.append( input_int )

Out of range issue within a loop

I try to make a script allowing to loop through a list (tmpList = openFiles(cop_node)). This list contains 5 other sublists of 206 components.
The last 200 components of the sublists are string numbers ( a line of 200 string numbers for each component separated with a space character).
I need to loop through the main list and create a new list of 5 components, each new component containing the 200*200 values in float.
My actual code is try to add a second loop to an older code working with the equivalent of one sublist. But python return an error "Index out of range"
def valuesFiles(cop_node):
tmpList = openFiles(cop_node)
valueList = []
valueListStr = []*len(tmpList)
for j in range (len(tmpList)):
tmpList = openFiles(cop_node)[j][6:]
tmpList.reverse()
for i in range (len(tmpList)):
splitList = tmpList[i].split(' ')
valueListStr[j].extend(splitList)
#valueList.append(float(valueListStr[j][i]))
return(valueList)
valueListStr = []*len(tmpList) does not do what you think it does, if you want a list of lists use a list comp with range:
valueListStr = [[] for _ in range(len(tmpList))]
That will create a list of lists:
In [9]: valueListStr = [] * i
In [10]: valueListStr
Out[10]: []
In [11]: valueListStr = [[] for _ in range(i)]
In [12]: valueListStr
Out[12]: [[], [], [], []]
So why you get an error is because of valueListStr[j].extend(splitList), you cannot index an empty list.
You don't actually seem to return the list anywhere so I presume you actually want to actually return it, you can also just create lists inside the loop as needed, you can also just loop over tmpList and openFiles(cop_node):
def valuesFiles(cop_node):
valueListStr = []
for j in openFiles(cop_node):
tmpList = j[6:]
tmpList.reverse()
tmp = []
for s in tmpList:
tmp.extend(s.split(' '))
valueListStr.append(tmp)
return valueListStr
Which using itertools.chain can become:
from itertools import chain
def values_files(cop_node):
return [list(chain(*(s.split(' ') for s in reversed(sub[6:]))))
for sub in openFiles(cop_node)]
def valuesFiles(cop_node):
valueListStr = []
for j in openFiles(cop_node):
tmpList = j[6:]
tmpList.reverse()
tmp = []
for s in tmpList:
tmp.extend(s.split(' '))
valueListStr.append(tmp)
return valueListStr
After little modification I get it to work as excepted :
def valuesFiles(cop_node):
valueList = []
for j in range (len(openFiles(cop_node))):
tmpList = openFiles(cop_node)[j][6:]
tmpList.reverse()
tmpStr =[]
for s in tmpList:
tmpStr.extend(s.split(' '))
tmp = []
for t in tmpStr:
tmp.append(float(t))
valueList.append(tmp)
return(valueList)
I don't understand why but the first loop statement didn't work. At the end the I had empty lists like so : [[],[],[],[],[]] . That's why I changed the beginning. Finally I converted the strings to floats.

Categories