i have to write a function that takes as an input a list and if to Consecutive numbers have the same sighn then they both go to a same list in lists if not a new list in list is opened for example:
[2,5,-3,-1,-1,3,-2,-2]->[[2,5]],[-3,-1,-1],[3],[-2,-2]]
this is my code :
def num_8(lst):
my_lst=[[lst[0]]]
j=0
for i in range(1,len(lst)):
if (lst[i]> 0 and lst[i-1]>0) or (lst[i]<0 and lst[i-1]<0):
my_lst[j].append(lst[i])
print(my_lst)
else:
j=j+1
my_lst[j].append([lst[i]])
return my_lst
print(num_8([2,5,-3,-1,-1,3,-2,-2]))
but i keep on getting
my_lst[j].append([lst[i]])
IndexError: list index out of range
and i dont know were i get out of range :( thanks
The error is with the else part.
my_lst[j] does not exisit at that point(The len of my_lst is j -1)
So you'll have to append the first number to my_lst and not my_lst[j] (Similar to what you have done in the first line of the function)
my_lst.append([lst[i]])
Related
I have to iterate through a list using a for loop. In the list, I have to see if the number is even, and if it is, I have to add one to it, and if it is odd, I also have to add one to it. Then i have to print it.
So, the list is [1,2,3,4,5,6,7,8,9,10] and the desired output would be [2,3,4,5,6,7,8,9,10,11].
samplenumber = [1,2,3,4,5,6,7,8,9,10]
for i in samplenumber:
if i%2 == 0:
print (samplenumber+1)
else:
print (samplenumber+1)
This is my code above^^
According to your required Answers, the code will be like this:
samplenumber = [1,2,3,4,5,6,7,8,9,10]
for i in samplenumber:
j=+1
a=int(i)+ j
print (a, end=",")
I have data in the form of list of lists where I am trying to match the demand and supply such that each demand matches uniquely to one supply item.
dmndId_w_freq = [['a',4,[1,2,3,4]],['b',6,[5,6,7,8,3,4]],['c',7,[6,5,7,9,8,3,4]],['d',8,[1,6,3,4,5,6,7,10]]]
num_sims = 1
for sim_count in range(num_sims):
dmndID_used_flag = {}
splID_used_flag = {}
dmndID_splId_one_match = {}
for i in dmndId_w_freq:
if i[0] not in dmndID_used_flag.keys():
for j in i[2]:
#print j
#print "CLICK TO CONTINUE..."
#raw_input()
if j in splID_used_flag.keys():
i[2].remove(j)
dmndID_splId_one_match[i[0]] = i[2][0]
splID_used_flag[i[2][0]] = 1
dmndID_used_flag[i[0]] = 1
print
print dmndID_splId_one_match
#print splID_used_flag
#print dmndID_used_flag
#raw_input()
I would expect the output dmndID_splId_one_match to be something like {'a':1,'b':5,'c':6,'d':3}.
But I end up getting {'a':1,'b':5,'c':6,'d':6}
So I am NOT getting a unique match as the supply item 6 is getting mapped to demands 'c' as well as demand 'd'.
I tried to debug the code by looping through it and it seems that the problem is in the for-loop
for j in i[2]:
The code is not going through all the elements of i[2]. It does not happen with the 'a' and 'b' part. but starts happening with the 'c' part. It goes over 6 and 5 but skips 7 (the third element of the list [6,5,7,9,8,3,4]). Similarly, in the 'd' part it skips the 2nd element 6 in the list [1,6,3,4,5,6,7,10]. And that is why the mapping is happening twice, since I am not able to remove it.
What am I doing wrong that it is not executing the for-loop as expected?
Is there a better way to write this code?
I figured out the problem in the for loop. I am looping through i[2] and then trying to modify it within the loop. this makes it unstable.
i want to calculte the specfic numbers of words from the given sentence...words are alredy save in my dictonary and sentence is will be input from user.....
Here is my code.
from collections import Counter
Find_word= raw_input('Write Sentence:')
wordTosearch=['is', 'am']
sentence= Find_word.split()
cnt = Counter(sentence)
for k in sentence:
if k in wordTosearch:
print k, wordTosearch[k]
if cnt[wordTosearch]>1:
print "aggresive"
else:
print "Not agressive"
from collections import Counter
Find_word= raw_input('Write Sentence:')
sentence= Find_word.split()
cnt = Counter(sentence)
wordTosearch=['is', 'am']
for k in wordTosearch:
print k, cnt[k]
if all( cnt[x] > 1 for x in wordTosearch ):
print "aggresive"
else:
print "Not agressive"
I dont know what the bottom part should do though.
wordTosearch is a list of words.
The following is iterating through that list of words:
if k in wordTosearch:
print k, wordTosearch[k] # <----
where k is a word, and wordTosearch[k] is the attempt to access a list value by a string key which gives you "TypeError: list indices must be integers, not str".
You can not access list values by string indices as Python lists are "numbered" sequences
I used the split() function to convert string to a list time = time.split() and this is how my output looks like :
[u'1472120400.107']
[u'1472120399.999']
[u'1472120399.334']
[u'1472120397.633']
[u'1472120397.261']
[u'1472120394.328']
[u'1472120393.762']
[u'1472120393.737']
Then I tried accessing the contents of the list using print time[1] which gives the index out of range error (cause only a single value is stored in one list). I checked questions posted by other people and used print len(time). This is the output for that:
1
[u'1472120400.107']
1
[u'1472120399.999']
1
[u'1472120399.334']
1
[u'1472120397.633']
1
[u'1472120397.261']
1
[u'1472120394.328']
1
[u'1472120393.762']
1
[u'1472120393.737']
I do this entire thing inside a for loop because I get logs dynamically and have to extract out just the time.
This is part of my code:
line_collect = lines.collect() #spark function
for line in line_collect :
a = re.search(rx1,line)
time = a.group()
time = time.split()
#print time[1] #index out of range error which is why I wrote another for below
for k in time :
time1 = time[k]#trying to put those individual list values into one variable but get type error
print len(time1)
I get the following error :
time1 = time[k]
TypeError: list indices must be integers, not unicode
Can someone tell me how to read each of those single list values into just one list so I can access each of them using a single index[value]. I'm new to python.
My required output:
time =['1472120400.107','1472120399.999','1472120399.334','1472120397.633','1472120397.261','1472120394.328','1472120393.762','1472120393.737']
so that i can use time[1] to give 1472120399.999 as result.
Update: I misunderstood what you wanted. You have the correct output already and it's a string. The reason you have a u before the string is because it's a unicode string that has 16 bits. u is a python flag to distinguish it from a normal string. Printing it to the screen will give you the correct string. Use it normally as you would any other string.
time = [u'1472120400.107'] # One element just to show
for k in time:
print(k)
Looping over a list using a for loop will give you one value at a time, not the index itself. Consider using enumerate:
for k, value in enumerate(time):
time1 = value # Or time1 = time[k]
print(time1)
Or just getting the value itself:
for k in time:
time1 = k
print(time1)
--
Also, Python is zero based language, so to get the first element out of a list you probably want to use time[0].
Thanks for your help. I finally got the code right:
newlst = []
for line in line_collect :
a = re.search(rx1,line)
time = a.group()
newlst.append(float(time))
print newlst
This will put the whole list values into one list.
Output:
[1472120400.107, 1472120399.999, 1472120399.334, 1472120397.633,
1472120397.261, 1472120394.328, 1472120393.762, 1472120393.737]
I have a list of list, Let's say
list1 = [('A',[R]),
('B',['A','C']),
('C',['B']),
('B',[]),
('C',['D']),
('D',['C'])]
I'm trying to compare the 2nd elements of 2nd list ['A','C'] with previous list first element 'A' and the next list first element ['C']. Likewise I want to compare all the 2nd elements of a list with previous and next list's first element. What I tried so far is
for i, items in enumerate (list1):
for j in items[1]:
if len(j)>0:
if i !=0 and j == items[i-1][0]:
print(j,items[i-1][0],'equal')
if i < len(list1) and j==items[i+1][0]:
print(j,items[i+1][0],'equal')
It shows error as " tuple index out of range ". Please correct me where I am going wrong ?
The expected result is like
(A,A,equal)
(C,C,equal)
(B,B,equal)
(B,B,equal)
(D,D,equal)
(C,C,equal)
When you reference items, you need to use list1
if i !=0 and j == list1[i-1][0]:
print(j,list1[i-1][0],'equal')
if i -1 < len(list1) and j==list1[i+1][0]:
print(j,list1[i+1][0],'equal')
Not sure what if len(j)>0: is all about as j is a character. Maybe just if j:
This might be easier code to understand.
for i, row in enumerate (list1): # Use the list1[1] list as the key data
for item in row[1]: # Compare all items in this list with previous row first element
# and next row first element
if i > 0: # Previous row
if item == list1[i-1][0]:
print ('{} : {} equal'.format(item, list1[i-1][0]))
if i < len(list1) - 1: # Next row
if item == list1[i+1][0]:
print ('{} : {} equal'.format(item, list1[i+1][0]))
The correct code is below:
for i, items in enumerate(list1):
for j in items[1]:
if len(j)>0:
if i!=0 and j==list1[i-1][0]:
print(j,j,'equal')
if i+1 < len(list1) and j==list1[i+1][0]:
print(j,j,'equal')
You should be using list1, not items in the if statement.