Fizzbuzz (Turning my output to a string?) - python

New here and hoping I can help as much as I am helped. Basically, I have been tasked with writing a fizzbuzz program in Python and so far so good except for some feedback I received.
Now I have to ensure that the output of my program comes across horizontally and is not printed vertically on new lines. From my understanding, and my lecturers hinting, I need to turn function to produce strings and remove the print statements as well.
Code is below:
def fizzbuzz1 (num):
for num in range(1, num):
if (num%3 == 0) and (num%5 == 0):
print("Fizzbuzz")
elif ((num % 3) == 0):
print("Fizz")
elif ((num % 5) == 0):
print("buzz")
else :
print (num)
def main ():
while True: #Just to keep my program up and running while I play with it
num = input ("please type a number: ") #
num = int (num)
print ("Please select an type what option you wish to try: A) Is this Fizz or Buzz? B) Count saying fizz/buzz/fizzbuzz")
opt = input ("Please type A or B and press enter: ")
if opt == "A":
fizzbuzz(num)
elif (opt == "a")
fizzbuzz(num)
elif (opt == "B"):
print (fizzbuzz1(num))
elif (opt == "b"):
print (fizzbuzz1(num))
main ()
I have tried a whole host of things, and my lecturer doesn't seem too interested in help me. Womp. I was recommended to review this exercise were I played with this piece of code:
def func(num):
value = ‘’
for x in range(...):
if .... == .... :
value += str(x) + ‘, ‘
return value[…]# You need to remove the last comma and the space
When I do play with this code, I do get numbers to go across the screen. But for the life of me I can not seem to incorporate what I have written with elements from this. Where am I going astray?
Thank you for any and all your advice/help. If you do choose to reply, please keep it as simple as possible for me.
Cheers.
Update: Thanks everyone for your suggestions, lots of thimgs I didnt know to try!
I also found a thread here at: Can't figure out how to print horizontally in python?
Which has answers to a similar issue.

Try printing without a new line, if you use Python 3.x
def fizzbuzz1 (num):
for num in range(1, num):
if (num%3 == 0) and (num%5 == 0):
print("Fizzbuzz ", end="")
elif ((num % 3) == 0):
print("Fizz ", end="")
elif ((num % 5) == 0):
print("buzz ", end="")
else:
print ( str(num) + " ")
print(" ")

You're very close. The approach I would take would be to store the results in a list, then join the contents of the list to make the output string. Here's an example:
>>> def fizzbuzz1(num):
... fb = []
...
... # Iterate through the range, then use `fb.append()` to append the
... # new element to the end of the list.
... for n in range(1, num):
... if not (n%3 or n%5):
... fb.append('Fizzbuzz')
... elif not n%3:
... fb.append('Fizz')
... elif not n%5:
... fb.append('Buzz')
... else:
... fb.append(str(n))
...
... return ', '.join(fb)
...
>>> fizzbuzz1(20)
'1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, Fizzbuzz, 16, 17, Fizz, 19'
>>>

Related

simple string program doesent work, python

A friend of mine told me that she needs help with some homework, I owe her a favor so I said fine, why not. she needed help with a program that checks a sequence, if the sequence is made of the same 2 chars one after the other it will print "yes" (for example "ABABABAB" or "3$3$3$3:)
The program works fine with even length strings (for example "abab") but not with odd length one ("ububu")
I made the code messy and "bad" in purpose, computers is her worst subject so I don't want it to look obvious that someone else wrote the code
the code -
def main():
StringInput = input('your string here - ')
GoodOrBad = True
L1 = StringInput[0]
L2 = StringInput[1]
i = 0
while i <= len(StringInput):
if i % 2 == 0:
if StringInput[i] == L1:
i = i + 1
else:
GoodOrBad = False
break
if i % 2 != 0:
if StringInput[i] == L2:
i = i + 1
else:
GoodOrBad = False
break
if GoodOrBad == True:
print("yes")
elif GoodOrBad != True:
print("no")
main()
I hope someone will spot the problem, thanks you if you read everything :)
How about (assuming s is your string):
len(set(s[::2]))==1 & len(set(s[1::2]))==1
It checks that there is 1 char in the even locations, and 1 char in the odd locations.
a) Showing your friend bad and messy code makes her hardly a better programmer. I suggest that you explain to her in a way that she can improve her programming skills.
b) If you check for the character at the even position and find that it is good, you increment i. After that, you check if i is odd (which it is, since you found a valid character at the even position), you check if the character is valid. Instead of checking for odd position, an else should do the trick.
You can do this using two methods->
O(n)-
def main():
StringInput = input('your string here - ')
GoodOrBad = True
L1 = StringInput[0]
L2 = StringInput[1]
i = 2
while i < len(StringInput):
l=StringInput[i]
if(l==StringInput[i-2]):
GoodOrBad=True
else:
GoodOrBad=False
i+=1
if GoodOrBad == True:
print("yes")
elif GoodOrBad == False:
print("no")
main()
Another method->
O(1)-
def main():
StringInput = input('your string here - ')
GoodOrBad = True
L1 = set(StringInput[0::2])
L2 = set(StringInput[1::2])
if len(L1)==len(L2):
print("yes")
else:
print("no")
main()
There is a lot in this that I would change, but I am just showing the minimal changes to get it to work. There are 2 issues.
You have an off by one error in the code:
i = 0
while i <= len(StringInput):
# in the loop you index into StringInput
StringInput[i]
Say you have 5 characters in StringInput. Because your while loop is going from i = 0 to i < = len(StringInput), it is going to go through the values [0, 1, 2, 3, 4, 5]. That last index is a problem since it is off the end off StringInput.
It will throw a 'string index out of range' exception.
You need to use:
while i < len(StringInput)
You also need to change the second if to an elif (actually it could just be an else, but...) so you do not try to test both in the same pass of the loop. If you go into the second if after the last char has been tested in the first if it will go out of range again.
elif i % 2 != 0:
So the corrected code would be:
def main():
StringInput = input('your string here - ')
GoodOrBad = True
L1 = StringInput[0]
L2 = StringInput[1]
i = 0
while i < len(StringInput):
if i % 2 == 0:
if StringInput[i] == L1:
i = i + 1
else:
GoodOrBad = False
break
elif i % 2 != 0:
if StringInput[i] == L2:
i = i + 1
else:
GoodOrBad = False
break
if GoodOrBad == True:
print("yes")
elif GoodOrBad != True:
print("no")
main()
def main():
StringInput = input('your string here - ')
MaxLength = len(StringInput) // 2 + (len(StringInput) % 2 > 0)
start = StringInput[:2]
chained = start * MaxLength
GoodOrBad = chained[:len(StringInput)] == StringInput
if GoodOrBad == True:
print("yes")
elif GoodOrBad != True:
print("no")
I believe this does what you want. You can make it messier if this isn't bad enough.

Random number generator and validator

This is my code for a gtin-8 number generator
barcode = []
inputChoice = 0
inputChoice = 1
checkNumber = 0
placeHolder = 0
def generate():
generate = 0
for i in str(Userinput):
barcode.append(int(i))
print(barcode)
for i in range (0,6,2):
generate += barcode[i] *3
print('Generate is now ',generate)
print(generate)
def checkNumber():
for i in str(Userinput):
checkNumber += int(i)
placeHolder += int(i)
checkNumber = round(checkNumber, -1)
checkNumber = (checkNumber - placeHolder) % 10
return(checkNumber)
def check():
jk = 0
def main():
inputChoice=0
while inputChoice !=9 and inputChoice !=1 and inputChoice!=2:
inputChoice=int(input("chose 1 to get GTIN,2 to check,9 to exit\n"))
Userinput = (input("input the barcode \n"))
if inputChoice==1 :
if len(Userinput) !=7:
print("make sure you inputted 7 inegers")
if inputChoice == 2:
if len(Userinput) !=8:
print("Make sure you input 8 integers")
else:
generate(Userinput)
return(Userinput)
Userinput = main()
generate()
checkNumber()
I have made a function called check number, generate and main but when I run a code it gives me this error:
TypeError: generate() takes 0 positional arguments but 1 was given
I am unsure why this is the case, jk = 0 is there as I have not finished that function and I am just using it as a placeholder.
works fine after adding *args, than we get
UnboundLocalError: local variable 'checkNumber' referenced before assignment
so add default args in the flag of checkNumber()
def generate(*args): #<<<< edit
generate = 0
for i in str(Userinput):
barcode.append(int(i))
print(barcode)
for i in range (0,6,2):
generate += barcode[i] *3
print('Generate is now ',generate)
print(generate)
def checkNumber(checkNumber=0, placeHolder=0): #<<<< edit
for i in str(Userinput):
checkNumber += int(i)
placeHolder += int(i)
checkNumber = round(checkNumber, -1)
checkNumber = (checkNumber - placeHolder) % 10
return(checkNumber)
that its works finaly result with 1515155155151 as barcode:
chose 1 to get GTIN,2 to check,9 to exit
2
input the barcode
1515155155151
Make sure you input 8 integers
[1, 5, 1, 5, 1, 5, 5, 1, 5, 5, 1, 5, 1]
Generate is now 3
Generate is now 6
Generate is now 9
9
Ok you asked for feedback so here we go...
Point #1: dont use globals when you dont need them. Hint : you can write huge (10+klocs) programs without a single global (talking about globals that are modified or reassigned during execution of course - pseudo-constants etc are ok). Practicaly, this starts by writing pure functions - functions that take arguments, return results, and for which the same set of arguments will always produce the same results
Point #2: respect the language's usual coding conventions (cf pep8 for Python)
Point #3: learn the language's idioms - in your example,
use of str.format()
use of list comprehensions or generator expressions instead of for loops where it makes sense,
a main() function that is really a main function and is guarded by a if __name__ == "__main__": check)
Here's an example of what your code could look like once those points are fixed:
def generate(source):
barcode = [int(c) for c in source]
result = sum(barcode[i] * 3 for i in range(0, 6, 2))
return result, barcode
def check_number(source):
placeholder = checksum = sum(int(i) for i in source)
checksum = round(checksum, -1)
checksum = (checksum - placeholder) % 10
return checksum
def check(what):
jk = 0
def main():
choice = 0
while True:
choice = input("chose 1 to get GTIN, 2 to check, 9 to exit\n").strip()
try:
choice = int(choice)
if choice not in (1, 2, 9):
raise ValueError
except ValueError:
print("Invalid value '{}'".format(choice))
continue
if choice == 9:
return
while True:
source = input("input the barcode \n").strip()
# source should contain only digits
try:
int(source)
except ValueError:
print("Make sure you entered only integers")
continue
if choice == 1 and len(source) != 7:
print("Make sure you entered 7 integers")
continue
elif choice == 2 and len(source) != 8:
print("Make sure you entered 8 integers")
continue
else:
# ok, valid input
break
if choice == 1:
result, barcode = generate(source)
print("barcode : {}.".format(barcode))
print("result : {}".format(result))
elif choice == 2:
raise NotImplementedError("check is not yet implemented")
if __name__ == "__main__":
main()

Tuple index out of range

print "\n\t\t\t\t",moves[6],"|",moves[7],"|",moves[8]
IndexError: tuple index out of range
is the error that I am getting. I am currently writing a python program for tictactoe. moves is equal to ['','','','','','','','','']. Would you like any other info?
I have so far, changed 789 in the row to 678 because indexes begin at 0. Nothing happening.
Next, I tried various other small changes, each of which either changed the error or just gave me the same error.
I also attempted to change formats and things, which did not go so well. I am running python 2.7(?), if that matters.
def draw(moves):
print "\n\t\t\t\t",moves[6],"|",moves[7],"|",moves[8]
print "\t\t\t\t", "--------"
print "\n\t\t\t\t",moves[3],"|",moves[4],"|",moves[5]
print "\t\t\t\t", "--------"
print "\n\t\t\t\t",moves[0],"|",moves[1],"|",moves[2], "\n"
import time
import random
moves = ['','','','','','','','','']
player = ''
ai = ''
restart = ''
first = 19
whosfirst = 1
# Ok, so this is to decide the symbol for each person ---------------------------------------------------
def XorO(man, machine):
print 'Please select a symbol to represent you'
player = raw_input( "Please select \"X\" or \"O\"")
while player not in ('x','X','o','O'):
print "I'm sorry, I don't think I got that. Please try again"
time.sleep(1)
player = raw_input("Select \"X\" or \"O\"")
if player == 'x' or player == 'X':
print "X"
time.sleep(1)
print "Ok, then I'll be \"O\""
ai = 'o'
else:
print "O"
time.sleep(1)
print "Ok, then I'll be \"X\""
ai = 'x'
return player.upper(), ai.upper()
# This is for who is going first -----------------------------------------------------------------------
def first():
number = "a"
while number not in ('n','y',"no",'yes'):
number = raw_input("Do you want to go first? - ").lower()
if number == 'y' or number == 'yes':
return 1
elif number == 'n' or number == 'no':
return 0
else:
print "I'm sorry, I dont think that I understood you."
time.sleep(1)
print "Please select y, yes, n, or no"
#Here Comes the hard part -- drawing the board
def draw(moves):
print "\n\t\t\t\t",moves[6],"|",moves[7],"|",moves[8]
print "\t\t\t\t", "--------"
print "\n\t\t\t\t",moves[3],"|",moves[4],"|",moves[5]
print "\t\t\t\t", "--------"
print "\n\t\t\t\t",moves[0],"|",moves[1],"|",moves[2], "\n"
def playerwon():
print "You won! Yay! Now try again"
def aiwon():
print "I won! Won't you try again?"
def playerfirst(player, ai, moves):
while win(player, ai, moves) is None:
moves = playermove(player, moves - 1)
moves[int(moves)] = player
draw(moves)
if win(player, ai, moves) != None:
break
else:
pass
Dmove = machine_move(player, ai, moves)
print "Nice moves! I'll try ",Dmove
moves[int(Dmove)] = ai
draw(moves)
q = win(player, ai, moves)
if q == 1:
playerwon()
elif q == 0:
aiwon()
else:
print "We tied =-("
time.sleep(2)
print "Let's have another go!"
def aifirst(player, ai, moves):
while not win(player, ai, moves):
Dmove = machine_move(man, machine, moves)
print "I'll take..." , Dmove
moves[Dmove] = machine
draw(moves)
if win(player, ai, moves) != None:
break
else:
pass
moves = playermove(player, moves)
moves[int(moves)] = player
draw(moves)
variable = win(player, ai, moves)
if q == 1:
playerwon()
elif q == 0:
aiwon()
else:
print "We tied =-("
time.sleep(2)
print "Let's have another go!"
def win(player, ai, moves):
ways = ((7,8,9),(4,5,6),(1,2,3),(7,4,1)(8,5,2),(9,6,3),(7,5,3),(9,5,1))
for i in ways:
if ways[i[0]] == ways[i[1]] == ways[i[2]] != empty:
winner = new[i[0]]
if winner == player:
return 1
elif winner == ai:
return 0
if empty not in new:
return 'TIE'
if empty not in new:
return 'TIE'
return None
def playermove(player, moves):
moves = raw_input("Where would you like to place your symbol?")
while True:
if moves not in ('0','1','2','3','4','5','6','7','8'):
print "Sorry, I don't think that's a valid spot... Try again"
moves = raw_input("Where would you like to place your symbol ")
elif moves[int(moves)] != empty:
print "Sorry, I think there's somehing already there..."
moves = raw_input("Where would you like to place your symbol?")
else:
return int(moves)
def aimove(player, ai, moves):
bestmoves = [5, 7, 9, 1, 3]
blank = []
for i in range(0,9):
if moves[i] == empty:
blank.append(i)
for num in blank:
moves[i] = ai
if win(man, ai, moves) is 0:
return i
moves[i] = empty
for num in blank:
moves[i] = man
if win(man, ai, moves) is 1:
return num
moves[i] = empty
return int(blank[random.randrange(len(blank))])
def display_instruction():
print "Welcome to PMARINA's TicTacToe v 1.1.1 ..."
print "In order to place your symbol, just press the corresponding key on your numpad."
print "If you do not have a numpad, then please note down the following arrangement"
print "7 | 8 | 9"
print "-----------"
print "4 | 5 | 6"
print "-----------"
print "1 | 2 | 3"
print "Good Luck, and don't forget to do the most important thing:"
time.sleep(2)
print "HAVING FUN!!"
time.sleep(2)
def letsgo(player, ai, moves):
display_instruction()
print "so lets begin.."
moves = XorO(player, ai)
player = moves[0]
ai = moves[1]
whosfirst = first()
if whosfirst == 1:
print "Ok, you are first!"
print "Lets go!"
draw(moves)
playerfirst(player, ai, moves)
else:
print "Ok, I'll be the first!"
print "So, lets start.."
draw(moves)
aifirst(player, ai, moves)
letsgo(player, ai, moves)
raw_input("Press enter to exit")
Line 14:
moves = ['','','','','','','','','']
Line 192:
moves = XorO(player, ai)
...
draw(moves)
You overwrote your initial declaration of moves, so ('X', 'O') is being passed to draw.
If moves is ['','','','','','','','',''] and the error message you're getting is:
IndexError: tuple index out of range
Then the error is not occurring on the line you say it is. moves is a list, not a tuple. And it does have indices up to 8. moves[9] would generate this error instead:
IndexError: list index out of range
The only tuple I see in the code is ways. Also you don't seem to initialize new before you use it in the function 'win'.
FYI, tuples are made using parentheses tup = (1, 2, 3, 4) while lists use brackets list = [1,2,3,4]. Tuples are also immutable, so you can't modify them later.

Trying to Make a Quiz

So I am trying to run a program on python3 that asks basic addition questions using random numbers. I have got the program running however, I wanted to know if there was a way I could count the occurrences of "Correct" and "Wrong" so I can give the person taking the quiz some feedback on how they did.
import random
num_ques=int(input('Enter Number of Questions:'))
while(num_ques < 1):
num_ques=int(input('Enter Positive Number of Questions:'))
for i in range(0, (num_ques)):
a=random.randint(1,100)
b=random.randint(1,100)
answer=int(input(str(a) + '+' + str(b) + '='))
sum=a+b
if (answer==sum):
print ('Correct')
else:
print ('Wrong.')
You could use a dict to store counts for each type, increment them when you come across each type, and then access it after to print the counts out.
Something like this:
import random
stats = {'correct': 0, 'wrong': 0}
num_ques=int(input('Enter Number of Questions:'))
while(num_ques < 1):
num_ques=int(input('Enter Positive Number of Questions:'))
for i in range(0, (num_ques)):
a=random.randint(1,100)
b=random.randint(1,100)
answer=int(input(str(a) + '+' + str(b) + '='))
sum=a+b
if (answer==sum):
print ('Correct')
stats['correct'] += 1
else:
print ('Wrong.')
stats['wrong'] += 1
print "results: {0} correct, {1} wrong".format(stats['correct'], stats['wrong'])
import operator
import random
def ask_float(prompt):
while True:
try: return float(input(prompt))
except: print("Invalid Input please enter a number")
def ask_question(*args):
a = random.randint(1,100)
b = random.randint(1,100)
op = random.choice("+-/*")
answ = {"+":operator.add,"-":operator.sub,"*":operator.mul,"/":operator.div}[op](a,b)
return abs(answ - ask_float("%s %s %s = ?"%(a,op,b)))<0.01
num_questions = 5
answers_correct = sum(map(ask_question,range(num_questions)))
print("You got %d/%d Correct!"%(answers_correct,num_questions))

python: program hanging! (print issue maybe?)

So, I'm quite nooby at python. I decided to make a program that makes prime numbers. I know there's probably a function built in that does this but I decided to do it myself.
number = 1
numlist = list()
for x in range (0, 1000):
numlist.append("")
print "Created list entry " + str(x)
while True:
number = number + 1
if number % 2 != 0:
numscrollerA = 1
numscrollerB = 1
while numscrollerA <= number:
if float(number) / float(numscrollerA) == float(int(number)):
numlist[numscrollerA] = "true"
if float(number) / float(numscrollerA) != float(int(number)):
numlist[numscrollerA] = "false"
numscrollerA = numscrollerA + 1
while numscrollerB <= number:
if numscrollerB != 1 and numscroller != number and numlist[numscrollerB] == "true":
primestatus = "false"
else:
primestatus = "true"
if primestatus == "true":
print number
I get "Created list entry x" 1000 times as I should. Then the program just hangs.
while numscrollerB <= number:
if numscrollerB != 1 and numscroller != number and numlist[numscrollerB] == "true":
primestatus = "false"
else:
primestatus = "true"
You don't increase numscrollerB in this loop, so it runs infinitedly. Anyway, You should rather use 'for loop':
for numscrollerB in range(1, number+1):
pass # do something
Your code is very unpythonic. Typical of a newcomer experienced in a different style of coding.
Your list is uneccessary.
In python you could create the list like this
def check_even(val):
#this contains your logic
return val % 2 == 0
evenslist = [check_even(i) for i in xrange(1, 1001)]
print numlist

Categories

Resources