Python 3.6 "IndexError: list index out of range" - python

Can someone tell me my mistake?
realpair = input("")
realpairfinal = []
rp = list(realpair)
print(rp[0],rp[1])
for i in range(0, len(realpair)):
a = []
v1 = rp[0]
v2 = rp[1]
rp.pop(0)
rp.pop(0)
a.append(v1)
a.append(v2)
realpairfinal.append(a)
pair = realpairfinal
pair2 = realpairfinal
print(realpairfinal)
if my input is 123456, realpairfinal is supposed to be [[1, 2][3, 4][5, 6]] but it tells me:
1 2
Traceback (most recent call last):
v1 = rp[0]
IndexError: list index out of range

realpair = input("")
realpairfinal = []
rp = list(realpair)
for i in range(0, len(realpair)-3):
a = []
v1 = rp[0]
v2 = rp[1]
rp.pop(0)
rp.pop(0)
a.append(v1)
a.append(v2)
realpairfinal.append(a)
pair = realpairfinal
pair2 = realpairfinal
print(realpairfinal)
Subtract three from the length. Output: [['1', '2'], ['3', '4'], ['5', '6']]

pairs = [list(realpair[i:i+2]) for i in range(0, len(realpair), 2)]
This is using a list comprehension to construct a list instead of making an empty list and then appending elements to it.
I'm taking substring of length 2, making it into a list of characters using list() which is then added to the outer list (using list comprehension)

Related

How do you read input line of text in python and make an array out of those elements and assign last digit to a variable?

You are given as input lines of a file containing a list and integer which is associated with a variable.
line = 1,2,3,4;5
How do i go about making an array out of the first 4 elements [1,2,3,4] and assigning the last element 5 to variable K?
I wanted to split it and get this:
arr = [1,2,3,4]
k = 5
text = "1,2,3,4;5"
myList = text.split(";")
k = int(myList[-1])
myList.pop()
arr = myList
n = len(arr)
i = 0
while(i<n):
left = i
right = min(i + k - 1, n - 1)
while (left < right):
arr[left], arr[right] = arr[right], arr[left]
left+= 1;
right-=1
i+= k
for i in range(0, n):
print(arr[i], end ="")
Thank you everyone. I just needed to split the input and change the type from string to integer.
Here's a one line version using the re module:
import re
line = '1,2,3,4;5'
*arr, k = re.split('[,;]', line)
This gives:
print(arr, k)
['1', '2', '3', '4'] 5
If you need the array (Python list) to be integers instead of strings, you can use:
arr = [int(s) for s in arr]
Hi looking at the input you gave 1,2,3,4;5
If this is the input then:
(a,k) = input().split (";") #this will sperate 1,2,3,4 to arr and 5 to k
arr = a.split(",") #it sperate 1234 and makes a list
print(arr,r)
Please tell me if it works
Here is what you can try:
x='1,2,3,4;5'.split(",")
last=int(x[-1].split(";")[1])
x[-1]=x[-1].split(';')[0]
print(x,last)
OR
x='1,2,3,4;5'.split(';')
print(list(x[0].split(',')),int(x[1]))
You could do something like this:
>>> line = '1,2,3,4;5'
>>> arr, k = line.split(';')
>>> arr = arr.split(',')
>>> arr
['1', '2', '3', '4']
>>> k
5
line.split(';') will split the value separated by ; into two lists.
arr.split(',') will then split all the value separated by ,.

Append new values to the same key in a Python dictionary

I am inputting:
5
A 3
A 2
A 4
B 13
B 14
And I want to put them in the dictionary like this.
{A: ['3', '2', '4'] , B['13','14']}
But I got this:
{'A': ['3', '2', '4'], 'B': ['1', '3', '14']}
I tried:
N = int(input())
d = dict()
for i in range(N):
first,second = [j for j in input().split()]
if first in d:
d[first].append(second)
else:
d[first] = list(second)
print(d)
You want
d[first] = [second]
not
d[first] = list(second)
list(string) iterates over string and places each individual character as a separate element in the list.
[string] creates a list with the entire string as an element.
Here after the input it checks whether it is already in the dictionary and if it appends the new value and if it isn't already there then it creates a new list in the dictionary.
N = int(input())
d = dict()
for i in range(N):
i = input()
lst = i.split()
if lst[0] in d:
d[lst[0]].append(lst[1])
else:
d[lst[0]] = [lst[1]]
print(d)

Delete the duplicate arrays inside an array in python

I want to ignore the duplicates from an array that has multiple array in lowest running cost. For example;
A = [['1','2'],['3','4'],['5','6'],['1','2'],['3','4'],['7','8']]
the expected output should be like as
Output = [['1','2'],['3','4'],['5','6'],['7','8']]
Is it possible to compare arrays inside an array.
I am doing in this way;
A = [['1','2'],['3','4'],['5','6'],['1','2'],['3','4'],['7','8']]
output = set()
for x in A:
output.add(x)
print (output)
But it prompts;
TypeError: unhashable type: 'list'
How about something simple like:
B = list(map(list, set(map(tuple, A))))
Here's my "bakeoff" -- please let me know if I've misrepresented your solution:
import timeit
from random import choice
DIGITS = list("123456789")
# one million elements in list
A = [[choice(DIGITS), choice(DIGITS)] for _ in range(1000000)]
def elena(A): # MrName's solution is identical
B = []
for i in A:
if i not in B:
B.append(i)
return B
def cdlane(A):
return list(map(list, set(map(tuple, A))))
def VikashSingh(A):
uniques = set()
B = []
for x in A:
val = '-'.join([str(key) for key in x])
if val not in uniques:
B.append(x)
uniques.add(val)
return B
def AbhilekhSingh(A):
def unique_elements(l):
last = object()
for item in l:
if item == last:
continue
yield item
last = item
return list(unique_elements(sorted(A)))
# sanity check to make sure everyone one agrees on the answer
B = sorted(elena(A))
assert(B == sorted(cdlane(A)))
assert(B == sorted(VikashSingh(A)))
assert(B == sorted(AbhilekhSingh(A)))
print("elena:", format(timeit.timeit('B = elena(A)', number=10, globals=globals()), ".3"))
print("cdlane:", format(timeit.timeit('B = cdlane(A)', number=10, globals=globals()), ".3"))
print("VikashSingh:", format(timeit.timeit('B = VikashSingh(A)', number=10, globals=globals()), ".3"))
print("AbhilekhSingh:", format(timeit.timeit('B = AbhilekhSingh(A)', number=10, globals=globals()), ".3"))
RESULTS
elena: 17.5
cdlane: 2.04
VikashSingh: 10.0
AbhilekhSingh: 8.83
Here's a simple solution:
In [27]: A = [['1','2'],['3','4'],['5','6'],['1','2'],['3','4'], ['7','8']]
In [28]: new_list = []
In [29]: for i in A:
...: if i not in new_list:
...: new_list.append(i)
...:
In [30]: new_list
Out[30]: [['1', '2'], ['3', '4'], ['5', '6'], ['7', '8']]
You can sort the list and compare every element with it's previous one.
List length: n
Element length: m
Complexity: Sorting(n * log(n) * m) + Comparison(n * m) = Total(n * log(n) * m)
Try this:
def unique_elements(l):
last = object()
for item in l:
if item == last:
continue
yield item
last = item
def remove_duplicates(l):
return list(unique_elements(sorted(l)))
Another potentially simple solution, but not sure how the "cost" would compare to other presented solutions:
A = [['1','2'],['3','4'],['5','6'],['1','2'],['3','4'],['7','8']]
res = []
for entry in A:
if not entry in res:
res.append(entry)
List length: n
Element length: m
Complexity:
Iterate on n
Format key by iterating on m
Check key exists is set `uniques` in O(1)
Total running time is is O(n * m)
one simple way to do this is:
uniques = set()
output = []
for x in A:
val = '-'.join([str(key) for key in x])
if val not in uniques:
output.append(x)
uniques.add(val)
print (output)
output:
[['1', '2'], ['3', '4'], ['5', '6'], ['7', '8']]

Matching and Combining Multiple 2D lists in Python

I am trying to combine (2) 2D lists based on a common value in both lists.
The values in the list are unique so there is nothing to take in to account for a list entry having any of the same values.
The example is:
list1 = [['hdisk37', '00f7e0b88577106a']]
list2 = [['1', '00f7e0b8cee02cd6'], ['2', '00f7e0b88577106a']]
With the desired result of:
list3 = [['hdisk37', '00f7e0b88577106a','2']]
The common value is at list1[0][1] and list2[1][1].
The pythonic way to get the needed result using set objects:
list1 = [['hdisk37', '00f7e0b88577106a']]
list2 = [['1', '00f7e0b8cee02cd6'], ['2', '00f7e0b88577106a']]
set1 = set(list1[0])
list3 = [list(set1 | s) for s in map(set, list2) if set1 & s]
print(list3)
The output:
[['00f7e0b88577106a', '2', 'hdisk37']]
set1 & s is intersection of two sets(returns a new set with elements common to the first set and all others)
set1 | s is union of a specified sets
Try this:
result = []
for inner_list1 in list1:
for inner_list2 in list2:
set1 = set(inner_list1)
set2 = set(inner_list1)
if set1.intersection(set2):
result.append(list(set1.union(set2)))
For each inner list in both lists, check if the intersection between them is not empty. In case it isn't, they are both merged and added to the final result.
This method returns all the possible "second value" matches as a dict, from the second value to the resulting list. It also takes an arbitrary number of these lists of lists (not just two).
import collections
a = [['hdisk37', '00f7e0b88577106a']]
b = [['1', '00f7e0b8cee02cd6'], ['2', '00f7e0b88577106a']]
def combine(*lols): # list of lists
ret = collections.defaultdict(set)
for lol in lols:
for l in lol:
ret[l[1]].add(l[1])
ret[l[1]].add(l[0])
return {k:list(v) for k,v in ret.items()}
print combine(a,b)
Output:
$ python test.py
{'00f7e0b8cee02cd6': ['00f7e0b8cee02cd6', '1'], '00f7e0b88577106a': ['hdisk37', '2', '00f7e0b88577106a']}
To get your exact output requested, you'd do:
combine(list1, list2).get('00f7e0b88577106a')
If you wanna try something different you could do a
merger = lambda x,y : set(x)|set(y) if set(x)&set(y) else x
results = []
for item in list1:
result = reduce(merger,[item]+list2)
if isinstance(result,set):
results.append(result)
print results

python numpy parse array to get items

Hi I tried taking distinct items of every sublist and making an array
My input is a 2D list
alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']]
And output I want is an array of distinct items
out = [1,2,3,5,15,657]
I tried
from numpy import np
alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']]
anarray = np.array(alist)
newarray = []
for i in anarray:
for j in i:
if j in newarray:
pass
else:
print j
You could make use of a set:
out = set()
for inner in alist:
out.update(inner)
out = map(int, out) # in your example you have a list of ints
>>> print out
[1, 2, 3, 5, 15, 657]
from itertools import chain
alist = [['1', '2'], ['3', '5', '2'], ['15', '1'], ['5', '657', '3', '1']]
# Flatten the list into a single-level list of all the values
flattened_list = list(chain.from_iterable(alist))
# Use a set to remove the duplicates
uniques = set(flattened_list)
# Sort the unique values by the numeric value of each value
sorted_results = sorted(uniques, key=lambda value: int(value))
print sorted_results
Modifying your code slightly you can store your result in newarray:
alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']]
newarray = []
for i in alist:
for j in i:
if j in newarray:
pass
else:
newarray.append(j)
Your result will be stored in newarray
To make it slightly better:
alist = [['1','2'], ['3','5','2'], ['15','1'], ['5','657','3','1']]
newarray = []
for i in alist:
for j in i:
if j not in newarray:
newarray.append(j)

Categories

Resources