SlideShare a Scribd company logo
1 of 11
For any help regarding Python Homework Help
visit : - https://www.pythonhomeworkhelp.com/,
Email :- support@pythonhomeworkhelp.com or
call us at :- +1 678 648 4277
Problem 1 - Login security
In this problem, we'll create a login screen, where the user must enter a password in
order to see a secret message. We will give the user 3 chances to get the password right,
and either print the secret message or a failure message (after 3 chances).
First, define a function encrypt that takes one string. It will hash the string using the built-
in Python function hash (try it on the shell) and modulo the value by a prime number (e.g.
541 -- this is very small in the computer science world but good enough for us). The
function should then return this number.
e.g. encrypt("mypassword") -> 283 (if you use 541 as the prime, for example) At the top
of the file, define a variable _KEY to be the result, e.g. _KEY = 283.
Now, write the rest of the program. Each time you ask the user for the password, call
encrypt with the user's input, and compare the value to _KEY. If the two match, the user
(most likely) entered the correct password, otherwise he loses one chance.
Problem 2 - The game of Nims / Stones
In this game, two players sit in front of a pile of 100 stones. They take turns, each removing
between 1 and 5 stones (assuming there are at least 5 stones left in the pile). The person
who removes the last stone(s) wins.
Write a program to play this game. This may seem tricky, so break it down into parts. Like
many programs, we have to use nested loops (one loop inside another).
In the outermost loop, we want to keep playing until we are out of stones.
Inside that, we want to keep alternating players. You have the option of either writing two
blocks of code, or keeping a variable that tracks the current player. The second way is
slightly trickier since we haven't learned lists yet, but it's definitely do-able!
Finally, we might want to have an innermost loop that checks if the user's input is valid. Is
it a number? Is it a valid number (e.g. between 1 and 5)? Are there enough stones in the
pile to take off this many? If any of these answers are no, we should tell the user and re-
ask them the question.
So, the basic outline of the program should be something like this:
TOTAL = 100
MAX = 5
pile = TOTAL # all stones are in the pile to start while [pile is not empty]:
while [player 1's answer is not valid]: [ask player 1]
[check player 1's input... is it valid?] [same as above for player 2]
Note how the important numbers 100 and 5 are stored in a single variable at the top. This
is good practice -- it allows you to easily change the constants of a program. For example,
for testing, you may want to start with only 15 or 20 stones.
Be careful with the validity checks. Specifically, we want to keep asking player 1 for their
choice as long as their answer is not valid, BUT we want to make sure we ask them at least
ONCE. So, for example, we will want to keep a variable that tracks whether their answer is
valid, and set it to False initially.
When you're finished, test each other's programs by playing them!
Solution 1:
# Some constants...
LARGE_PRIME = 541
_KEY = 171 # to get this number, I used the password "solution"
MAX_FAILURES = 3 # stop when we hit this many failures
# The encrypt function. Remember, functions shouldn't be asking for input or
# printing their result. Any input a function needs (in this case, a string to
# encrypt) should be passed in, and the output should be returned.
def encrypt(text):
return hash(text) % LARGE_PRIME
# Main program code
num_failures = 0
# We'll keep looping until we hit the max number of failures...
# We need to break out of the loop when we get it correct also, see below.
while num_failures < MAX_FAILURES:
login = raw_input("Please enter the password: ")
if encrypt(login) == _KEY:
print "Correct!"
break # remember, this breaks out of the current loop
else:
num_failures = num_failures + 1
print "Incorrect! You have failed", num_failures, "times."
# When we get here, it's either because num_failures == MAX_FAILURES, or
# because we hit the break statement (i.e. we got the correct login), so...
if num_failures >= MAX_FAILURES:
print "Sorry, you have hit the maximum number of failures allowed."
Solution 2: Nims 1
#
print ' ____...----....'
print ' |""--..__...------._'
print ' `""--..__|.__ `.'
print ' | ` |'
print ' | | |'
print ' / | |'
print ' __' / |'
print ' ,' ""--..__ ,-' |'
print '|""--..__ ,' |'
print '| ""| |'
print '| ; , | |'
print '| ' | |"'
print '| | |.-.___'
print '| | | "---(='
print '|__ | __..''
print ' ""--..__|__..--""'
print
print "Welcome to Nim!"
#get a valid initial pile size
pile_size = int(raw_input("How many stones would you like to start with?n"))
while pile_size <= 0:
pile_size = int(raw_input("You need to start with at least one stone in the pile!n"))
#2 players; player 1 and player 2. Start with player 1
player = 1
#main game loop
while pile_size > 0:
prompt = "Player " + str(player) + ", there are " + str(pile_size) + " stones in front of you.
" + 
"How many stones would you like to remove (1-5)?n"
move = int(raw_input(prompt))
if move <= 0:
print "Hey! You have to remove at least one stone!"
elif move > pile_size:
print "There aren't even that many stones in the pile..."
elif move > 5:
print "You can't remove more than five stones."
else:
#if we're here, they gave a valid move
pile_size = pile_size - move
player = 2-(player-1) #this is kind of cute: changes 1 to 2 and 2 to 1.
#If we've exited the loop, the pile size is 0. The player whose turn it is NOW just lost the
game..
print "Player", 2-(player-1), "has won the game!"
Solution 2: Nims 2
TOTAL = 100
MAX = 5
pile = TOTAL # number of stones in the pile at any given time
def is_valid(x):
# returns True iff x is between 1 and MAX, and there's also enough stones,
# otherwise returns False
return (x >= 1) and (x <= MAX) and (x <= pile)
while pile > 0:
# player 1 turn
print "Player 1's turn. There are", pile, "stones in the pile."
x = 0
while not is_valid(x):
# ask
x = int(raw_input("Player 1, how many? "))
# check
if not is_valid(x):
print "That's not valid, it has to be between 1 and 5, and",
"you can't pick up more than there are in the pile."
pile = pile - x
if pile == 0:
# win -- do something
print "Congratulations, Player 1, you win!"
break
# player 2 turn
print "Player 2's turn. There are", pile, "stones in the pile."
y = 0
while not is_valid(y):
y = int(raw_input("Player 2, how many? "))
if not is_valid(x):
print "That's not valid, it has to be between 1 and 5, and",
"you can't pick up more than there are in the pile."
pile = pile - y
if pile == 0:
# win -- do something
print "Congratulations, Player 2, you win!"
break
print "Game over."

More Related Content

Similar to Python Homework Help

Java Guessing Game Number Tutorial
Java Guessing Game Number TutorialJava Guessing Game Number Tutorial
Java Guessing Game Number TutorialOXUS 20
 
1 ECE 175 Computer Programming for Engineering Applica.docx
1  ECE 175 Computer Programming for Engineering Applica.docx1  ECE 175 Computer Programming for Engineering Applica.docx
1 ECE 175 Computer Programming for Engineering Applica.docxoswald1horne84988
 
Introduction to Genetic Algorithms with Python - Hello World!
Introduction to Genetic Algorithms with Python  - Hello World!Introduction to Genetic Algorithms with Python  - Hello World!
Introduction to Genetic Algorithms with Python - Hello World!Cℓinton Sheppard
 
Pythonlearn-03-Conditional.pptx
Pythonlearn-03-Conditional.pptxPythonlearn-03-Conditional.pptx
Pythonlearn-03-Conditional.pptxVigneshChaturvedi1
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fuclimatewarrior
 
This is all about control flow in python intruducing the Break and Continue.pptx
This is all about control flow in python intruducing the Break and Continue.pptxThis is all about control flow in python intruducing the Break and Continue.pptx
This is all about control flow in python intruducing the Break and Continue.pptxelezearrepil1
 
Teeing Up Python - Code Golf
Teeing Up Python - Code GolfTeeing Up Python - Code Golf
Teeing Up Python - Code GolfYelp Engineering
 
Python+Syntax+Cheat+Sheet+Booklet.pdf
Python+Syntax+Cheat+Sheet+Booklet.pdfPython+Syntax+Cheat+Sheet+Booklet.pdf
Python+Syntax+Cheat+Sheet+Booklet.pdfGanteng tengab
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2Mohamed Ahmed
 
Ecs 10 programming assignment 4 loopapalooza
Ecs 10 programming assignment 4   loopapaloozaEcs 10 programming assignment 4   loopapalooza
Ecs 10 programming assignment 4 loopapaloozaJenniferBall44
 
You will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfYou will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfFashionColZone
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School ProgrammersSiva Arunachalam
 

Similar to Python Homework Help (20)

Java Guessing Game Number Tutorial
Java Guessing Game Number TutorialJava Guessing Game Number Tutorial
Java Guessing Game Number Tutorial
 
Python.pptx
Python.pptxPython.pptx
Python.pptx
 
1 ECE 175 Computer Programming for Engineering Applica.docx
1  ECE 175 Computer Programming for Engineering Applica.docx1  ECE 175 Computer Programming for Engineering Applica.docx
1 ECE 175 Computer Programming for Engineering Applica.docx
 
Introduction to Genetic Algorithms with Python - Hello World!
Introduction to Genetic Algorithms with Python  - Hello World!Introduction to Genetic Algorithms with Python  - Hello World!
Introduction to Genetic Algorithms with Python - Hello World!
 
Python Math Concepts Book
Python Math Concepts BookPython Math Concepts Book
Python Math Concepts Book
 
OS.pdf
OS.pdfOS.pdf
OS.pdf
 
Pythonlearn-03-Conditional.pptx
Pythonlearn-03-Conditional.pptxPythonlearn-03-Conditional.pptx
Pythonlearn-03-Conditional.pptx
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
This is all about control flow in python intruducing the Break and Continue.pptx
This is all about control flow in python intruducing the Break and Continue.pptxThis is all about control flow in python intruducing the Break and Continue.pptx
This is all about control flow in python intruducing the Break and Continue.pptx
 
Teeing Up Python - Code Golf
Teeing Up Python - Code GolfTeeing Up Python - Code Golf
Teeing Up Python - Code Golf
 
Python+Syntax+Cheat+Sheet+Booklet.pdf
Python+Syntax+Cheat+Sheet+Booklet.pdfPython+Syntax+Cheat+Sheet+Booklet.pdf
Python+Syntax+Cheat+Sheet+Booklet.pdf
 
pyton Notes9
pyton Notes9pyton Notes9
pyton Notes9
 
C++ Course - Lesson 2
C++ Course - Lesson 2C++ Course - Lesson 2
C++ Course - Lesson 2
 
Loops in Python.pptx
Loops in Python.pptxLoops in Python.pptx
Loops in Python.pptx
 
While loop
While loopWhile loop
While loop
 
Python-Tuples
Python-TuplesPython-Tuples
Python-Tuples
 
Ruby Intro {spection}
Ruby Intro {spection}Ruby Intro {spection}
Ruby Intro {spection}
 
Ecs 10 programming assignment 4 loopapalooza
Ecs 10 programming assignment 4   loopapaloozaEcs 10 programming assignment 4   loopapalooza
Ecs 10 programming assignment 4 loopapalooza
 
You will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdfYou will write a multi-interface version of the well-known concentra.pdf
You will write a multi-interface version of the well-known concentra.pdf
 
Python for High School Programmers
Python for High School ProgrammersPython for High School Programmers
Python for High School Programmers
 

More from Python Homework Help

Introduction to Python Dictionary.pptx
Introduction to Python Dictionary.pptxIntroduction to Python Dictionary.pptx
Introduction to Python Dictionary.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptxPython Homework Help
 
Python Programming Homework Help.pptx
Python Programming Homework Help.pptxPython Programming Homework Help.pptx
Python Programming Homework Help.pptxPython Homework Help
 

More from Python Homework Help (20)

Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Complete my Python Homework
Complete my Python HomeworkComplete my Python Homework
Complete my Python Homework
 
Introduction to Python Dictionary.pptx
Introduction to Python Dictionary.pptxIntroduction to Python Dictionary.pptx
Introduction to Python Dictionary.pptx
 
Basic Python Programming.pptx
Basic Python Programming.pptxBasic Python Programming.pptx
Basic Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Introduction to Python Programming.pptx
Introduction to Python Programming.pptxIntroduction to Python Programming.pptx
Introduction to Python Programming.pptx
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 
Python Programming Homework Help.pptx
Python Programming Homework Help.pptxPython Programming Homework Help.pptx
Python Programming Homework Help.pptx
 
Quality Python Homework Help
Quality Python Homework HelpQuality Python Homework Help
Quality Python Homework Help
 
Perfect Python Homework Help
Perfect Python Homework HelpPerfect Python Homework Help
Perfect Python Homework Help
 
Python Homework Help
Python Homework HelpPython Homework Help
Python Homework Help
 

Recently uploaded

JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 

Recently uploaded (20)

JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 

Python Homework Help

  • 1. For any help regarding Python Homework Help visit : - https://www.pythonhomeworkhelp.com/, Email :- support@pythonhomeworkhelp.com or call us at :- +1 678 648 4277
  • 2. Problem 1 - Login security In this problem, we'll create a login screen, where the user must enter a password in order to see a secret message. We will give the user 3 chances to get the password right, and either print the secret message or a failure message (after 3 chances). First, define a function encrypt that takes one string. It will hash the string using the built- in Python function hash (try it on the shell) and modulo the value by a prime number (e.g. 541 -- this is very small in the computer science world but good enough for us). The function should then return this number. e.g. encrypt("mypassword") -> 283 (if you use 541 as the prime, for example) At the top of the file, define a variable _KEY to be the result, e.g. _KEY = 283. Now, write the rest of the program. Each time you ask the user for the password, call encrypt with the user's input, and compare the value to _KEY. If the two match, the user (most likely) entered the correct password, otherwise he loses one chance.
  • 3. Problem 2 - The game of Nims / Stones In this game, two players sit in front of a pile of 100 stones. They take turns, each removing between 1 and 5 stones (assuming there are at least 5 stones left in the pile). The person who removes the last stone(s) wins. Write a program to play this game. This may seem tricky, so break it down into parts. Like many programs, we have to use nested loops (one loop inside another). In the outermost loop, we want to keep playing until we are out of stones. Inside that, we want to keep alternating players. You have the option of either writing two blocks of code, or keeping a variable that tracks the current player. The second way is slightly trickier since we haven't learned lists yet, but it's definitely do-able! Finally, we might want to have an innermost loop that checks if the user's input is valid. Is it a number? Is it a valid number (e.g. between 1 and 5)? Are there enough stones in the pile to take off this many? If any of these answers are no, we should tell the user and re- ask them the question.
  • 4. So, the basic outline of the program should be something like this: TOTAL = 100 MAX = 5 pile = TOTAL # all stones are in the pile to start while [pile is not empty]: while [player 1's answer is not valid]: [ask player 1] [check player 1's input... is it valid?] [same as above for player 2] Note how the important numbers 100 and 5 are stored in a single variable at the top. This is good practice -- it allows you to easily change the constants of a program. For example, for testing, you may want to start with only 15 or 20 stones. Be careful with the validity checks. Specifically, we want to keep asking player 1 for their choice as long as their answer is not valid, BUT we want to make sure we ask them at least ONCE. So, for example, we will want to keep a variable that tracks whether their answer is valid, and set it to False initially. When you're finished, test each other's programs by playing them!
  • 5. Solution 1: # Some constants... LARGE_PRIME = 541 _KEY = 171 # to get this number, I used the password "solution" MAX_FAILURES = 3 # stop when we hit this many failures # The encrypt function. Remember, functions shouldn't be asking for input or # printing their result. Any input a function needs (in this case, a string to # encrypt) should be passed in, and the output should be returned. def encrypt(text): return hash(text) % LARGE_PRIME # Main program code num_failures = 0 # We'll keep looping until we hit the max number of failures... # We need to break out of the loop when we get it correct also, see below.
  • 6. while num_failures < MAX_FAILURES: login = raw_input("Please enter the password: ") if encrypt(login) == _KEY: print "Correct!" break # remember, this breaks out of the current loop else: num_failures = num_failures + 1 print "Incorrect! You have failed", num_failures, "times." # When we get here, it's either because num_failures == MAX_FAILURES, or # because we hit the break statement (i.e. we got the correct login), so... if num_failures >= MAX_FAILURES: print "Sorry, you have hit the maximum number of failures allowed."
  • 7. Solution 2: Nims 1 # print ' ____...----....' print ' |""--..__...------._' print ' `""--..__|.__ `.' print ' | ` |' print ' | | |' print ' / | |' print ' __' / |' print ' ,' ""--..__ ,-' |' print '|""--..__ ,' |' print '| ""| |' print '| ; , | |' print '| ' | |"' print '| | |.-.___' print '| | | "---(=' print '|__ | __..'' print ' ""--..__|__..--""' print print "Welcome to Nim!"
  • 8. #get a valid initial pile size pile_size = int(raw_input("How many stones would you like to start with?n")) while pile_size <= 0: pile_size = int(raw_input("You need to start with at least one stone in the pile!n")) #2 players; player 1 and player 2. Start with player 1 player = 1 #main game loop while pile_size > 0: prompt = "Player " + str(player) + ", there are " + str(pile_size) + " stones in front of you. " + "How many stones would you like to remove (1-5)?n" move = int(raw_input(prompt)) if move <= 0: print "Hey! You have to remove at least one stone!" elif move > pile_size: print "There aren't even that many stones in the pile..." elif move > 5: print "You can't remove more than five stones." else:
  • 9. #if we're here, they gave a valid move pile_size = pile_size - move player = 2-(player-1) #this is kind of cute: changes 1 to 2 and 2 to 1. #If we've exited the loop, the pile size is 0. The player whose turn it is NOW just lost the game.. print "Player", 2-(player-1), "has won the game!" Solution 2: Nims 2 TOTAL = 100 MAX = 5 pile = TOTAL # number of stones in the pile at any given time def is_valid(x): # returns True iff x is between 1 and MAX, and there's also enough stones, # otherwise returns False return (x >= 1) and (x <= MAX) and (x <= pile) while pile > 0:
  • 10. # player 1 turn print "Player 1's turn. There are", pile, "stones in the pile." x = 0 while not is_valid(x): # ask x = int(raw_input("Player 1, how many? ")) # check if not is_valid(x): print "That's not valid, it has to be between 1 and 5, and", "you can't pick up more than there are in the pile." pile = pile - x if pile == 0: # win -- do something print "Congratulations, Player 1, you win!" break # player 2 turn print "Player 2's turn. There are", pile, "stones in the pile." y = 0
  • 11. while not is_valid(y): y = int(raw_input("Player 2, how many? ")) if not is_valid(x): print "That's not valid, it has to be between 1 and 5, and", "you can't pick up more than there are in the pile." pile = pile - y if pile == 0: # win -- do something print "Congratulations, Player 2, you win!" break print "Game over."