The problem:
https://www.beecrowd.com.br/judge/problems/view/1032
I can't get the numbers out of the people list, this method I did gives the error "pop index out of range".
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# PRIME LIST
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
from audioop import reverse
numerosPrimos = 3501
primos = []
for i in range(2, numerosPrimos + 1):
for j in range(2, int(i ** 0.5) + 1):
if i % j == 0:
break
else:
primos.append(i)
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# PEOPLE LIST
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
numeroPessoas = int(input())
pessoas = []
for l in range(1, numeroPessoas + 1):
pessoas.append(l)
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# REMOVING PEOPLE
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
# pessoasEliminada = pessoas
p = primos[0]
pessoas.sort(reverse=True)
mult = 1
while len(pessoas) >= 1 and p <= 3501:
pessoas.pop(len(pessoas) - p)
print(pessoas)
p = p + p
Related
Is there any way to improve the performance of below python code.
I tried list comprehension, but not sure how to implement it on below scenario.
*In below code, intcons is a dataframe
p = [[0 for i in range(30)] for j in range(5)]
violate = [[ 0 for i in range(8)] for j in range(4)]
mm = []
intcons['first.store_id'] = ((intcons.store_id != intcons.store_id.shift()))
for i in intcons.index:
if intcons['first.store_id'][i] == True:
addit = 1
for q in range(1, 6):
intcons[f'f{q}'] = 0
p[1][q] = 0
p[3][q] = 0
mm[1] = 1
mm[2] = np.log(intcons['K1'])
mm[3] = np.log(intcons['K2'])
mm[4] = np.log(intcons['K3'])
mm[5] = np.log(intcons['K4'])
intercep = 1
for er in range(6, 10):
for j in range(1, 5):
p[er][j] = 0
if er == j + 5:
p[er][j] = 1
for hh in range(1, 4):
for z in range(1, 2):
violate[hh][z] = 0
print(i)
else:
addit = addit + 1
I am dumbfounded right now, I have some code that works generating an array of data and operating on it.
I am trying to sample random sections from my code, in order to check the calculations I am doing.
I have done this before and it has worked fine. I
target_sample =[1,2,10,25,83,62]
df, s_array_track ,z_array_track = MonteCarloValuationAntithetic(df,target_sample)
#df,z,s_array,lookback_scenario = MonteCarloValuation(df)
target_sample =[1,2,10,25,83,62]
lookback = []
for i in range(n_samples):
s = df["current_index"][i]
s_max = df["max_index"][i]
t = df["time to maturity_Months"][i]
sigma = df["volatility"][i]
cap = df["cap_rate"][i]
r = df["interest_rate"][i]
z = np.zeros((int(index_crediting_term*12)+1,n_scenarios))
s_array_track=np.zeros((len(target_sample),int(index_crediting_term*12)+1,n_scenarios))
z_array_track = np.zeros((len(target_sample),int(index_crediting_term*12)+1,n_scenarios))
df_track = df
s_start = df['initial_index'][i]
s_array = np.zeros((int(index_crediting_term*12)+1,n_scenarios))
for k in range(int(n_scenarios/2)):
for j in range(int(t)+1):
drift =( r - .5 *(sigma**2)) * (1/12)
z[j][k] = np.random.normal(0, 1)
diffusion = sigma* z[j][k] * (np.sqrt(1/12))
if j == 0:
s_array[j][k] = s
if (0 < j) and (j < t):
s_array[j][k] = s_array[j-1][k]*np.exp(drift + diffusion)
if j==t:
s_array[j][k] = s_max
else:
continue
for k in range(int(n_scenarios/2),int(n_scenarios)):
for j in range(int(t)+1):
drift =( r - .5 *(sigma**2)) * (1/12)
z[j][k] = -z[j][int(k-n_scenarios/2)]
diffusion = sigma* z[j][k] * (np.sqrt(1/12))
if j == 0:
s_array[j][k] = s
if (0 < j) and (j < t):
s_array[j][k] = s_array[j-1][k]*np.exp(drift + diffusion)
if j == t:
s_array[j][k] = s_max
else:
continue
if i in target_sample:
print(str(i) + " is in Target")
h = target_sample.index(i)
print(str(h))
s_array_track[h] = s_array
z_array_track[h] = z
lookback_temp = max(0,np.mean(np.clip(np.max(((s_array[:][:] / s_start)-1) ,axis =0 ),None,cap))))
lookback.append(lookback_temp)
df["Lookback"] = lookback
I am not getting the results I am expecting. When I do
s_array_track[h] = s_array
Outside of the code it works as expected. What is going on in my loop? I have spent hours on this and I am really confused as to why its not working.
I would like to implement the above mentioned algorithm in Python. Time Complexity of Dijkstra's Algorithm is O(V2), but I would like to implement it using min-priority queue so it drops down to O(V+ElogV).
Heres an example input:
The program should 2 problems, src: 0 dest: 2 and src: 1 dest: 2. 3 vertexes will be provided by the input and there will be 3 edges provided also, all of these are separated by an empty line.
2
3
3
0 2
1 2
2 0
-4 1
6 3
1 0
1 2
0 2
Solution:
5.0 10.2
Heres my current code:
import math
import sys
def build_graph(edges, weights, e):
graph = edges
for i in range(e):
graph[i].append(weights[i])
return graph
def debug():
print(pontparok)
print(csucsok)
print(utszakaszok)
print(hosszak)
def read(n, bemenet):
for i in range(n):
temp = input().split("\t")
bemenet[i] = temp
bemenet[i][0] = int(bemenet[i][0])
bemenet[i][1] = int(bemenet[i][1])
def dijkstra(edges, src, dest, n):
dist = [0] * n
current = src
for i in range(n):
dist[i] = sys.maxsize
dist[src] = 0
explored = [False] * n
q = 0
while not explored[dest] and q < 1000:
q += 1
min = sys.maxsize
minVertex = current
for edge in edges:
if edge[0] == current and not explored[edge[1]]:
if min > dist[edge[1]]:
min = dist[edge[1]]
minVertex = edge[1]
elif edge[1] == current and not explored[edge[0]]:
if min > dist[edge[0]]:
min = dist[edge[0]]
minVertex = edge[0]
current = minVertex
explored[current] = True
for edge in edges:
if edge[0] == current:
if dist[current] + edge[2] < dist[edge[1]]:
dist[edge[1]] = dist[current] + edge[2]
elif edge[1] == current:
if dist[current] + edge[2] < dist[edge[0]]:
dist[edge[0]] = dist[current] + edge[2]
return round(dist[dest], 2)
p = int(input())
n = int(input())
e = int(input())
input()
pontparok = [[0] * 2] * p
csucsok = [[0] * 2] * n
utszakaszok = [[0] * 2] * e
hosszak = [0] * e
read(p, pontparok)
input()
read(n, csucsok)
input()
read(e, utszakaszok)
for i in range(e):
hosszak[i] = math.sqrt(pow((csucsok[utszakaszok[i][0]][0] - csucsok[utszakaszok[i][1]][0]), 2) + pow((csucsok[utszakaszok[i][0]][1] - csucsok[utszakaszok[i][1]][1]), 2))
#debug()
graph = build_graph(utszakaszok, hosszak, e)
#print(hosszak)
for i in range(p):
if i == p - 1:
print(dijkstra(graph, pontparok[i][0], pontparok[i][1], n))
else:
print(dijkstra(graph, pontparok[i][0], pontparok[i][1], n), end="\t")
import heapq
import math
def read(n, bemenet):
for i in range(n):
temp = input().split("\t")
bemenet[i] = temp
bemenet[i][0] = int(bemenet[i][0])
bemenet[i][1] = int(bemenet[i][1])
def dijkstra(graph, starting_vertex, destination_vertex):
distances = {vertex: float('infinity') for vertex in graph}
distances[starting_vertex] = 0
pq = [(0, starting_vertex)]
while len(pq) > 0:
current_distance, current_vertex = heapq.heappop(pq)
for neighbor, weight in graph[current_vertex].items():
distance = current_distance + weight
if distance < distances[neighbor]:
distances[neighbor] = distance
heapq.heappush(pq, (distance, neighbor))
return round(distances[destination_vertex], 2)
def build_graph(edges, weights, e):
graph = edges
for i in range(e):
graph[i].append(weights[i])
return graph
p = int(input())
n = int(input())
e = int(input())
input()
pontparok = [[0] * 2] * p
csucsok = [[0] * 2] * n
utszakaszok = [[0] * 2] * e
hosszak = [0] * e
read(p, pontparok)
input()
read(n, csucsok)
input()
read(e, utszakaszok)
for i in range(e):
hosszak[i] = math.sqrt(pow((csucsok[utszakaszok[i][0]][0] - csucsok[utszakaszok[i][1]][0]), 2) + pow((csucsok[utszakaszok[i][0]][1] - csucsok[utszakaszok[i][1]][1]), 2))
graph2 = build_graph(utszakaszok, hosszak, e)
graph = { }
[graph.setdefault(i, []) for i in range(n)]
for i in range(n):
graph[i] = {}
for edge in graph2:
graph[edge[0]].update({edge[1]: edge[2]})
graph[edge[1]].update({edge[0]: edge[2]})
for i in range(p):
if i == p - 1:
print(dijkstra(graph, pontparok[i][0], pontparok[i][1]))
else:
print(dijkstra(graph, pontparok[i][0], pontparok[i][1]), end="\t")
So I have an application in Python that calculates the variable number in the "PV = nRT" chemical equation. The code is like this:
r = 0.082
# Variables
p = float(input('Pressure = '))
p_unit = input('Unit = ')
print('_____________________')
v = float(input('Volume = '))
v_unit = input('Unit = ')
print('_____________________')
n = float(input('Moles = '))
print('_____________________')
t = float(input('Temperature = '))
t_unit = input('Unit = ')
# Unit Conversion
if p_unit == 'bar':
p = p * 0.987
if v_unit == 'cm3':
v = v / 1000
if v_unit == 'm3':
v = v * 1000
if t_unit == 'c':
t = t + 273
if t_unit == 'f':
t = ((t - 32) * (5 / 9)) + 273
# Solve Equation
def calc():
if p == 000:
return (n * r * t) / v
if v == 000:
return (n * r * t) / p
if n == 000:
return (p * v) / (r * t)
if t == 000:
return (p * v) / (n * r)
and then at the end I run the function to get the result. But the problem is I want to convert the result to a Scientific Number (e.g. 0.005 = 5 x 10^-3). I tried the solution below:
def conv_to_sci(num):
i = 0
if num > 10:
while num > 10:
num / 10
i = i - 1
if num < 10:
while num < 10:
num * 10
i = i + 1
return num + "x 10^" + i
but it didn't work. Any questions?
I'd just use numpy to get scientific notation
import numpy as np
num = 0.005
num_sc = np.format_float_scientific(num)
>>> num_sc
'5.e-03'
Use str.format
"{:.0e}".format(0.005)
This will print:
'5e-03'
Or,
def conv_to_sci(num):
i = 0
while int(num) != num:
num *= 10
i += 1
return "{0} x 10^{1}".format(int(num), i)
conv_to_sci(0.005)
Will give: '5 x 10^3'
Question source: SPOJ.. ORDERS
def swap(ary,idx1,idx2):
tmp = ary[idx1]
ary[idx1] = ary[idx2]
ary[idx2] = tmp
def mkranks(size):
tmp = []
for i in range(1, size + 1):
tmp = tmp + [i]
return tmp
def permutations(ordered, movements):
size = len(ordered)
for i in range(1, size): # The leftmost one never moves
for j in range(0, int(movements[i])):
swap(ordered, i-j, i-j-1)
return ordered
numberofcases = input()
for i in range(0, numberofcases):
sizeofcase = input()
tmp = raw_input()
movements = ""
for i in range(0, len(tmp)):
if i % 2 != 1:
movements = movements + tmp[i]
ordered = mkranks(sizeofcase)
ordered = permutations(ordered, movements)
output = ""
for i in range(0, sizeofcase - 1):
output = output + str(ordered[i]) + " "
output = output + str(ordered[sizeofcase - 1])
print output
Having made your code a bit more Pythonic (but without altering its flow/algorithm):
def swap(ary, idx1, idx2):
ary[idx1], ary[idx2] = [ary[i] for i in (idx2, idx1)]
def permutations(ordered, movements):
size = len(ordered)
for i in range(1, len(ordered)):
for j in range(movements[i]):
swap(ordered, i-j, i-j-1)
return ordered
numberofcases = input()
for i in range(numberofcases):
sizeofcase = input()
movements = [int(s) for s in raw_input().split()]
ordered = [str(i) for i in range(1, sizeofcase+1)]
ordered = permutations(ordered, movements)
output = " ".join(ordered)
print output
I see it runs correctly in the sample case given at the SPOJ URL you indicate. What is your failing case?