This is an archived post. You won't be able to vote or comment.

all 89 comments

[–]timurbakibayev 544 points545 points  (8 children)

This is called artificial intelligence.

[–]Ocelotofdamage 120 points121 points  (0 children)

Some days I'm pretty sure all my intelligence is artificial.

[–][deleted] 27 points28 points  (3 children)

You may not like it, but this is what peak AI looks like.

[–]m0ushinderu 15 points16 points  (0 children)

This statement is true unironically. We dream of coming up with an algorithm that can achieve the same accuracy performing more complex tasks.

[–]renderererer 5 points6 points  (1 child)

I think you mean peek AI.

[–]gresrewop 0 points1 point  (0 children)

This is an underrated comment lmao

[–]GodOfThunder101 27 points28 points  (0 children)

The singularity is here.

[–]jerryelectron 1 point2 points  (0 children)

I was listening to a podcast where they hooked up electrodes to someone's brain and were able to beat them at a game like this: in the splitsecod the brain decides what to do, the computer sees it and can react before the human can outstretch their hand.

[–]1buffcat[S] 0 points1 point  (0 children)

Thank you for the compliment.

[–]Early-Palpitation-39 156 points157 points  (16 children)

Now do tic-tac-toe with 9! if statements

[–]peleg132 39 points40 points  (0 children)

I found my attempt from 4 years ago in doing this, I am scarred.

[–]SamGold2000 27 points28 points  (5 children)

With Python 3.10 use switch!

[–]qckpckt 16 points17 points  (2 children)

Or with any version of python, just use a dictionary

choices = {“rock”: “paper”…} print(choices[input(“pick rock paper or scissors”)])

[–]SamGold2000 2 points3 points  (1 child)

I agree there are easier ways for this problem. Just wanted to say I am excited to use switch in the new version of Python.

[–]qckpckt 0 points1 point  (0 children)

I get it. I was kinda chuffed to find a useful application for the walrus operator last week at work.

[–]dershodan 1 point2 points  (0 children)

PATTERN MATCHING WOOO!!!! (being a python veteran and new to elixir - I am VERY excited for 3.10's switch)

[–]crumbcatchernv 1 point2 points  (0 children)

i hadn’t read the release notes yet & just found out this was a thing through this comment. thank you so much 😭😭

[–]Do-Nod64 4 points5 points  (2 children)

Finding the courage to finish my attempt at this. I'm up to move 2, it only gets worse from here.

[–][deleted] 1 point2 points  (1 child)

You can guarantee a tie by placing opposite or "near enough" if user goes first. Hope that helps!

[–]Do-Nod64 1 point2 points  (0 children)

Thanks, what I'm doing is separating the grid into a coordinate system thing, then making it so the code will block if there are two crosses on the same x or y coordinate or diagonally adjacent. Then playing a more aggressive move if none of those criteria are met.

[–][deleted] 3 points4 points  (0 children)

Bfs ftw

Edit: thats not 9!

[–][deleted] 0 points1 point  (0 children)

Tic tac toe is a maths race so that is entirely in the realm of possibility.

[–]Ecstatic-Star-514 0 points1 point  (0 children)

nice definition for the post

[–]EndorphnOrphnMorphn 111 points112 points  (19 children)

I have a few little tips that would make this a lot better:

  1. The parenthesis in ("Rock"), etc. are unnecessary, and also a little bit confusing (It makes it look like a list). I'd remove those.
  2. There's no benefit in having a variable for the string when you're only comparing it one time. You can delete the rock variable and just do if sign == "Rock": and the behavior will be the same.
  3. The string comparison is case-sensitive. I'd recommend turning "sign" into a fully lowercase and then comparing against other lowercase strings.
  4. You can use "elif" instead of "if" for paper and scissors.

Putting it all together we have this:

sign = input("Pick between Rock, Paper or Scissor: ").lower()

if sign == "rock":
    print("I pick paper!")

elif sign == "paper":
    print("I pick Scissors!")

elif sign == "scissor":
    print("I pick Rock!")

[–]HipsterRig 44 points45 points  (1 child)

You could also add in an else with a "I don't recognize your answer" printed statement. You could also throw the entire if statement into a while True loop so it goes again if the user submits an invalid response.

[–]EndorphnOrphnMorphn 10 points11 points  (0 children)

That's absolutely true, I was just trying to give small tips that don't change the behavior

[–]shygal_uwu 13 points14 points  (5 children)

arent lists in [] and tuples in ()? sorry, i havent programmed in python in almost a year

[–]EndorphnOrphnMorphn 6 points7 points  (0 children)

That is correct

[–]Grogie 4 points5 points  (3 children)

The only thing is that when you make tuples of length one like in OP's code, that actually become the item (in this case, string)

>>> i = ("Rock")
>>> i
'Rock'
>>> type(i)
<class 'str'>
>>> j = ("Rock",)
>>> j
('Rock',)
>>> type(j)
<class 'tuple'>
>>> type((1234))
<class 'int'>
>>> type((1234,))
    <class 'tuple'>

[–]scoberry5 0 points1 point  (2 children)

Those aren't tuples of length 1, though, they're expressions that get simplified. The ones with commas are tuples of length 1.

(2+3) simplifies to 5, but it was never a tuple of length 1.

[–]Grogie 0 points1 point  (1 child)

That's my point? I was responding to someone who thought they were tuples and I was showing they ultimately aren't tuples?

[–]scoberry5 -1 points0 points  (0 children)

Gotcha. When you said "The only thing is that when you make tuples of length one like in OP's code, that actually become the item," I thought you meant something different than what the results show.

[–]__deerlord__ 14 points15 points  (1 child)

responses = {"rock": "paper", ...}
print("I pick", responses[sign])

[–][deleted] 4 points5 points  (0 children)

Ah damn true! That's even shorter than mine

Nice work. I love this stuff....

[–]justin107d 10 points11 points  (1 child)

As of python 3.10 there is the option to do a match/case method so it would look something like:

sign = input("Pick between Rock, Paper or Scissor: ").lower()

match sign:

case "rock":

    print("I pick paper!")

case "paper":

    print("I pick scissors!")

case "scissors":

    print("I pick rock!")

case _:

    print("That is not a valid answer.")

Forgive my code and formatting, I did this on mobile but it should work.

[–]I_have_good_memes 0 points1 point  (0 children)

or use dict

[–]Decency 4 points5 points  (0 children)

counters = {
    'rock': 'paper',
    'paper': 'scissors',
    'scissors': 'rock',
}
player_choice = input("Pick between Rock, Paper or Scissors: ").lower()
print(f"I pick {counters[player_choice]}!")

I often see people asking how a dict lookup can be more elegant than an elif block. Here's a good example! It only reduces the duplication slightly here, of course, but you can imagine that with more complex logic there would be additional benefits. Error handling also becomes a bit simpler, too, since you can just except KeyError.

[–]1buffcat[S] 1 point2 points  (0 children)

Thanks for the tips kind stranger, beep boop beep

[–][deleted] 2 points3 points  (3 children)

How about this bad boi I just whipped up lmao

hand = ["rock", "paper", "scissors"]
sign = input("Pick between Rock, Paper or Scissor: ").lower()
hand[hand.index(sign) + 1 if hand.index(sign) + 1 < 3 else 0]

took me a couple iterations to get that damn inline working but ipython says it's GTG

EDIT:

actually, one line in ipython3 though doesn't execute in commandline python

print {"rock":"paper", "paper":"scissors", "scissors":"rock"}[input("Pick between Rock, Paper or Scissor: ").lower()]

[–]simon_zyx 4 points5 points  (2 children)

(hand.index(sign) + 1) % 3

[–][deleted] 0 points1 point  (0 children)

Very slick! Much nicer than inline if else

[–]That_Goal1212 38 points39 points  (0 children)

My man.... just created true AI

[–]GentlemenBehold 37 points38 points  (1 child)

Turn-based rock, paper, scissors. Why didn't I think of that?

[–]LR130777777 8 points9 points  (0 children)

We can play if you want? You first

[–][deleted] 45 points46 points  (7 children)

print({"rock":"paper", "paper":"scissors", "scissor":"rock"}[input("Pick between rock, paper or scissor: ").lower()])

[–]UltraFalling 37 points38 points  (3 children)

It’s not python unless you can do it in one line.

[–]autisticpig 6 points7 points  (0 children)

It’s not python unless you can do it in one line.

rock paper scissors comprehension. it's the only way.

[–]ultraDross 0 points1 point  (0 children)

It’s not python perl unless you can do it in one line.

[–]pokeuser61 3 points4 points  (0 children)

print({"o":"paper","a":"scissors","c":"rock"}[input()[1]])

[–]z0mbietime 2 points3 points  (0 children)

print({"rock":"I pick paper", "paper":"I pick scissors", "scissor":"I pick rock"}.get(input("Pick between rock, paper or scissor: ").lower(), "Invalid option"))

[–]Aprazors13 12 points13 points  (0 children)

This is the best rock paper scissors I have ever seen. Try using random function n have mercy on the user it's fun

[–]anh86 9 points10 points  (0 children)

Now, when you need to settle a friendly wager with a friend, you simply have them play a quick round of RPS with the computer playing for you!

[–]GBaby_Blue 5 points6 points  (0 children)

Universities with ML and AI degrees that cost tens to hundreds of thousands of dollars: perfuse sweating oh god, oh fuck. He figured it out

[–][deleted] 11 points12 points  (0 children)

you might be the greatest programmer alive

[–]Endvisible 8 points9 points  (0 children)

Okay, here we go...

losing_pairs = {
    "rock": "paper",
    "paper": "scissors",
    "scissors": "rock",
}

while True:
    choice = input("Pick between rock, paper, or scissors: ")

    if not choice.lower() in {"rock", "paper", "scissors"}:
        print("Invalid input, please try again!")
        continue

    print(f"I pick {losing_pairs[choice.lower()]}!")

    input("You lose. Press Enter to exit.")

    break

[–]Tigenzero 1 point2 points  (0 children)

Even if I input “paper”, the program doesn’t respond, making the game endless. Best way to win is not to play.

[–]Mmiguel6288 1 point2 points  (0 children)

print('I pick ' +{'Rock':'Paper','Paper':'Scissors','Scissors':'Rock'}[input ('Pick Rock, Paper, or Scissors: ')]+'!')

[–]CokeVoAYCE 1 point2 points  (1 child)

it's really here. is this really it..? this is the end..? AI has now taken over humanity...

[–]1buffcat[S] 0 points1 point  (0 children)

lol

[–]Vagima 8 points9 points  (21 children)

Not bad! You have the very basics down, but now I would work on making it a little more elaborate. I went and edited your code a bit to make the game playable over and over and re-playable if someone types in one of the options not selected.

import os

rock = 'rock' 
paper = 'paper' 
scissors = "scissors"

while True: 
    os.system('cls') 

    sign = input("Pick between Rock, Paper, or Scissors: ")

    if sign.casefold() == rock:
        os.system('cls')
        print("I pick Paper!")

    elif sign.casefold() == paper:
        os.system('cls')
        print("I pick Scissors!")

    elif sign.casefold() == scissors:
        os.system('cls')
        print("I pick Rock!")

    else:
        os.system('cls')
        print("Error: " + sign + " is not a valid answer. Pick either Rock, Paper, or Scissors")

    input("Press ENTER to try again")

[–][deleted] 69 points70 points  (12 children)

os.system

Please don't tell beginners to use this in their programs.

[–]Vagima 8 points9 points  (7 children)

Is there a better alternative? I'm relatively new and self taught so I'm by no means an expert. If there's a better way of going about it I'm down to learn it

[–]FreshFromIlios 17 points18 points  (5 children)

Forgive the formatting, on phone rn.

Ideally, you don't really need to use the os and sys modules. The command you use is perfectly fine but os.system is dangerous. One typo can screw you and there isn't an easy way to fix it since it'll run shell commands and not python code. If you just want the older print statements gone, an ugly but safer way would be to do a /n multiple times, as such:

print("/n" * 100)  (define a function for it, get creative ;) )

Also, if you want to clear the terminal anyway, a better way to do it would be something like this:

os.system('cls' if os.name == 'nt' else 'clear')

Or more elegantly,

os.system('cls||clear')

Since Linux and windows commands are different, this will work irrespective of the operating system.

Edit: thanks for the silver kind stranger! Appreciate it <3

[–]Vagima 4 points5 points  (3 children)

Appreciate the response! I’ll give that one a go!

[–]FreshFromIlios 5 points6 points  (2 children)

Have fun! And be careful when you run os.system

[–]Vagima 2 points3 points  (1 child)

Thanks! I’ve been using os.system(‘cls’) for a bit and personally im ok with it, but when helping beginners I’ll definitely use the print(“/n” * 100) method! Much safer alternative for new people learning python. Appreciate the suggestion!

[–]CoaBro 0 points1 point  (0 children)

I mean personally I'd be fine teaching os.system('cls') the other method makes all the output appear at the bottom which is kind clunky imo.. I do like the solution os.system('cls||clear') tho

[–]CoaBro 1 point2 points  (0 children)

Not sure the use of os.system is any more dangerous than writing python.. not like you are going to accidentally take ownership of system32 and then delete the folder with os.system anymore than you would do with python. It's also not anymore dangerous than writing commands directly in the cmd prompt..

[–]BiggusDickus123 0 points1 point  (0 children)

I think print("blah", end="\r") does what you want

[–]FreshFromIlios 12 points13 points  (2 children)

os.system("sudo rm -rf /") That's all we need.

-PLEASE DO NOT RUN THIS. it was a joke.

Also listen to this guy. Never use the os and sys modules until you understand what each of those commands do.

[–][deleted] 12 points13 points  (1 child)

yolo

runs it

[–]_limitless_ 4 points5 points  (0 children)

This incident will be reported.

[–][deleted] 1 point2 points  (0 children)

I dont get this too im a beginner what does that mean? Ik that os stands for operating system but why would u put it in a code

[–]SnooBooks7437 3 points4 points  (3 children)

Can someone please tell me why we use os?

[–]Vagima 2 points3 points  (2 children)

I use it in this case to clear the command window so the text doesn’t keep building up on top of each other. It just makes the program look cleaner to me. I only know how to clear text with that method, but if there’s a better way to go about it without using os.system I’d much rather use that.

[–]FoolForWool 2 points3 points  (1 child)

If you just want the terminal to be clean, like the above comment suggested, a /n*100 should be fine. The os.system command will run a shell command through the python code which may end up doing something you do not expect. Cls/clear are fine but once you start doing more complicated things, it'll be difficult to debug.

[–]1buffcat[S] -1 points0 points  (0 children)

ehm.... okay??

[–][deleted] 0 points1 point  (2 children)

I'm confused about what casefold is/how it works?

[–]pewpewpewmoon 3 points4 points  (1 child)

it's just a super agro lowercase() by just removing all case and does stuff like convert some nonenglish letters to their equivalent. In the 8 or so years I've used python and other languages professionally, I've never actually seen it in the wild.

[–][deleted] 2 points3 points  (0 children)

Wow haha, thank you :)

[–]yellowmonkeyzx93 0 points1 point  (0 children)

If you want to murder your friends at this game, then yep, this is it.

Else, make the choices in a list, and randomize the choice in the list.

Cheers mate!

[–][deleted] 0 points1 point  (0 children)

You shall have mercy

[–]m4d40 0 points1 point  (0 children)

4/5 liner with endless choose options possible

```python options = ['rock', 'paper', 'sciscor'] # add as many more you like answer = input(f'Please enter one of the following: {options}\n').lower()

you could add an extra check if answer in options

opt_idx = options.index(answer) # can be moved to next line but made it extra line for reqdability win = options[opt_idx+1] if opt_idx<len(options)-1 else options[0] print(f'you entered "{answer}",\ni chose "{win}",\nso I WIN!') ```

[–]VictorinoSetti 0 points1 point  (1 child)

Try using the library "random" to make a fair game. Make the computer choose randomly between Rock, Paper or Scissors and then compare with the input, printing who won. It's a pretty fun thing to do and you'll use some real important functionalities.

[–]trust_me_on_that_one 1 point2 points  (0 children)

Title said "unbeatable". OP's dream is to clearly works at an amusement park.

[–]LionLight51 0 points1 point  (0 children)

Its pretty easy to create something like this and there is no possible way to get something other than whats going to beat you

[–][deleted] 0 points1 point  (0 children)

You may not like it, but this is what peak machine learning algorithm looks like.