"for" loop x value? - python

I'm trying to get my second array to print x in increments but reset to zero once the case value changes.
Code:
array = ['2017001677', '2017001677', '2017001621', '2017001621']
array2 = ['2017001677', '2017001621']
x = 0
for case in array:
for case2 in array2:
if(case == case2):
print(case2)
print(x)
x = x + 1
Current Output:
2017001677
0
2017001677
1
2017001621
2
2017001621
3
Desired Output:
2017001677
0
2017001677
1
2017001621
0
2017001621
1
How do I accomplish this?

You can reset the counter for unique values in array by tracking the last-seen value, starting with None
array = ['2017001677', '2017001677', '2017001621', '2017001621']
array2 = ['2017001677', '2017001621']
last_case = None
for case in array:
if case != last_case:
x = 0
last_case = case
for case2 in array2:
if(case == case2):
print(case2)
print(x)
x = x + 1

Related

how do i loop over values within a for loop in python?

I have a df
1 1 2 2
2 2 1 1
I have written a function which:
takes the df in a for loop,
adds row(s) with a default value
replaces the values with another value in randomly selected cols
writes to csv
This is my code:
def add_x(df, max):
gt_w_x = df.copy()
counter = 0
for i in range(1, max):
if len(gt_w_x) != max:
counter+=1
# add new row with default value
gt_w_x.loc[-1,:] = 1
# reset index
gt_w_x = gt_w_x.reset_index(drop=True)
# how to loop over these values for x ??
x = 1
#x = 2
# assign value 'X' to x randomly selected cols on last row
gt_w_x.iloc[-1:, random.sample(list(range(gt_w_x.shape[1])), x)] = 'X'
x = str(x)
n = str(counter)
# write to file
df_path = 'test/' + x + '_' + n + '.csv'
gt_w_x.to_csv(df_path)
max = 4
add_x(df, max)
The output on my system is
test/1_1.csv
test/1_2.csv
cat test/1_1.csv
0,1.0,1.0,2.0,2.0
1,2.0,2.0,1.0,1.0
2,1.0,X,1.0,1.0
cat test/1_2.csv
0,1.0,1.0,2.0,2.0
1,2.0,2.0,1.0,1.0
2,1.0,X,1.0,1.0
3,1.0,X,1.0,1.0
How do I loop over values for x?
The desired output for x = 1 and x = 2 is
test/1_1.csv
test/1_2.csv
test/2_1.csv
test/2_2.csv
Currently, I run the function by commenting out different values for x which is suboptimal.
You can use a nested for loop. It works just like the one you have at the beginning of the function:
def add_x(df, max):
for x in range(1,3):
gt_w_x = df.copy()
counter = 0
for i in range(1, max):
if len(gt_w_x) != max:
counter+=1
# add new row with default value
gt_w_x.loc[-1,:] = 1
# reset index
gt_w_x = gt_w_x.reset_index(drop=True)
# assign value 'X' to x randomly selected cols on last row
gt_w_x.iloc[-1:, random.sample(list(range(gt_w_x.shape[1])), x)] = 'X'
n = str(counter)
# write to file
df_path = 'test/' + str(x) + '_' + n + '.csv'
gt_w_x.to_csv(df_path)
max = 4
add_x(df, max)

iterate through a list and restart index_1 at 0 if list index is out of range

I am trying to make a program where I have a list my_list_1 = [1,2,3,...] and a second list `my_list_2 = [1,2,3,...] and len(my_list_1) < len(my_list_2). I want to iterate through the lists like this:
my_list_1 = [1,2,3]
my_list_2 = [5,6,7,8,9]
result = []
for i in range(len(my_list_2)):
result.append(my_list_1[i] + my_list_2[i])
# i == 0: 1 + 5 = 6
# i == 1: 2 + 6 = 8
# i == 2: 3 + 7 = 10
# i == 3: 1 + 8 = 9
# i == 4: 2 + 9 = 11
""" what I want to happen is when i > len(my_list_1), instead of giving a index out of range
error, I want the loop to start at the beginning if the smaller list"""
I tried something like this:
for i in range(len(my_list_2)):
if i % (len(my_list_1) - 1) == 0 or i == 0:
x = 0
else:
x+=1
result.append(my_list_1[x] + my_list_2[i])
or
for i in range(len(my_list_2)):
if x == (len(my_list_1) - 1) or i == 0:
x = 0
else:
x += 1
result.append(my_list_1[x] + my_list_2[i])
this works but I am looking for something a bit more elegant and possibibly even making a copy of my_list_1 and extend it to the length of my_list_2 so that it would look like this:
>>> my_list_1 = [1,2,3]
>>> my_list_2 = [5,6,7,8,9]
>>> extend_list(my_list_1, len(my_list_2))
[1,2,3,1,2]
You can also use itertools.cycle to create a cyclical list iterator, and use zip for the iterator and the other list.
from itertools import cycle
my_list_1 = [1,2,3]
my_list_2 = [5,6,7,8,9]
# I use list comprehension here
result = [ a + b for a, b in zip(cycle(my_list_1), my_list_2) ]
print(result)
# [6, 8, 10, 9, 11]
You just need modulo for the first index:
for i in range(len(my_list_2)):
x = i % len(my_list_1)
result.append(my_list_1[x] + my_list_2[i])

I am trying to solve the hacker rank problem. I am still a beginner and I don't know where I went wrong with Python 3

THIS IS THE QUESTION:
Given an array of integers, find and print the maximum number of integers you can select from the array such that the absolute difference between any two of the chosen integers is less than or equal to 1
def pickingNumbers(a):
maxi=0
for i in a:
x=a.count(i)
y=a.count(i-1)
x=x+y
if x>maxi :
maxi=x
print(maxi)
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
a = list(map(int, input().rstrip().split()))
result = pickingNumbers(a)
fptr.write(str(result) + '\n')
fptr.close()
given input:
6
4 6 5 3 3 1
expected output: 3
my output: None
You printed the value of maxi at the end of pickingNumbers instead of returning it.
As you don't explicitely return a value, your function returns None, which get converted to the string 'None' in str(result)
Just replace it:
def pickingNumbers(a):
maxi = 0
for i in a:
x = a.count(i)
y = a.count(i-1)
x = x+y
if x > maxi :
maxi = x
return maxi
and you should be fine...

Summing results from a monte carlo

I am trying to sum the values in the 'Callpayoff' list however am unable to do so, print(Callpayoff) returns a vertical list:
0
4.081687878300656
1.6000410648454846
0.5024316862043037
0
so I wonder if it's a special sublist ? sum(Callpayoff) does not work unfortunately. Any help would be greatly appreciated.
def Generate_asset_price(S,v,r,dt):
return (1 + r * dt + v * sqrt(dt) * np.random.normal(0,1))
def Call_Poff(S,T):
return max(stream[-1] - S,0)
# initial values
S = 100
v = 0.2
r = 0.05
T = 1
N = 2 # number of steps
dt = 0.00396825
simulations = 5
for x in range(simulations):
stream = [100]
Callpayoffs = []
t = 0
for n in range(N):
s = stream[t] * Generate_asset_price(S,v,r,dt)
stream.append(s)
t += 1
Callpayoff = Call_Poff(S,T)
print(Callpayoff)
plt.plot(stream)
Right now you're not appending values to a list, you're just replacing the value of Callpayoff at each iteration and printing it. At each iteration, it's printed on a new line so it looks like a "vertical list".
What you need to do is use Callpayoffs.append(Call_Poff(S,T)) instead of Callpayoff = Call_Poff(S,T).
Now a new element will be added to Callpayoffs at every iteration of the for loop.
Then you can print the list with print(Callpayoffs) or the sum with print(sum(Callpayoffs))
All in all the for loop should look like this:
for x in range(simulations):
stream = [100]
Callpayoffs = []
t = 0
for n in range(N):
s = stream[t] * Generate_asset_price(S,v,r,dt)
stream.append(s)
t += 1
Callpayoffs.append(Call_Poff(S,T))
print(Callpayoffs,"sum:",sum(Callpayoffs))
Output:
[2.125034975231003, 0] sum: 2.125034975231003
[0, 0] sum: 0
[0, 0] sum: 0
[0, 0] sum: 0
[3.2142923036024342, 4.1390018820809615] sum: 7.353294185683396

Panda dataframe not updating all columns

I am running the following test code to map violations to nearby buildingIDs by "NearVicinity" and "MidVicinity". The results come out unexpected and I am not sure what I am missing in my code.
So the results I get seem to have correctly updated 'TicketIssuedDT' and 'NearVicinity', 'MidVicinity' colunns however the 'BuildingID' and 'X' columns only map correctly to result['X'][0] and result['BuildingID'][0]. All remaining 999 rows have 0 for 'BuildingID' and 'X'.
result = pd.DataFrame(np.zeros((1000, 5)),columns=['BuildingID', 'TicketIssuedDT', 'NearVicinity', 'MidVicinity','X'])
z = 0
for i in range(0,10):
#for i, j in dataframe2.iterrows():
dataframe2Lat = dataframe2['Latitude'][i]
dataframe2Long = dataframe2['Longitude'][i]
for x in range(0,11102):
#for x, y in dataframe1.iterrows():
dist = (math.fabs(dataframe2Long - dataframe1['Longitude'][x]) + math.fabs(dataframe2Lat - dataframe1['Latitude'][x]))
if dist < .02:
result['X'][z] = x
result['BuildingID'][z] = dataframe1['BuildingID'][x]
result['TicketIssuedDT'][z] = dataframe2['TicketIssuedDT'][i]
result['MidVicinity'][z] = 1
if dist < .007:
result['NearVicinity'][z] = 1
else:
result['NearVicinity'][z] = 0
z += 1
print(i)

Categories

Resources