How to make extra functionality on output values? - python-3.x

I need to access results of dice form "Attacker" and "Defender" and compare them. Have no idea how to do it. I've already tried IF loop (if a > b, print "lala") but it doesn't work.
import random
counter = 0
while counter < 1:
a = random.randrange(1,6)
b = random.randrange(1,6)
c = random.randrange(1,6)
print("Attacker:")
print(a,"-", b,"-", c)
counter += 1
counter = 0
while counter < 1:
d = random.randrange(1,6)
e = random.randrange(1,6)
g = random.randrange(1,6)
print("Defender:")
print(d,"-", e,"-", g)
counter += 1
Expected program is printing 3 random numbers in range(0-6) for each player and then compare results prining "Player1 (orP2) Wins"

Declare the a-g variables outside their while loops. The scope of variables determines where you can use them. You've declared those variables within a while loop, so you can only use them within their while loop.
a = None # or whatever default value
b = None
...
g = None
counter = 0
while counter < 1:
a = random.randrange(1, 6)
...
counter = 0
while counter < 1:
d = random.randrange(1, 6)
...
if a > b:
...

import random
counter = 0
number_of_dice=3
playerA = [0]*number_of_dice
playerB = [0]*number_of_dice
#let's fill those arrays
for i in range(number_of_dice):
playerA[i] = random.randrange(1,6)
playerB[i] = random.randrange(1,6)
print("Player A threw ",playerA)
print("Player B threw ",playerB)
#now evaluate the scores
wins_for_A = 0
wins_for_B = 0
for i in range(number_of_dice):
if playerA[i]>playerB[i]:
wins_for_A+=1
elif playerA[i]<playerB[i]:
wins_for_B+=1
#no else... that means a draw
if wins_for_A>wins_for_B:
print("player A wins")
elif wins_for_A<wins_for_B:
print("player B wins")
else:
print("draw")
it outputs something like
Player A threw [5, 3, 3]
Player B threw [3, 2, 3]
player A wins
Process finished with exit code 0

Related

What am I doing wrong with this code for hackerrank?

I have been coding this problem for HackerRank and I ran into so many problems. The problem is called "Plus Minus" and I am doing it in Python 3. The directions are on https://www.hackerrank.com/challenges/plus-minus/problem. I tried so many things and it says that "there is no response on stdout". I guess a none-type is being returned. Here is the code.:
def plusMinus(arr):
p = 0
neg = 0
z = arr.count(0)
no = 0
for num in range(n):
if arr[num] < 0:
neg+=1
if arr[num] > 0:
p+=1
else:
no += 1
continue
return p/n
The following are the issues:
1) variable n, which represents length of the array, needs to be passed to the function plusMinus
2) No need to maintain the extra variable no, as you have already calculated the zero count. Therefore, we can eliminate the extra else condition.
3) No need to use continue statement, as there is no code after the statement.
4) The function needs to print the values instead of returning.
Have a look at the following code with proper naming of variables for easy understanding:
def plusMinus(arr, n):
positive_count = 0
negative_count = 0
zero_count = arr.count(0)
for num in range(n):
if arr[num] < 0:
negative_count += 1
if arr[num] > 0:
positive_count += 1
print(positive_count/n)
print(negative_count/n)
print(zero_count/n)
if __name__ == '__main__':
n = int(input())
arr = list(map(int, input().rstrip().split()))
plusMinus(arr, n)
The 6 decimals at the end are needed too :
Positive_Values = 0
Zeros = 0
Negative_Values = 0
n = int(input())
array = list(map(int,input().split()))
if len(array) != n:
print(f"Error, the list only has {len(array)} numbers out of {n}")
else:
for i in range(0,n):
if array[i] == 0:
Zeros +=1
elif array[i] > 0:
Positive_Values += 1
else:
Negative_Values += 1
Proportion_Positive_Values = Positive_Values / n
Proportion_Of_Zeros = Zeros / n
Proportion_Negative_Values = Negative_Values / n
print('{:.6f}'.format(Proportion_Positive_Values))
print('{:.6f}'.format(Proportion_Negative_Values))
print('{:.6f}'.format(Proportion_Of_Zeros))

How to print the index/elements that are included in the final max sum of non-adjacent elements?

In the program of finding the max sum of non-adjacent elements how can we print the elements/indexes of elements which are considered in the final sum. So here I am attaching my code for that. I am using dynamic programming.
I got the correct answer when there is only one possibility of occurring max sum like we have -1, 2, 4, 5. So the output will be 5 and 2.
n = int(input())
tickets = list(map(int,input().split()))
incl = 0
excl = 0
max_list = []
for i in range(len(tickets)):
if excl>incl:
new_excl = excl
else:
new_excl = incl
incl = excl + tickets[i]
excl = new_excl
if excl > incl:
if len(max_list)>1 and (max_list[len(max_list)-1] - max_list[len(max_list)-2])==1:
del max_list[len(max_list)-2]
else:
max_list += [i]
if excl>incl:
print(excl,max_list)
else:
print(incl,max_list)
But I do not get answers when the input like this : 4, 5, 4, 3. In this input there are two possibilities : 4+4 and 5+3. I want to print that possibility that has a higher digits than the other from right side. So in this example from right side 4 > 3 so the possibility of 4 should be printed. But I got all the elements in the list.
I have to solve this problem. This is problem from the techgig's code gladiators qualification round. I find the answer for my problem but anyway this solution doesn't get me 100 marks. I haven't checked it for many test cases but you can check it and if it fails then please inform so I can get what the problem is.
from itertools import combinations
for i in range(int(input())):
n = int(input())
tickets = list(map(int,input().split()))
incl = 0
excl = 0
max_list = []
for i in range(len(tickets)):
if excl>incl:
new_excl = excl
else:
new_excl = incl
incl = excl + tickets[i]
excl = new_excl
if excl > incl:
if len(max_list)>1 and (max_list[len(max_list)-1] - max_list[len(max_list)-2])==1:
del max_list[len(max_list)-2]
else:
max_list += [i]
if excl>incl:
s=excl
else:
s=incl
a=[]
if 1 in [abs(t-s) for s,t in zip(max_list,max_list[1:])]:
for m in range(2,n):
for n in list(combinations(max_list, m)):
if sum(tickets[b] for b in n)==s:
a+=[n]
l=[]
index=[]
for m in a:
l+=[tickets[m[1]]]
index+=[m[1]]
v = index[l.index(max(l))]
for m in a:
if v in m:
ans = m
break
for d in list(reversed(ans)):
print(tickets[d],end='')
print()
else:
max_list.reverse()
for d in max_list:
print(tickets[d],end='')
print()

Code showing no output whatsoever (python)

Trying to make a little Fibonacci game where the user guesses a set amount of steps. I'm trying to make a functioning Fibonacci generator to make the lists to refer to later, but nothing is showing up. I'm sure I'm returning the values. What am I doing wrong?
""" Core Fibonacci Code
a = int(input("How many steps of fibonacci would you like? "))
def fibonacci(counter):
a = 0
b = 1
count = 2
print (a)
print (b)
fib = [0, 1]
while (counter > count):
c = a + b
print (c)
a = b
b = c
count += 1
fibonacci(a)
"""
def fibonacci(counter):
a = 0
b = 1
count = 2
print (a)
print (b)
fib_list.append = a
fib_list.append = b
while (counter > count):
c = a + b
fib_list.append = c
a = b
b = c
count += 1
def homescreen():
print = ("Which gamemode would you like to play?")
print = ("EASY - 10 Steps")
print = ("MEDIUM - 25 Steps")
print = ("HARD - 50 Steps")
request = input("")
if request is "Easy" or "easy":
z = 10
elif request is "Medium" or "medium":
z = 25
elif request is "Hard" or "hard":
z = 50
return z
homescreen()
fibonacci(z)
print (fib_list)
Use print("Which gamemode would you like to play?") and not print=.
You use such format when your returning something from the called function.
eg:
def foo():
#Something
return y
x=foo()
Note :
Use the function append(), dont use lib_list.append=a.
Also declare lib_list outside the function fibonacci() as you're mentioning it in the function call outside of the function.

Given a positive integer, determine if it's the nth Fibonacci number for some n

I try to find out the index of a certain Fibonacci number. However my program returned to me this result "Your program took too long to execute. Check your code for infinite loops, or extra input requests" after typing in 1134903171.
num = 1
num_prev = 1
n = int(input())
i = 1
if n < 2:
print(1, 2)
else:
while i <= n + 2:
num_prev, num = num, num + num_prev
i += 1
if n == num:
print(i + 1)
break
elif i == n + 3:
print(-1)
#break`
Thank you guys. The problem of last code is that: if the number isn't a Fibonacci number and meanwhile it is too large, it will took to many loops for the calculation. As I used a web compiler to calculate, they do not allow such "infinity" loop to operate. Then I used a math methode to limite the loop.
import math
N=int(input())
root1=math.sqrt(5*N*N+4)
root2=math.sqrt(5*N*N-4)
i=1
num, num_prev = 1, 1
if root1%1==0 or root2%1==0:
while i <= N+2:
num_prev,num = num,(num+num_prev)
i+=1
if N==num:
print(i+1)
break
else:
print(-1)
But the best answer could be:
prev, next = 1, 1
index = 2
possible_fib = int(input())
while possible_fib > next:
prev, next = next, prev + next
index += 1
if possible_fib == next:
print(index)
else:
print(-1)

Puzzler solver program: How many different solutions are there to (1/a)+(1/b)+(1/c)+(1/d)+(1/e)+(1/f)+(1/g) = 1?

I wrote the python code below that solves and prints each possible solution for anything under 6 unit fractions, but given how I programmed it, it takes infinitely long to check for 7 fractions. Any ideas on how to modify the code to find all the possible solutions more efficienty?
import sys
from fractions import Fraction
import os
#myfile = open('7fractions.txt', 'w')
max = 7 #>2 #THIS VARIABLE DECIDES HOW MANY FRACTIONS ARE ALLOWED
A = [0] * max
A[0] = 1
def printList(A):
return str(A).strip('[]')
def sumList(A):
sum = 0
for i in A:
if i != 0:
sum += Fraction(1, i)
return sum
def sumTest(A):
sum = 0
v = 0
for i in range(0, len(A)):
if A[i] == 0 and v == 0:
v = Fraction(1,A[i-1])
if v != 0:
sum += v
else:
sum += Fraction(1, A[i])
return sum
def solve(n, A):
if n == max - 2:
while (sumTest(A) > 1):
print(A)
if sumList(A) < 1:
e = 1 - sumList(A)
if e.numerator == 1 and e.denominator>A[n-1]:
A[n+1] = e.denominator
#myfile.write(printList(A) + '\n')
print(A)
A[n+1] = 0
A[n] += 1
else:
while (sumTest(A) > 1):
if sumList(A) < 1:
A[n+1] = A[n] + 1
solve(n+1, A)
A[n+1] = 0
A[n] += 1
#execute
solve(0, A)

Resources