Code showing no output whatsoever (python) - python-3.x

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.

Related

How to check if this input is a negative number

I'm new to python and want to make a program that generates Pi with the given decimal numbers. Problem is that I don't know how to check if the user has inputted a positive number.
This is the function that generates Pi (I don't know for sure how it works)
def PiBerekening(limiet):
q = 1
r = 0
t = 1
k = 1
n = 3
l = 3
decimaal = limiet
teller = 0
while teller != decimaal + 1:
if 4 * q + r - t < n * t:
# yield digit
yield n
# insert period after first digit
if teller == 0:
yield '.'
# end
if decimaal == teller:
print('')
break
teller += 1
nr = 10 * (r - n * t)
n = ((10 * (3 * q + r)) // t) - 10 * n
q *= 10
r = nr
else:
nr = (2 * q + r) * l
nn = (q * (7 * k) + 2 + (r * l)) // (t * l)
q *= k
t *= l
l += 2
k += 1
n = nn
r = nr
And this is how I ask the user how many decimals he wants to see
while not verlaatloop:
try:
pi_cijfers = PiBerekening(int(input("With how many decimals would you like to calculate Pi?")))
assert pi_cijfer > 0 # This is one of the things I've tried but I get the "NameError: name 'pi_cijfer' is not defined" error and I don't know what to do to check if the inputted number is negative
except ValueError:
print("This isn't a valid number, try again")
except AssertionError:
print("This number is negative, try again")
else:
verlaatloop = True
This is how I show the calculated Pi
for pi_cijfer in pi_cijfers:
print(pi_cijfer, end='')
You can first validate the input and then pass it to the PiBerekening function. Something like this:
while not verlaatloop:
try:
no_decimals = int(input("With how many decimals would you like to calculate Pi?"))
if no_decimals > 0:
pi_cijfers = PiBerekening(no_decimals)
#assert pi_cijfer > 0 # This is one of the things I've tried but I get the "NameError: name 'pi_cijfer' is not defined" error and I don't know what to do to check if the inputted number is negative
except ValueError:
print("This isn't a valid number, try again")
except AssertionError:
print("This number is negative, try again")
else:
verlaatloop = True

How to make extra functionality on output values?

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

Lazy Sorting HackerRank Python

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.

always got the same output with random.choice in a function

I tried using for-loop to exec my function but its always the same result.
import random
def main(arr):
result = random.choice(arr)
...some code...
return len(result)
for i in range(100):
main(arr)
I could only get diff result from stop/run the terminal. Anyone know why?
my question is the same as this one. random.choice always same
import random
results = []
with open('kargerMinCut.txt') as inputfile:
for line in inputfile:
results.append(line.strip().split('\t'))
def contract(arr):
while len(arr) > 2:
# Generate random number in list of lists
# ranList = random.choice(arr)
ranList = arr[np.random.choice(len(arr))]
ranNum = random.choice(ranList[1:])
# retrieve the index of the random number
listIndex = arr.index(ranList)
for i in range(0, len(arr)):
if arr[i][0] == ranNum:
targetList = i
break
target = ranList[0]
for i in range(0, len(arr)):
if i == listIndex:
arr[i].pop(0)
arr[i] = [x for x in arr[i] if x != ranNum]
elif i == targetList:
arr[i] = [x for x in arr[i] if x != target]
else:
for index, item in enumerate(arr[i]):
if item == target:
arr[i][index] = ranNum
arr[targetList] += arr[listIndex]
del arr[listIndex]
return len(arr[0])-1
the arr would be like this
array = [[1,2,3,4],[2,1,3,4],[3,1,2,4],[4,1,2,3]]
I don't know what you do inside your function but I've got the normal result. And in the question what you linked to the person just used seed. This is kinda pseudorandom that gives you all the time the same random output. Here is the link to deep your knowledge about pseudorandom
import random
arr = [1,2,3,4,5]
def main(arr):
result = random.choice(arr)
print(result)
for i in range(100):
main(arr)
The result is as it has to be:
1
3
5
3
4
3
1
4
4
3
2

Creating a Fibonacci sequence function in Python 3

I am trying to create a function that prints a list of the first 4 numbers in the Fibonacci sequence, the first 10 numbers in the Fibonacci sequence, and then "the first -4" numbers in the Fibonacci sequence. The "-4" numbers in the Fibonacci sequence should return an empty list because there is no "-4" numbers in the sequence. I need the function to print the 3 lists as an end result in the main() function. Here is my code so far, I'm new to functions so any help would be appreciated.
fn = []
def F(n):
i = 0
a = 0
b = 1
for i in range(0,n):
temp = a
a = b
b = temp + b
fn.append(b)
i = i + 1
return fn
main():
print F(4)
print F(10)
print F(-4)
Your function for generating Fibonacci numbers is correct except the global variable fn = [] should be declared within the function body. Also, as suggested in the comment by #alfasin, a, b = b, a + b is more Pythonic.
def fib_list(n):
a = 0; b = 1; fib_list = []
if n <= 0:
return
for i in range(0, n):
a, b = b, a + b
fib_list.append(b)
return fib_list
The other problems I could find with your code:
* print is not a statement in Python 3.x.x, it is a function instead, i.e. print F(4) should be print(F(4))
* main(): should be changed to if __name__ == '__main__':

Resources