So, I have 3 variables the total of which should be 120. I have done the verification of that. The variables should be equal to 0 or 20 or 40 or 60 or 80 or 100 or 120. I have done the verification for that as well but now what I need is for my program to check if variable 1 is 100 and variable 2 is 0 or 20 and variable 3 is 0 or 20 in terms to output a message. Then I need to check if variable 1 is 40 or 60 or 80 variable 2 is 0 or 20 or 40 or 60 or 80 and variable 3 is 0 or 20 or 40 or 60 in terms to output a different message.
if pass_credit + defer_credit + fail_credit != 120:
print("Total incorrect!")
elif pass_credit == 120 and defer_credit == 0 fail_credit == 0:
print("Progress")
break
elif pass_credit == 100 and defer_credit == 0 or 20 and fail_credit == 0 or 20:
print("Progress - module trailer")
break
That's what I have so far
Thanks in advance
the semantics of this line is wrong:
elif pass_credit == 100 and defer_credit == 0 or 20 and fail_credit == 0 or 20:
Either write
elif pass_credit == 100 and (defer_credit == 0 or defer_credit == 20) and (fail_credit == 0 or fail_credit == 20):
or write
elif pass_credit == 100 and defer_credit in (0, 20) and fail_credit in (0, 20):
If you want to use a general message for all the good combinations (with the values), use:
a, b, c = 80, 40, 0
message = "The values are: "
for i, var in enumerate([a, b, c]):
message += "Variable " + str(i + 1) + " is: " + str(var) + ", "
print(message[:-2] if a + b + c == 120 else "Total incorrect!")
Output:
The values are: Variable 1 is: 80, Variable 2 is: 40, Variable 3 is: 0
If you want a different message for every possible combination, continue your elifs to cover all options (with #gelonida's correction for the syntex). No smart way to do that.
Related
I'm new to python and have a question
I want to print 10 values per line and I can't figure out how to do it. Here's my attempt at it;
a = 1
b = 15
count = 0
count_end = 10
while count < count_end:
while a < b:
count = count + 1
print(a, end = " ")
a = a + 1
if(count == count_end):
break
The output is 1 2 3 4 5 6 7 8 9 10 but I want the output to go from 1 to 10 on one line and then continue from 11 to 15 on a new line under it. I've seen some people use lists to answer a similar question but I don't want to use lists for this question.
Any help would be greatly appreciated :)
Just use one loop, and then check if count % count_end == 0 to detect every multiple of count_end.
for count, current in enumerate(range(a, b)):
print(current, end=" ")
if count % count_end == 0 or current == b-1:
print()
a = 1
b = 15
count = 0
count_end = 10
while count < count_end:
while a <= b:
count = count + 1
print(a, end = " ")
a = a + 1
if(count == count_end):
print("")
something like this ?
In my code I iterate through dataframes of each year to calculate the number of wins (increase between numbers) and losses (decrease between numbers), and the ratio of wins to losses. The loop I run correctly displays the right number of wins and losses in the dataframe they are eventually pushed to. However, when calculating the win/loss ratio, the if statement isn't working for no real reason. Here is the loop:
trades = []
wins = []
losses = []
winloss = []
for df in df_years_grouped:
total_trades = len(df)
trades.append(total_trades)
win = 0
loss = 0
for i, row in df.iterrows():
if i == 0:
continue
elif (df[1][i] > df[1][i-1]):
win += 1
elif (df[1][i] < df[1][i-1]):
loss += 1
wins.append(win)
losses.append(loss)
if win == 0 & loss == 0:
winloss.append(0)
elif win > 0 & loss == 0:
winloss.append('All Wins')
elif win == 0 & loss > 0:
winloss.append('All Losses')
else:
winloss.append(win/loss)
Here is the outcome in the Dataframe:
Trades Win Lose W/L
11 5 5 All Wins
42 21 20 All Wins
35 16 18 All Wins
14 9 4 All Wins
23 13 9 All Wins
12 7 4 All Wins
4 2 1 All Wins
4 2 1 All Wins
11 5 5 All Wins
6 3 2 All Wins
0 0 0 0
9 6 2 All Wins
2 0 1 0
16 6 9 All Wins
3 0 2 0
14 7 6 All Wins
206 106 99 1.070707
As you can see it works on one or two but fails on the most, making most of them wins?
I believe you should be using "and" instead of "&" in the if statements. You can read up on the differences here:
https://www.geeksforgeeks.org/difference-between-and-and-in-python/
I think the issue is between 'and' and '&'
Give the following a read:
https://www.geeksforgeeks.org/difference-between-and-and-in-python/
'and' is the Locigal AND whereas '&' is the bit-and 'AND'
a = 14
b = 4
print(b and a) - 14
print(b & a) - 4
See here too:
what is the difference between "&" and "and" in Python?
I would suggest changing you code to use the logical AND
or maybe the following if you do not mind more IF statements
if win == 0:
if loss == 0
winloss.append(0)
elif loss > 0:
winloss.append('All Losses')
elif win > 0:
if loss == 0:
winloss.append('All Wins')
else:
winloss.append(win/loss)
I personally would also find this easier to read as an external user
You should use and instead of &, their have different priority:
win == 0 & loss == 0 is equivalent to win == (0 & loss) == 0:
import ast
assert ast.dump(ast.parse("win == 0 & loss == 0")) == ast.dump(ast.parse("win == (0 & loss) == 0"))
If tosses = 4 output shows two peg toss point for user and if tosses = 5, output shows one peg toss point for user. Also, how do I put these blockquotes because when I put any test code inside that it says the code is not formatted properly.
'''
import random
question = 0
correct = 5
points = 0
tosses = random.randint(3, 5)
utotal = 0
upoint = 0
cpoint = 0
ctotal = 0
user = "Adarsh"
print(user,"s turn")
while tosses <= correct :
peg = random.randint(0, 5)
tosses = tosses + 1
if peg == 0 :
upoint = - 15
utotal = utotal - 15
elif peg == 1 :
upoint = 20
utotal = utotal + 20
elif peg == 2 :
upoint = 50
utotal = utotal + 50
elif peg == 3 :
upoint = 10
utotal = utotal + 10
elif peg == 4 :
upoint = 30
utotal = utotal + 30
elif peg == 5 :
upoint = 100
utotal = utotal + 100
print("Ring is on Peg", peg, ".", "+", upoint)
print("total points", utotal)
print("Computer's turn")
for i in range(0, 4):
peg = random.randint(0, 5)
tosses = tosses + 1
if peg == 0 :
cpoint = - 15
ctotal = ctotal - 15
elif peg == 1 :
cpoint = 20
ctotal = ctotal + 20
elif peg == 2 :
cpoint = 50
ctotal = ctotal + 50
elif peg == 3 :
cpoint = 10
ctotal = ctotal + 10
elif peg == 4 :
cpoint = 30
ctotal = ctotal + 30
elif peg == 5 :
cpoint = 100
ctotal = ctotal + 100
print("Ring is on Peg", peg, ".", "+", cpoint)
print("total points", ctotal)
if ctotal > utotal:
print("computer wins")
else:
print("you win")
'''
testCode
The script below should give approximately what you wanted. Have defined a method toss(user, tosses) that takes the user and tosses as parameters. user is a user name and tosses is the same number of tosses, in order to run the experiment on equal terms.
import random
# The commented lines below are not used
# question = 0
correct = 5
points = 0
#upoint = 0 -- again not used
#cpoint = 0
def toss(user, tosses):
print(user,"s turn")
upoint = total_points = 0 # Initialize so that they can be used below
while tosses <= correct :
peg = random.randint(0, 5)
tosses = tosses + 1
if peg == 0 :
upoint = - 15
total_points = total_points - 15
elif peg == 1 :
upoint = 20
total_points = total_points + 20
elif peg == 2 :
upoint = 50
total_points = total_points + 50
elif peg == 3 :
upoint = 10
total_points = total_points + 10
elif peg == 4 :
upoint = 30
total_points = total_points + 30
elif peg == 5 :
upoint = 100
total_points = total_points + 100
print("Ring is on Peg", peg, ".", "+", upoint)
print("total points", total_points)
return(total_points)
# moved the tosses' initialisation here before we call
# the corresponding methods
tosses = random.randint(3, 5)
utotal = toss("Arash", tosses)
ctotal = toss("Computer", tosses)
# Your comment can perhaps be placed here
if ctotal > utotal:
print("computer wins")
else:
print("you win")
An example run
Arash s turn
Ring is on Peg 4 . + 30
Ring is on Peg 3 . + 10
Ring is on Peg 2 . + 50
total points 90
Computer s turn
Ring is on Peg 2 . + 50
Ring is on Peg 3 . + 10
Ring is on Peg 5 . + 100
total points 160
computer wins
NOTE: Your link that you call blockquote shows the program execution. If I understand well, you were thinking of putting that as a comment somewhere in your script, probably towards the end, where the printing takes place.
This problem may use the concept of stack in python.
My code is as follows, but it always get Time Limit Exceed (TLE) error.
I think the problem is the algorithm I design is too slow due to two loops.
I would like to know how to implement the concept of stack and use only one loop in this problem. Please instruct me and help me to revise the code, thank you so much.
Input: including one line, which contains several integers, representing the score of each time, and the numbers are separated by spaces
Output: including one line, which contains several integers, representing the interval frequency when increase happens of each score(if the score does not increase, it returns 0), and the numbers are separated by spaces
inp = [int(i) for i in input().split()]
#create a function to calculate intervals
def cal_interval(lst):
lenth = len(inp)
output_lst = []
for i in range(lenth):
#set counter
count = 1
#set iteraion number
iter_num = 0
for j in range(i+1, lenth):
iter_num += 1
if inp[j] > inp[i]:
output_lst.append(count)
break
else:
count += 1
if iter_num == (lenth-i-1):
output_lst.append(0)
break
#last number
output_lst.append(0)
#from int list transformed into str list
output_lst = [str(i) for i in output_lst]
#join by spaces
space = ' '
interval_str = space.join(output_lst)
return interval_str
print (cal_interval(inp))
there are two sets of test data as follows,
Sample Input 1: 89 56 78 9 81 7
Sample Output 1: 0 1 2 1 0 0
Sample Input 2: 76 3 60 57 11 72 73 86 27 91 56 58 21 2
Sample Output 2: 7 1 3 2 1 1 1 2 1 0 1 0 0 0
You can actually do this using slicing with some comprehensions, also next will be useful as you can supply it a default:
def get_intervals(data):
for score, *nums in (data[i:] for i in range(len(data))):
yield next((i for i, n in enumerate(nums, 1) if n > score), 0)
All I’m doing here is each iteration, score is the next number in data and nums is the rest after it. Then using next it’s grabbing the first value’s index in nums if the value is above score otherwise defaulting to 0.
So with that all you need to do in place of cal_interval is print the result of get_intervals joined:
print(' '.join(get_intervals([89, 56, 78, 9, 81, 7])))
print(' '.join(get_intervals( [76, 3, 60, 57, 11, 72, 73, 86, 27, 91, 56, 58, 21, 2])))
Results:
0 1 2 1 0 0
7 1 3 2 1 1 1 2 1 0 1 0 0 0
def stack():
while(f==1):
print("1. Push\n2. Pop\n3. Peek\n4. Traverse\n5. Quit")
print("Enter any input: ")
a = input()
if a != '':
a = int(a)
switch(a)
def switch(a):
global top
if a == 1:
print("Enter the Element To push")
b = input()
print(top)
top += 1
ar.append(b)
print(b,"item was Pushed")
elif a == 2:
poped()
print("item was Poped")
elif a == 3:
c = ar[top]
print("Peek value is:",c)
elif a == 4:
print("Traversing all items")
for i in ar:
print(i)
elif a ==5:
print("Quit")
global f
f=2
else:
print("Invalid Value")
def poped():
if top == -1:
print("Stack is Empty / Pop not performed")
else:
ar.pop()
top -= 1
# Driver Code
f = 1
top = -1
ar = []
stack()
a = 0
b = 0
for x in range (100):
a = a + 1
if a == 10:
b = b + 1
print(a)
print(b)
The outcome
99
1
What I want
10
90
IIUC, this should do the trick:
a = 0
b = 0
for x in range (100):
if a < 10:
a = a + 1
else:
b = b + 1
But to simplify further, you can use python's assignment operator, a += 1 syntax, which increments the value of a by 1:
a = 0
b = 0
for x in range (100):
if a < 10:
a += 1
else:
b += 1
Add a conditional check.
a = 0
b = 0
for x in range (100):
if (a % 10 != 0 or a==0):
a = a + 1
else:
b = b + 1
print(a)
print(b)
Just for fun:
a, b = 0, 0
for x in range(100):
add = a % 10 != 0 or a == 0
a += add
b += not add
This uses the fact that a bool is an int although I don’t advise it as it’s not too readable