I'm writing a code to factor the number 600851475143 (my teacher must be mad at us). It runs normally up to position 10007 and even gives the primes 71 and 6857, but gives the error below the code below this message after that.
numero = 600851475143 #number
primos = [2,...,104729] # here is a list of 10000 primes that stackoverflow wouldn't let me insert
# ^ primes
ponteiro = 0 # pointer
cont = primos[0]
primos_usados = [] #used primes
while True:
print(f"{ponteiro} - {cont} {numero}\n{primos_usados}") # to see the values per loop
if(numero%primos[cont] == 0):
numero = numero/primos[cont]
primos_usados.append(primos[cont])
ponteiro = 0
if(numero/primos[cont] == 1):
break
ponteiro += 1
cont = primos[ponteiro]
error:
if(numero%primos[cont] == 0):
IndexError: list index out of range
I manually tried to access the value primos[9999] but got the same error. how do I do this without having to either this error occur or I have to put 10000 numbers in a list?
Related
I am trying to create a program that takes only even numbers from a range of numbers from 1 to 100 and add all of the even numbers. I am a beginner and I have been trying to get this working since yesterday, and nothing I have tried works. This is my first post, so sorry if the format is wrong but here is my code.
for i in range(1, 100):
if i % 2 == 0:
x = [I]
y = sum(x)
print(y)
The problems with your code has multiple issues that - 1)if you want to get all even numbers from 1 to 100, your range should be (1, 101); 2) the way you build list is wrong (syntax); 3) the sum expect an iterable (list).
There are a few ways to accomplish this sum from 1 to 100 (inclusive), here it will start with yours, and try to show List Comprenshion and Generator Expression way:
lst = [] # to store the build-up list
tot = 0 # to store the answer
for i in range(1, 101):
if i % 2 == 0: # it's a even number
lst.append(i) # store it into lst
tot = sum(lst) # 2550
Generator expression:
all_evens_sum = sum(x for x in range(1, 101) if x % 2 == 0) # 2550
Or List Comprehension:
lst = [x for x in range(1, 101) if x % 2 == 0] # even nums
total = sum(lst) # 2550
I am a beginner too but it looks I can help you some.
for i in range(1, 100):
if(i % 2 == 0):
sum += i
print(sum) // do what you want
Given two integers m, n (1 <= m <= n) find all integers between m and n whose sum of squared divisors is itself a square. 42 is one such a number.
Code works correctly on sample inputs but it is rejected by automatic code checker and reports timeout error and asks to optimize the code...
while m < n :
list_divisors = []
temp_list = []
total = 0
for number in range (m+1) :
if m%(number+1) == 0 :
list_divisors.append(number+1)
for number in list_divisors :
total+= number*number
Codewars does not show what test cases it is failing for. It just shows Execution Timed Out (12000 ms) error. Below test cases passed during sample check.
Test.assert_equals(list_squared(1, 250), [[1, 1], [42, 2500], [246, 84100]])
Test.assert_equals(list_squared(42, 250), [[42, 2500], [246, 84100]])
Test.assert_equals(list_squared(250, 500), [[287, 84100]])
Try this based on your code. No data gets stored in a list. Total is the sum of squared of whole divisors. Then, if square-root of that total is a whole number, return the list.
import math
def list_squared(number):
total = 0
for x in range(1, number+1):
if number % x == 0:
total += x*x
bounds = math.sqrt(total)
if math.ceil(bounds) == math.floor(bounds):
return [number, total]
else:
return False
def all_numbers(start, end):
numbers = []
for x in range(start, end+1):
data = list_squared(x)
if data != False:
numbers.append(data)
return numbers
x = all_numbers(1, 10000)
print(x)
1..10000 checks takes 4.7s. I am sure it can be optimized further. Does this help you?
Even faster
Switching these two lines:
total = 0
for x in range(1, number+1):
with
total = 1 + number*number
for x in range(2, math.ceil((number+1)/2)):
will cut down your runtime to around half.
Even faster..er
def list_squared(number):
total = 0
x = 1
while x <= math.sqrt(number):
if number % x == 0:
if (number/x == x) :
total += x*x
else :
total += x*x + (number/x)*(number/x)
x += 1
bounds = math.sqrt(total)
if math.ceil(bounds) == math.floor(bounds):
return [number, total]
else:
return False
If you were to change list_squared a bit to loop through only square root of the number, you will get a runtime of half a second. The idea behind it is https://www.geeksforgeeks.org/find-divisors-natural-number-set-1/.
Let's take 42 as the number. Square root is 6.48. Let's just use 6. Start with 1. 42 is divisible by 1. 42 is also divisible by the result the division, which is 42.
Go to 2. 42 is divisible by 2. The result is 21. So, 21 is also a whole divisor. Repeat that through 6 and you've covered all divisors for 42. That cuts your runtime to sqrt(n) instead of half.
It looks like you never update the values of m or n. So if m < n is True on the first iteration of your loop, it will always be True and your while loop will be infinite. This would explain the timeout, probably because Codewars stops your code from executing if it hasn't finished after 12000ms.
To remedy this, you will have to update either m or n inside your while loop so that eventually the condition m < n evaluates to False, at which point your code will "drop through" the while loop.
I am new to coding and so the following code I wrote may be incorrect or sub-optimal. However, the problem I have is that I do not understand the input and thus cannot get the code to run (I only tested it with custom inputs).
The essence of the problem is that you have some sequence of numbers and you want to arrange the sequence monotonically (nondecreasing or nonincreasing). You do this by a random shuffle. How many shuffles does it take for you to get to the monotonic sequence via a random shuffle? You can find the problem here and here is my code below:
#!/bin/python3 ------ The following import is given in the prompt
import os
import sys
# Complete the solve function below. Here is my code below
def solve(P):
P.sort()
correct = P
count = []
i = 0
# Here I am trying to calculate the number of ways to get the desired monotonic sequence
# I count the number of repeated numbers in the sequence as separate items in a list
for j in range(i,len(correct)):
if correct[i] != correct[j] or i == len(correct) - 1:
count.append(j-i)
i = j
j = len(correct)
else:
j = j + 1
summ = 0
for k in range(len(count)):
summ = summ + count[k]
if summ == len(correct):
i = len(correct)
poss = [1]*len(count)
for k in range(len(count)):
for l in range(1,count[k]+1):
poss[k] = poss[k]*l
possible = 1
for x in poss:
possible = possible * x
# This is calculating the number of different permutations of n distinct elements
total = 1
n = len(correct)
for i in range(1,n+1):
total = total * i
# Calculating the probability to the 6th decimal place
probability = float(possible / total)
expected = round(1/probability, 6)
print(expected)
# The following code is given in the prompt to input the test cases
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
P_count = int(input())
P = list(map(int, input().rstrip().split()))
result = solve(P)
fptr.write(str(result) + '\n')
fptr.close()
In my code, I just assumed that P is the sequence of numbers you receive from the input.
I am trying to run a small casino roulette betting outcome simulator. As a result I want to understand how big of a bank the casino should have in order not to go bankrupt in relation to the players betting size.
Please see code below:
from random import choices
bankroll = 500
bet = 50
lose = -50
population = [bet, lose]
weights = [0.4865, 0.5135]
game_count = 1
winning_game_count = []
bankrupt_game_count = []
for i in range(10000):
while bankroll != 0 and game_count < 5000:
result = int(choices(population, weights)[0])
bankroll -= result
game_count += 1
if game_count > 4999:
winning_game_count.append('won')
elif bankroll == 0:
bankrupt_game_count.append('lost')
print(winning_game_count)
print(bankrupt_game_count)
I am getting the result of the last iteration only, whereas I want to get the total sum of all games (5000 games) and the number of games where bankroll resulted in 0. I am lost.
You only get the result of the last iteration because you only run 1 iteration.
You need to reset the variables that control your loop condition between each iteration:
for i in range(10000):
bankroll=500
game_count = 1
while bankroll != 0 and game_count < 5000:
I am trying to solve this problem on HackerRank which requires you to sort a list of integers and find how many times a number was moved in order to place in the correct ascending order (bribes within the context of the problem).
My code passes 8 of the 12 test cases but fails when the input is too large with a timeout error. This seems to be a common indicator on HackerRank that the code is too slow for the problem at hand. So is there a way to optimize this code so that it runs faster on larger data sets?
def minimum_bribes(queue):
"""Returns the minimum number of bribes people in a queue accepted."""
# Variable to keep track of bribes
bribes = 0
# Check if queue is too chaotic
for i in queue:
index = queue.index(i)
if i - index > 3:
return "Too chaotic"
# Use a bubble sort to find number of bribes
for i in range(len(queue) - 1):
for j in range(len(queue) - 1 - i):
if queue[j] > queue[j + 1]:
queue[j], queue[j + 1] = queue[j + 1], queue[j]
bribes += 1
return bribes
# Number of test cases
t = int(input())
results = []
for _ in range(t):
# Number of people
n = int(input())
# Final State of queue
q = list(map(int, input().rstrip().split()))
# Add bribe counts to results array
results.append(minimum_bribes(q))
# Print results
for result in results:
print(result)
I would recommend using while loop to test the condition, if there was no swap in the previous iteration, there is no need to run a new swap iteration.
def minimumBribes(queue):
for i in queue:
index = queue.index(i)
if (i - index) > 3:
print("Too chaotic")
return
n = len(queue)
swap =0
swapped = True
j =0
while swapped:
j+=1
swapped = False
for i in range(n-j):
if queue[i] > queue[i+1]:
queue[i], queue[i+1] = queue[i+1], queue[i]
swap +=1
swapped = True
print(swap)
return swap