How do I keep printing after the user has given the input? - python-3.x

from timeit import default_timer as timer
import random
num_1 = random.choice(range(12))
num_2 = random.choice(range(12))
score = 0
start = timer()
end = timer()
t = (end - start) # Time in seconds, e.g. 5.38091952400282
if t < 5 :
score += 100
if t > 5 :
score += 50
print(score)
how do i print the input again???
like after i have written what is 6 * 8 for example it gives me the score. How do i ask users for the question again???

Put the input inside the while loop:
num_1 = random.choice(range(12))
num_2 = random.choice(range(12))
score = 0
start = timer()
end = timer()
t = (end - start) # Time in seconds, e.g. 5.38091952400282
while True:
ans = input("what is "+num1" * "+num2+"?")
if t < 5 :
score += 100
if t > 5 :
score += 50
print(score)

Related

algorithm python3 Time efficiency

In Python, the top is functional and the bottom is not.
The non-functional type has a time-out and the functional type has passed. What is the difference?
The environment is a python3 environment.
import sys
n, m = map(int, sys.stdin.readline().split())
arr = list(map(int, sys.stdin.readline().split()))
start = 0
end = max(arr)
def solution(arr, start, end):
result = 0
while start <= end:
total = 0
mid = (start + end) // 2
for i in arr:
if i > mid:
total += i - mid
if total < m:
end = mid - 1
else:
result = mid
start = mid + 1
return result
print(solution(arr, start, end))
import sys
n, m = map(int, sys.stdin.readline().split())
arr = list(map(int, sys.stdin.readline().split()))
start = 0
end = max(arr)
result = 0
while start <= end:
total = 0
mid = (start + end) // 2
for i in arr:
if i > mid:
total += i - mid
if total < m:
end = mid - 1
else:
result = mid
start = mid + 1
print(result)
I followed the link to the corresponding SPOJ problem. Looks like for this particular question the limits for python 3 is pretty closely cut and your TLE is due to the I/O. (read the comments here). Your algorithm looks correct.
As far as the discrepancy in functional call and loop is considered. I submitted both your codes to the SPOJ, both were TLE.
I will recommend screening the comments beneath the question for potential pitfalls for the future reference, it is really helpful.

Python: Change variable depending on for loop iteration

I have a for loop with a 100 iterations and I would like to change the value of a variable for every 10 iterations. One way of doing this would be:
for i in range(100):
if i < 10:
var = 1
elif i < 20 :
var = 1.5
...
But I don't want to have 10 if statements. Is there a better way of doing it? In this case, the variable changes by the same amount for every 10 iterations.
You're looking for the modulo (%) operator. From the docs:
The % (modulo) operator yields the remainder from the division of the first argument by the second.
Indeed, 11 = 10 * 1 + 1 hence 11 % 10 = 1, but 30 = 10*3 + 0 hence 30 % 10 = 0! And you're looking for all those that are a factor of ten:
increment = 0.5
for i in range(100):
if i % 10 == 0:
var += increment
There is this modulo operator %
for i in range(100):
if 0 == i % 10:
var = var + 0.5
or if you want to change var on other than the first iteration:
for i in range(100):
if i and 0 == i % 10:
var = var + 0.5

Passes the first case but fails the other cases

Okay so I finished a code on hackerrank. It passes the test case but once I submit it fails the others. I have scanned through the code several times without a solution. Any thoughts on this? I have attached the screenshot of the question and my code as well as the test case scenarios that failed.
My code:
#!/bin/python3
import math
import os
import random
import re
import sys
def batting_stats(lst):
rgh,rgf,totr,totbf,totd,crat = 0,0,0,0,0,0 #rgh: runs greater than 100, rgf: runs greater 50
#totr:total runs, totbf:total balls faced, #totd: total
#dismissals, crat: conversion rate
results = []
for inning in lst:
runs_scored = inning[0]
balls_faced = inning[1]
dismissed = inning[-1]
totr += runs_scored
totbf += balls_faced
totd += dismissed
if runs_scored >= 100:
rgh += 1
elif runs_scored == 50:
rgf += 1
average = totr // max(totd, 1)
strikeRate = int((totr / totbf) * 100)
if rgf > 0:
crat = ( rgh // rgf ) * 100
results.append([average, strikeRate, crat])
return results
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
innings_count = int(input().strip())
innings = []
for _ in range(innings_count):
innings_item = list(map(int, input().rstrip().split()))
innings.append(innings_item)
result = batting_stats(innings)
for x in result or []:
fptr.write(' '.join(map(str, x)))
fptr.write('\n')
fptr.close()
I don't have access to your grader, but here are some obvious issues I see.
if runs_scored >= 100:
rgh += 1
elif runs_scored == 50:
rgf +=1
should be
if runs_scored >= 100:
rgh += 1
rgf +=1 (because a 100 plus score is also a 50 plus score)
elif runs_scored >= 50: (at least 50 is the condition not exactly 50)
rgf += 1
Next,
average = totr // max(totd, 1)
should be
if totd==0:
average=totr
else:
average=totr/totd
And,
crat = ( rgh // rgf ) * 100 should be
crat = ( rgh / rgf ) * 100
I have included these edits together with a few more, and have tested this code on the one available input and a few others. It returns, as expected, a list of lists with numbers that match the expected output. Please try this out in the grader.
import math
def batting_stats(lst):
rgh,rgf,totr,totbf,totd,crat = 0,0,0,0,0,0
results = []
for innings in lst:
totr += innings[0]
totbf += innings[1]
totd += innings[2]
if innings[0] >= 100:
rgh += 1
rgf +=1
elif innings[0] >= 50:
rgf+=1
if totd==0:
average=totr
else:
average=totr/totd
strikeRate = (totr / totbf) * 100
if rgf > 0:
crat = ( rgh / rgf ) * 100
else:
crat=0
results.append([math.floor(average), math.floor(strikeRate), math.floor(crat)])
return results

Python - track inputs

I am having difficulty keeping a track of the total number of inputs. I want my program to keep track of the total number of inputs and print it when my while loop breaks. Any help is appreciated!
r = float(input("enter r:"))
def main(r):
a = 3.14 * (float(r ** 2))
s_v = 0
total = 0
while True:
r = float(input("enter r:"))
if r == sentinal_value:
total += r
print("Total = " , total)
break
else:
print("Area = ", a)
continue
main(r)
I assume that you want your program to re-calculate the area with each iteration. As written, it will only be calculated the first time you run the mymian function. You don't need to pass any arguments to the function.
def mymian():
sentinal_value = 0
total = 0
while True:
r = float(input("enter r:"))
if r == sentinal_value:
print("Total number of r provided to this program" , total)
break
else:
print("Area = ", 3.14 * (float(r ** 2)))
total += 1
continue

Euler 12 need optimization

I have solved euler problem 12, but it needs some optimization. I have read on the euler forums, but it has not helped me optimized it. However, I have managed to get the solution, I just need to speed it up. It currently takes 4 minutes to run. Here is my code:
import time
def nthtriangle(n):
return (n * (n + 1)) / 2
def numberofnfactors(n):
count = 0
if n==1:
return 1
for i in range(1, 1 + int(n ** 0.5)):
if n % i == 0:
count += 2
return count
def FirstTriangleNumberWithoverxdivisors(divisors):
found = False
counter = 1
while not found:
print(int(nthtriangle(counter)), " ", numberofnfactors(nthtriangle(counter)))
if numberofnfactors(nthtriangle(counter)) > divisors:
print(" first triangle with over ",divisors, " divisors is ", int(nthtriangle(counter)))
found = True
break
counter += 1
start_time = time.time()
FirstTriangleNumberWithoverxdivisors(500)
print("My program took", time.time() - start_time, "to run")
Instead of calculating each triangle number individually, use a generator to get the triangle numbers
from timeit import timeit
def triangle_numbers():
count = 1
num = 0
while True:
num += count
count += 1
yield num
def count_divisors(n):
count = 0
if n==1:
return 1
for i in range(1, 1 + int(n ** 0.5)):
if n % i == 0:
count += 2
return count
print(timeit('next(num for num in triangle_numbers() if count_divisors(num) >= 500)',
globals=globals(), number=1))
Gives me 3.8404819999996107 (seconds) on my machine. You could probably also improve the divisor counting.
What's really slowing you down is calling nthtriangle and numberoffactors more than once in your loop! Plus, those calls to print aren't free.

Resources