Another project that I worked on for the past few hours has been completed. Maybe I'll do the R-P-S-Lizard-Spock (or even the 101-object version!) I thought that using an dictionary as a data structure was appropriate (and slightly creative). Pretty good, if I may say so myself.
rpsdata = {"r":["s"], "p":["r"], "s":["p"]}
def rps(s1, s2):
if s1 in rpsdata:
if s2 not in rpsdata:
print(s2 + " is not valid.")
new = raw_input("Enter a valid input: ")
rps(s1, new)
if s2 in rpsdata[s1]:
print(s1 + " wins!")
return 1
elif s1 in rpsdata[s2]:
print(s2 + " wins!")
return 0
elif s1 == s2:
print("Tie.")
return -1
else:
print(s1 + " is not valid.")
new = raw_input("Enter a valid input: ")
rps(new, s2)
roundnum = 0
p1wins = 0
p2wins = 0
while True:
s1 = raw_input("P1, enter a r, p, or s: ")
s2 = raw_input("P2, enter a r, p, or s: ")
num = rps(s1, s2)
if num == 0:
p2wins += 1
elif num == 1:
p1wins += 1
exit = raw_input("Exit? ")
roundnum += 1
if len(exit) == 0:
continue
elif exit[0].lower() == "e":
print("Thanks for playing.")
print("P1 won %.2f percent of the time." % float(100 * p1wins / roundnum))
print("P2 won %.2f percent of the time." % float(100 * p2wins / roundnum))
break
Tuesday, July 28, 2015
Tuesday, July 7, 2015
Project 5: One-Line Fizzbuzz
It's been a while since I last blogged; I figured I should write something up quickly.
Here's Fizzbuzz from the 100 projects -- in one line. Considering my usual Fizzbuzz solution takes around 8-10 lines, this is more concise. It's quite obtuse, though.
>>> def fizzbuzz(a, b, c): print "\n".join([(("Fizz"*(x%a == 0) + "Buzz"*(x%b == 0)) or str(x)) for x in range(1, c)])
>>> fizzbuzz(3, 2, 10)
1
Buzz
Fizz
Buzz
5
FizzBuzz
7
Buzz
Buzz
Fizz
>>> fizzbuzz(3, 1, 10)
Buzz
Buzz
FizzBuzz
Buzz
Buzz
FizzBuzz
Buzz
Buzz
FizzBuzz
I'm pretty proud of my solution, even if I did take the "\n".join approach from Michael Gilliland's blog entry on Fizzbuzz.
I hope to be publishing more. Thanks for reading.
Here's Fizzbuzz from the 100 projects -- in one line. Considering my usual Fizzbuzz solution takes around 8-10 lines, this is more concise. It's quite obtuse, though.
>>> def fizzbuzz(a, b, c): print "\n".join([(("Fizz"*(x%a == 0) + "Buzz"*(x%b == 0)) or str(x)) for x in range(1, c)])
>>> fizzbuzz(3, 2, 10)
1
Buzz
Fizz
Buzz
5
FizzBuzz
7
Buzz
Buzz
Fizz
>>> fizzbuzz(3, 1, 10)
Buzz
Buzz
FizzBuzz
Buzz
Buzz
FizzBuzz
Buzz
Buzz
FizzBuzz
I'm pretty proud of my solution, even if I did take the "\n".join approach from Michael Gilliland's blog entry on Fizzbuzz.
I hope to be publishing more. Thanks for reading.
Subscribe to:
Comments (Atom)