Indexes and ranges in python - python-3.x

I have this code:
def main():
if (len(sys.argv) > 2) :
P=list()
f= open('Trace.txt' , 'w+')
Seed = int(sys.argv[1])
for i in range(2, len(sys.argv)):
P[i-2] = int(sys.argv[i])
for j in range(0, len(sys.argv)-1) :
Probability=P[j]
for Iteration in (K*j, K*(j+1)):
Instruction= generateInstruction(Seed, Probability)
f.write(Instruction)
f.close()
else:
print('Params Error')
if __name__ == "__main__":
main()
The idea is that I am passing some parameters through the command line. the first is seed and the rest I want to have them in a list that I am parsing later and doing treatments according to that parameter.
I keep receiving this error:
P[i-2] = int(sys.argv[i])
IndexError: list assignment index out of range
what am I doing wrong
PS: K, generateSegment() are defined in a previous part of the code.

The error you see is related to a list being indexed with an invalid index.
Specifically, the problem is that P is an empty list at the time is being called in that line so P[0] is indeed not accessible. Perhaps what you want is to actually add the element to the list, this can be achieved, for example, by replacing:
P[i-2] = int(sys.argv[i])
with:
P.append(int(sys.argv[i]))
Note also that argument parsing is typically achieved way more efficiently in Python by using the standard module argparse, rather than parsing sys.argv manually.

It looks like you might be referencing a list item that does not exist.
I haven't used Python in quite a while but I'm pretty sure that if you want to add a value to the end of a list you can use someList.append(foo)

The problem is that you are assigning a value to an index which does not yet exist.
You need to replace
P[i-2] = int(sys.argv[I])
with
P.append(int(sys.argv[i]))
Furthermore, len(sys.argv) will return the number of items in sys.argv however indexing starts at 0 so you need to change:
for i in range(2, len(sys.argv)):
with
for i in range(2, len(sys.argv)-1):
As you will run into a list index out of range error otherwise

Related

Sum of two numbers Python

This is my code, but the Spyder keeps saying there is an indexError of list index out of range for a = int(tokens[0]). Please advise.
import sys
input_ = sys.stdin.read()
tokens = input_.split()
a = int(tokens[0])
b = int(tokens[1])
print(a+b)
The below also works, but I see someone running the above code in Linux and worked, and I am on windows, wondering what is the cause of the above not running properly. Thanks all!
def sum_of_two_digits(first_digit, second_digit):
return first_digit + second_digit
if __name__ == '__main__':
a, b = map(int, input().split())
print(sum_of_two_digits(a, b))
To prove you're getting the input you expect, you can print(len(tokens)) or simply print(input_). But suffice to say this is not a Linux/Windows issue. Rather, your tokens variable is empty by the time you index into it (tokens[0]).
You're not getting anything into the input_ value. This may be because you're using read() and are inputing the values in an unexpected way (I am guessing?). input() will probably serve you better - note that the 'Linux' version you refer to uses input(). read() will block until you send an escape sequence, though that probably has happened if you get to the list index error.

Python doesn`t work right. Parent list is changing by changing hereditary list

a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26]
for i in range(1, 27):
for j in range(1,27):
if j!=i:
lst = a
print(lst)
print(a)
lst.remove(i)
lst.remove(j)
print(lst)
print(a)
List 'a' is getting smaller coz i change list 'lst', wtf is this?
I just started to perform codewars kata.
By default, python creates a reference for an object. If you want to make an actual copy with new memory what you can do is:
from copy import deepcopy
lis_copy = deepcopy(lis)

Range function not iterating whole list, help me pls

def count4(lst):
count = 0
for i in range(lst[0],lst[-1]+1):
print(i)
print(count4([1,2,3,4,5,6,4,5,4,4]))
Here the output is showing just "1234" and not the whole list pls tell me how to iterate this list using range function.
The reason you are getting output as "1234"
The below statement
for i in range(last[0], last[-1]+1):
is interpreted as
for i in range(1, 4 + 1):
i.e
for i in range(1,5):
Solution: Use this
for i in lst:
You were trying to iterate in the range of values stored in the list at starting and end position that was passed, which is logically incorrect.
The other suggested methods are also correct since you specifically said to use the range function so think this might be the answer you were looking for
def count4(lst):
for i in range(len(lst)):
print(lst[i])
print(count4([1,2,3,4,5,6,4,5,4,4]))

Remove & add split-list using dictionary python [duplicate]

I have the code below. I'm trying to remove two strings from lists predict strings and test strings if one of them has been found in the other. The issue is that I have to split up each of them and check if there is a "portion" of one string inside the other. If there is then I just say there is a match and then delete both strings from the list so they are no longer iterated over.
ValueError: list.remove(x): x not in list
I get the above error though and I am assuming this is because I can't delete the string from test_strings since it is being iterated over? Is there a way around this?
Thanks
for test_string in test_strings[:]:
for predict_string in predict_strings[:]:
split_string = predict_string.split('/')
for string in split_string:
if (split_string in test_string):
no_matches = no_matches + 1
# Found match so remove both
test_strings.remove(test_string)
predict_strings.remove(predict_string)
Example input:
test_strings = ['hello/there', 'what/is/up', 'yo/do/di/doodle', 'ding/dong/darn']
predict_strings =['hello/there/mister', 'interesting/what/that/is']
so I want there to be a match between hello/there and hello/there/mister and for them to be removed from the list when doing the next comparison.
After one iteration I expect it to be:
test_strings == ['what/is/up', 'yo/do/di/doodle', 'ding/dong/darn']
predict_strings == ['interesting/what/that/is']
After the second iteration I expect it to be:
test_strings == ['yo/do/di/doodle', 'ding/dong/darn']
predict_strings == []
You should never try to modify an iterable while you're iterating over it, which is still effectively what you're trying to do. Make a set to keep track of your matches, then remove those elements at the end.
Also, your line for string in split_string: isn't really doing anything. You're not using the variable string. Either remove that loop, or change your code so that you're using string.
You can use augmented assignment to increase the value of no_matches.
no_matches = 0
found_in_test = set()
found_in_predict = set()
for test_string in test_strings:
test_set = set(test_string.split("/"))
for predict_string in predict_strings:
split_strings = set(predict_string.split("/"))
if not split_strings.isdisjoint(test_set):
no_matches += 1
found_in_test.add(test_string)
found_in_predict.add(predict_string)
for element in found_in_test:
test_strings.remove(element)
for element in found_in_predict:
predict_strings.remove(element)
From your code it seems likely that two split_strings match the same test_string. The first time through the loop removes test_string, the second time tries to do so but can't, since it's already removed!
You can try breaking out of the inner for loop if it finds a match, or use any instead.
for test_string, predict_string in itertools.product(test_strings[:], predict_strings[:]):
if any(s in test_string for s in predict_string.split('/')):
no_matches += 1 # isn't this counter-intuitive?
test_strings.remove(test_string)
predict_strings.remove(predict_string)

Correct way to look for a item property in python list with least time and code complexity

I have a list of suppliers eg.
suppliers=[] in which i have a n number of elements in somewhat following way eg [{"supplierId":"1","aCode":2},{"supplierId":"1","aCode":3}]
Now, I need to check based on the value of a property, lets say areaCode=2 and need to check if area code is in list of suppliers named as aCode. How can I detemine the area Code exists with minimum time and code complexity and by not using for loops as I will have a lot of data in suppliers array.
In your case because it is a list of dict it is hard to not use a loop. If you only want to see if it exists you can one line it such as:
print(any(areaCode==x['aCode'] for x in suppliers))
or if you want the entries you can one line it like this:
suppliers_in_area = [x for x in suppliers if x['aCode'] == areaCode]
Both versions require a for loop and both are equally fast but the first one requires minimal memory.
- Edit -
If you just one the first occurrence (or if only one element exists) then short circuit your for loop.
def get_supplier_by_area(area_code):
for supplier in suppliers:
if supplier['aCode'] == area_code:
return supplier
# It will return None if nothing is found
or you can use a generator if you want to return the next supplier every time to call the function.
def get_supplier_by_area(area_code):
for supplier in suppliers:
if supplier['aCode'] == area_code:
yield supplier
try:
gen = get_supplier_by_area('A01')
print(next(gen)) # will print the first result or will raise a StopIteration error
print(next(gen)) # will print the second result or will raise a StopIteration
except StopIteration:
print("No more results")
The inner items are dictionaries, they can be referenced by their key.
def main():
list1=[{"supplierId":"1","aCode":2},{"supplierId":"1","aCode":3}]
searchKey=2
for item in list1:
if item['aCode']==searchKey:
print(item)
if __name__== "__main__":
main()

Resources