Range function not iterating whole list, help me pls - python-3.x

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

Related

Storing the returned value of a function as a variable

Consider the following function:
def Func(x):
Code
return List_A, List_B, number_C
I want to store one of the returned values as some variable "x" so how can I go about doing this? For example, I want to store List_B as x
I tried
x=Func[1]
Detailed explanation:
n=int(input("blablabla"))
def Func(n)
l_e=[]
for i in range (1,n):
if i%2==0:
l_e.append(i)
l_o=[]
for i in range (1,n):
if i%2>0:
l_o.append(i)
l=len(l_0)+len(l_e)
return l_o, L_e, l
let's say I want to store the second item returned as a variable, how can I do this. I tried x=Func[1], and x=Func()[1] but to no avail.
The following works: x = Func()[1]. The parentheses call the function, then the square brackets pick the item you want out of the returned tuple.

Python function looping through a dictionary of sets removing and adding items updating only some items

Thanks in advance for your assistance.
I have two dictionaries: parent_dict has a series of sets as values & pub_plat_dict is a look-up dictionary that seeks to correct the names of the items that make up the sets in parent_dict.
The function update_dict allows names where it finds a '.' to pass. If it doesn't find a name then it will try to find the name in the pub_plat_dict. If found it will .remove the old name and .add the updated name. If the name isn't present, then I want the program to move to the next item.
When I run the function update_dict corrects the first item in the parent_dict, accurately skips multiple items that don't need to be updated but then doesn't .remove or .add the other wrongly named items.
Sample Data
parent_dict = {
'49d238407e0102ba':{'opportunity_history'}
, 'f9d53c74ec1d2ff6':{'servicer.trial_balance','src_platform.loan','src_platform.loan_disbursement'}
, 'fc35a98e0cfaab3d':{'loan', 'loan_agreement', 'opportunity_compliance_flag','zodiac'}
}
pub_plat_dict = {'loan':'src_platform.loan',
'opportunity_compliance_flag':'src_platform.opportunity_compliance_flag',
'opportunity_history':'src_platform.opportunity_history',
'loan_agreement': 'src_platform_mosaic_live.loan_agreement'}
Function
def update_dict(parent_dict):
for tbls in parent_dict.values():
for tbl in tbls:
if tbl.find(".") != -1:
pass
else:
try:
update = pub_plat_dict[tbl]
tbls.remove(tbl)
tbls.add(update)
except:
pass
return(parent_dict)
Output
{'49d238407e0102ba': {'src_platform.opportunity_history'}, 'f9d53c74ec1d2ff6': {'src_platform.loan', 'src_platform.loan_disbursement', 'servicer.trial_balance'}, 'fc35a98e0cfaab3d': {'opportunity_compliance_flag', 'loan_agreement', 'loan', 'zodiac'}}
NOTE: the first item is updated correctly but everything else is left unchanged.
I did the following loop to try to figure out my error (keeping it as close to the update_dict code as I could).
for tbls in parent_dict.values():
for tbl in tbls:
if tbl.find('.') != -1:
print("UNCHANGED-" + tbl)
else:
try:
print("CHANGED-" + pub_plat_dict[tbl])
except:
print("FAILURE-"+ tbl)
It gives me the following output:
UNCHANGED-src_platform.opportunity_history
UNCHANGED-src_platform.loan
UNCHANGED-src_platform.loan_disbursement
UNCHANGED-servicer.trial_balance
CHANGED-src_platform.opportunity_compliance_flag
CHANGED-src_platform_mosaic_live.loan_agreement
CHANGED-src_platform.loan
FAILURE-zodiac
Aside from the capitalized- word this is what I would expect the parent_dict would now look like. So my .remove and .add aren't working consistently.
EDIT: I also substituted .discard for .remove, the output did not change.
Any assistance would be greatly appreciated.
I couldn't get the function to work as I created it. Part of the issue is where the return statement appears. Using a return inside of a loop will break it and exit the function even if the iteration is still not finished. Another issue might be the redundant logic in the function.
I decided to create a new dictionary and use a list as the dict's values instead of sets. I simplified the logic in the function and got rid of the if statement which seemed redundant in light of the try clause.
from collections import defaultdict
cln_parent_dict = defaultdict(list)
def update_dict(parent_dict):
for key in parent_dict:
for value in parent_dict[key]:
try:
cln_parent_dict[key].append(pub_plat_dict[value])
except:
cln_parent_dict[key].append(value)
return(cln_parent_dict)
when I run the function I get what I expect:
Function Output
defaultdict(<class 'list'>, {'49d238407e0102ba': ['src_platform.opportunity_history'], 'f9d53c74ec1d2ff6': ['servicer.trial_balance', 'src_platform.loan_disbursement', 'src_platform.loan'], 'fc35a98e0cfaab3d': ['zodiac', 'src_platform_mosaic_live.loan_agreement', 'src_platform.opportunity_compliance_flag', 'src_platform.loan']})
Overall the change seems to work for the 100K items in the dataset.
Thanks to everyone for taking a look.

Indexes and ranges in python

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

Saving ord(characters) from different lines(one string) in different lists

i just can't figure it out.
I got a string with some lines.
qual=[abcdefg\nabcedfg\nabcdefg]
I want to convert my characters to the ascii value and saves those values in an other list for each line.
value=[[1,2,3,4,5,6],[1,2,3,4,5,6],[1,2,3,4,5,6]
But my codes saves them all in one list.
values=[1,2,3,4,5,6,1,2,3,4,5,6,1,2,3,4,5,6]
First of all my code:
for element in qual:
qs = ord(element)
quality_code.append(qs)
I also tried to split() the string but the result is still the same
qual=line#[:-100]
qually=qual.split()
for list in qually:
for element in list:
qs = ord(element)
quality.append(qs)
My next attempt was:
for element in qual:
qs = ord(element)
quality_code.append(qs)
for position in range(0, len(quality_code)):
qual_liste[position].append(quality_code[position])
With this code an IndexError(list index out of range) occurs.
There is probably a way with try and except but i dont get it.
for element in qual:
qs = ord(element)
quality_code.append(qs)
for position in range(0, len(quality_code)):
try:
qual_liste[position].append(quality_code[position])
except IndexError:
pass
With this code the qual_lists stays empty, probably because of the pass
but i dont know what to insert instead of pass.
Thanks a lot for help. I hope my bad english is excusable .D
Here you go, this should do the trick:
qual="abcdefg\nabcedfg\nabcdefg"
print([[ord(ii) for ii in i] for i in qual.split('\n')])
List comprehension is always the answer.

Why am I getting an index out of range in my code?

Here is my code for part of a connect 4 program:
def place_piece(n,column):
col=int(column)
boardlist=[['.'*42]]
for l in range(7):
if boardlist[col+42-7l]=='.':
if n%2==0:
piece=X
else:
piece=O
boardlist[col+7(6-l)]=piece
break
return boardlist
print(place_piece(1,3))
When I run it, line 5 if boardlist[col+42-7l]=='.': has an index out of range error. Why? And how could I fix this?
An index out of range error means that the index of the array you are referring to doesn't exist. This is how you declared boardlist:
boardlist=[['.'*42]]
In this case, boardlist itself only contains one element, which happens to be another array. Thus, the only viable index would be boardlist[0]. Based on the code you posted, I would suggest changing it to this:
boardlist=['.']*42
Your col+42-7l is more than len(boardlist) - 1 at some point in your loop. As simple as that.

Resources