In my def getLotteryGame(): Which is suppose to check if the timer runs out and if it does it sorts the players, ranks them, gives them their winnings and stores a note for them and then return True and when it returns True the bot reloads the game making a new round. I tried several ways of trying to get it to return True. This is the code:
def getLotteryGame():
global pot
global players
different = float(time.time() - lotteryStart)
years = int(different / Point.YEAR)
days = int((different % Point.YEAR) / Point.DAY)
hours = int((different % Point.DAY) / Point.HOUR)
mins = int((different % Point.HOUR) / Point.MINUTE)
secs = int(different % Point.MINUTE)
if secs <= 0:
if len(players) > 0:
random.shuffle(players)
ratios = []
for i in range(-2, len(players) - 2) if i > 0 else range(len(players)):
if i < 0:
ratios.append(1 - (i * 0.33)) # ratio > 1
else:
ratios.append(1 / (1 + (i * 0.33))) # ratio <= 1
winnings = [pot * r for r in ratios]
for m in range(1, len(players)):
notes.store("~lottery~", players[m], "The system has placed you "+Point.ordinal(m)+" in the lottery. The lottery awarded you "+winnings+" P$", time.time())
alerts.append(players[m])
winnings = int(winnings)
point = Point.dPoint[players[m]]
point = int(point)
point = int(point+winnings)
Point.dPoint[players[m]] = int(point)
return(True)
elif len(players) == 0:
return(True)
else:
return(False)
When I wait for the difference to go <= 0 for if secs <= 0. It keeps returning False instead and I'm not sure why.
Your code logic is brokem. lotteryStart is defined when the code first runs, as time.time(). Later, you find the number of seconds since lotteryStart. This number of seconds, might be zero occasionally, and is never going to be less than zero. Since time moves forward, it should always be positive. Thus your code always executes the final else statement that returns False.
different = float(time.time() - lotteryStart)
Maybe lotteryStart is a global variable as well as it is not defined anywhere?
Related
I am practicing on CodingBat and trying the below question:
We want to make a row of bricks that is goal inches long. We have a number of small bricks (1 inch each) and big bricks (5 inches each). Return True if it is possible to make the goal by choosing from the given bricks.
Test cases:
make_bricks(3, 1, 8) → True
make_bricks(3, 1, 9) → False
make_bricks(3, 2, 10) → True
make_bricks(7, 1, 13) → False
make_bricks(1, 4, 12) → False
When I run on my code on code editor(VSCode), I pass every test cases but when I do submit on the CodingBat(https://codingbat.com/prob/p118406) I am getting and error as Time out. Please can anyone explain me why or is there any error in my code below:
def make_bricks(small, big, goal):
myNum = 5
result = 0
i = 1
for i in range(big+1):
if (i * myNum) == goal:
return True
elif (i * myNum) > goal:
result = ((i * myNum) - myNum)
elif (i * myNum) < goal:
result = (i * myNum)
for i in range(small + 1):
if result + i == goal:
return True
return False
print(make_bricks(20, 0, 19))
You can calculate this without loops. It's the loops that are taking too much time. Some simple arithmetic and a couple of quick early checks should solve this issue:
def make_bricks(small, big, goal):
big_ = big * 5
max_ = big_ + small
if goal > max_:
return False # impossible
if goal == max_:
return True # simple case - just use all the bricks
if big_ > goal:
big_ = goal // 5 * 5
return big_ + small >= goal
The time out happens in this test case:
make_bricks(2, 1000000, 100003)
That's probably because it's taking to much time to process the test case. In the test case above, the code is iterating over one million times, and in each iteration it's multiplying numbers and storing the result into result for no use in the first 999.999 loops:
elif (i * myNum) < goal:
result = (i * myNum)
You can do the calculations whithout a loop:
def make_bricks(small_bricks_available, big_bricks_available, goal):
big_brick_size = 5
small_brick_size = 1
if goal < big_brick_size:
return small_bricks_available >= goal
big_bricks_needed = goal // big_brick_size
if big_bricks_needed > big_bricks_available:
big_bricks_needed = big_bricks_available
goal -= big_bricks_needed * big_brick_size
small_bricks_needed = goal // small_brick_size
# the first comparison is not necessary, but I left it for clarity
return big_bricks_available >= big_bricks_needed and small_bricks_available >= small_bricks_needed
I'm pretty new to python and I spent a couple hours on a simple project that involves prime numbers. I need to interpret a timer to count the delay of how long it takes to find x amount of prime numbers and give me back that delay in the form of a message box. Here is what I have so far for the project and it works perfectly fine.
import time
import ctypes
lower = 1
upper = 25000000
z = 1
while z < 1000:
if z == 100:
break
for num in range(lower, upper + 1):
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
z += 1
print(z, ": ", num)
As far I understood, you want to calculate how much time you need to calculate z number of prime number.
You can simply start a timer at the beginning of the program and subtract it at the end.
import time
def is_prime(x):
if x%2 == 0:
return False
for i in range(3, x, 2):
if x%i == 0:
return False
return True
start_time = time.time()
z = 1
i=3
while True:
if z == 3000:
break
if is_prime(i):
z += 1
i += 1
delay = time.time() - start_time
print('Delay: ', delay)
Delay: 1.3431673049926758
I need to understand the complexity of the following code. I am familiar with the concepts of all the Big O() notation and also have read a lot of blogs but I cant figure how to apply to big programs.
Following is the code for largest pallindrome number from 100 to 999:
def isPaindrome(number):
stringNum = str(number)
firstDigit_index,lastDigit_index=0,len(stringNum)-1
isPalindrome = False
while(lastDigit_index > 0 and firstDigit_index < lastDigit_index):
#print(stringNum[f],"==",stringNum[l],"......")
if(stringNum[firstDigit_index]==stringNum[lastDigit_index]):
isPalindrome = True
else:
isPalindrome = False
break
firstDigit_index = firstDigit_index + 1
lastDigit_index = lastDigit_index - 1
if(isPalindrome):
return number
else:
return 0
max = 0
startRange = 100
endRange = 999
for i in range(endRange*endRange,startRange*startRange,-1):
factors = []
result = isPaindrome(i)
if(result!=0):
for i in range(startRange,endRange+1):
if(result%i==0):
factors.append(i)
if(len(factors)>1):
sumFactor = factors[(len(factors))-1] + factors[(len(factors))-2]
mul = factors[(len(factors))-1] * factors[(len(factors))-2]
if(sumFactor>max and mul==result):
max = sumFactor
print("Largest Palindrome made from product of two 3 digit numbers(",factors[(len(factors))-1],",",factors[(len(factors))-2] ,") is", result,".")
If anyone could just make me understant step by step how to calculate I'd be grateful.
As I mentioned, your isPalindrome function is literally incorrect, as you're not changing the indexes. I changed a bit of your also, so this is the version I'm analysing. (I'm only analysing the isPalindrome function, since I actually couldn't understand what the main function is doing), sorry!
def isPalindrome(n):
num = str(n)
head, tail = 0, len(num) - 1
while tail > head:
if num[head] != num[tail]: # Not symmetrical!! WARNING!
return False
head += 1 # move position
tail -= 1 # move position
return True
This code on average is O(|n|) i.e. O(log N) where N is the number. This is because on average, the if comparison has 50% chance of breaking (returning False) and 50% of continuing. Therefore the expected number of comparisons would be |n|/4 which is O(|n|).
I'm trying to create a basic code to simulate stock market behavior as an exercise in my programming class. It's based off of weighted randomness and is displayed through pylab.
For the most part it looks good, but for no matter how many trials I run there seems to be a tad that does not look random. From 1-50 of each random update, there seems to be a definitive upwards trend that is not reflected anywhere else in the series. The weighted values are not altered anywhere else in the code, so this trend should be an aberration seeing that I make sure that the results given are the average of a great many trials. Would anyone know what's wrong with my code that causes this to happen? Thanks!
class Simulation(object):
def __init__(self, netPos=300, downChance=.1, downTrend=.06, start = 1285.85, time = 0, recession = False):
self.netPos = netPos
self.downChance = downChance
self.downTrend = downTrend
self.value = start
self.time = time
self.recession = False
def getValue(self):
return self.value
def update(self):
if not self.recession:
if random.random() < self.downTrend:
self.recession = True
if random.random() > self.downChance:
self.value += random.random() * self.netPos
else:
self.value -= random.random() * self.netPos
else:
if random.random() < self.downTrend:
self.recession = False
if random.random() < self.downChance:
self.value += random.random() * self.netPos
else:
self.value -= random.random() * self.netPos
times = 5000
values = []
for i in range(1200):
values += [0]
for x in range(times):
runOnce = Simulation()
for y in range(1200):
values[y] += runOnce.getValue()
runOnce.update()
for i in range(1200):
values[i] = values[i] / times
def plottem(x,y):
pylab.plot(range(1200), values[x:y-1], label="Trend")
pylab.title("Simulated Trend")
pylab.xlabel("Time")
pylab.ylabel("Relative Value")
pylab.legend(loc = 1)
pylab.show()
def getChange(x,y):
print (values[x] - values[y-1])/(x-y-1)
plottem(0,1999)
Results:
This is entirely expected. You've run a bunch of simulations that all start with an upward trend and averaged their results. Since they all start with an uptick, the average starts with an uptick. After that, they go out of phase, and the average doesn't have much of a trend.
I recently started messing around with python and I wrote a program to print out the 1000th prime number but the output only shows a blinking cursor , the code is shown below:
number = 3
count= 1
while count <= 1000:
prime = True
for x in range(2, number):
if number % x == 0:
prime= False
if prime == True:
count = count + 1
if count <= 1000:
number = number + 1
print number
Any help and concise explanation would be appreciated
edit: i just realized the problem. #tichodroma solved the problem but did so by editing the OP post. so when i got to it it was already solved, how ever, he solved it by putting the print into the loop, hence the many numbers waterfall. but it should be outside the loop so as to only show the final result. also - after looking at the OP code before edit, it was written in such a way that it was taking a long time to run, and the "blinking line" was the system working in the background
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
counter = 0
number = 0
while True:
if isprime(number):
counter+=1
if counter == 10000:
break
number+=1
print number