Skip to content

Instantly share code, notes, and snippets.

@ibelgin
Last active September 23, 2020 09:33
Show Gist options
  • Save ibelgin/3d3bd2a6d18323be052cfbb3e85c6d77 to your computer and use it in GitHub Desktop.
Save ibelgin/3d3bd2a6d18323be052cfbb3e85c6d77 to your computer and use it in GitHub Desktop.
Answers practicepython.org
# Create a program that asks the user to enter their name and their age.
# Print out a message addressed to them that tells them the year that they will turn 100 years old.
name , age = input("Enter Your Name -> ") , int(input("Enter Your Age -> "))
print(2020 + (100-age))
# Ask the user for a number. Depending on whether the number is even or odd,
# print out an appropriate message to the user.
# Hint: how does an even / odd number react differently when divided by 2?
if int(input("Enter The Number -> "))%2 == 0:
print("Its An Even Number")
else:
print("Its An Odd Number")
# Take a list, say for example this one:
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# and write a program that prints out all the elements of the list that are less than 5.
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
print([items for items in a if items<5])
# Create a program that asks the user for a number and then prints out a list of all the divisors of that number.
# (If you don’t know what a divisor is, it is a number that divides evenly into another number.
# For example, 13 is a divisor of 26 because 26 / 13 has no remainder.)
num = int(input("Enter the Number -> "))
print([items for items in range(1,num) if num%items ==0])
# Take two lists, say for example these two:
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# and write a program that returns a list that contains only the elements that are common between the lists (without duplicates).
# Make sure your program works on two lists of different sizes.
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
a , b = set(a),set(b)
print(list(a.union(b)))
# Ask the user for a string and print out whether this string is a palindrome or not.
#(A palindrome is a string that reads the same forwards and backwards.)
strg=input("Enter A String -> ")
if strg[::-1] == strg :
print("Palindrome")
else:
print("Not Palindrome")
# Let’s say I give you a list saved in a variable: a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100].
# Write one line of Python that takes this list a and makes a new list that has only the even elements of this list in it.
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
print([items for items in a if items%2==0])
# Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input),
# compare them, print out a message of congratulations to the winner, and ask if the players want to start a new game)
# Remember the rules: Rock beats scissors , Scissors beats paper , Paper beats rock
print("This is A Rock Paper Scissor Game \n ")
a=[
["rock","scissors"],
["paper","rock"],
["scissors","paper"]
]
available = ["rock","paper","scissors"]
while True:
option1 = input("player 1 -> ")
option2 = input("Player 2 -> ")
print(" ")
if option1 == option2:
print("\n Thats A DRAW :) \n")
break
elif option1==exit or option2 == "exit":
print("Came Out)")
break
else:
for i in range(0,3):
if option1 == a[i][0] and option2 in available:
if option2 == a[i][1] :
print("\n Congratulations ! {} \n".format("player 1"))
break
else:
print("\n Congratulations ! {} \n".format("player 2"))
break
else:
continue
# Generate a random number between 1 and 9 (including 1 and 9). Ask the user to guess the number,
# then tell them whether they guessed too low, too high, or exactly right.
# (Hint: remember to use the user input lessons from the very first exercise)
import random
no_of_guess = 0
num = random.randint(0,9)
while True:
try:
user_input = input("Enter Your Guess -> ")
if user_input == "exit":
break
elif int(user_input) < num:
print("You Went Too Low")
no_of_guess+=1
elif int(user_input) > num:
print("You Went Too High")
no_of_guess+=1
elif int(user_input) == num:
print("You Have Got it ! It Took You ",no_of_guess," to Find The Answer")
cont = input("Do You Want To Continue Y/N ")
if cont == "Y":
no_of_guess = 0
num = random.randint(0,9)
continue
else:
break
else:
print("Enter A Valid Number Or String")
except:
print("Enter A Word Or A Number")
# Make a two-player Rock-Paper-Scissors game. (Hint: Ask for player plays (using input),
# compare them, print out a message of congratulations to the winner, and ask if the players want to start a new game)
# Remember the rules: Rock beats scissors , Scissors beats paper , Paper beats rock
print("This is A Rock Paper Scissor Game \n ")
player1 = input("Enter Player 1 Name -> ")
player2 = input("Enter Player 2 Name -> ")
winrule = {
'rock': 'scissors',
'paper': 'rock',
'scissors': 'paper'
}
print("")
while True:
option1 = input("{} Choise -> ".format(player1))
option2 = input("{} Choise -> ".format(player2))
print(" ")
if option1 not in winrule or option2 not in winrule:
print("Error - invalid option\n")
elif option1 == option2:
print("\n Thats A DRAW :) \n")
elif option2 == winrule[option1]:
print("\n Congratulations ! {} \n".format(player1))
else:
print("\n Congratulations ! {} \n".format(player2))
# take two lists, say for example these two:
# a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
# b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# and write a program that returns a list that contains only the elements
# that are common between the lists (without duplicates). Make sure your program works on
# two lists of different sizes. Write this in one line of Python using at least one list comprehension
a = list(set([1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]))
b = list(set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]))
for_a = [ items for items in a if items in b]
print(for_a)
# Ask the user for a number and determine whether the number is prime or not.
# (For those who have forgotten, a prime number is a number that has no divisors.).
num = int(input("Enter A Number -> "))
test_list = [i for i in range(2,num) if num % i == 0]
if len(test_list) == 0:
print("Prime Number")
else :
print("Not A Prime Number")
# Write a program that takes a list of numbers (for example, a = [5, 10, 15, 20, 25])
# and makes a new list of only the first and last elements of the given list. For practice, write this code inside a function.
user_inp = int(input("Enter The Number Of Elements To Add -> "))
a=[]
for i in range(0,user_inp):
temp = int(input("Enter Element {} ".format(i)))
a.append(temp)
def Last_First():
return [a[0],a[len(a)-1]]
first_element , last_element = Last_First()
print("First Element is ",first_element)
print("Last Element is ",last_element)
# Write a program that asks the user how many Fibonnaci numbers to generate and then generates them.
# Take this opportunity to think about how you can use functions. Make sure to ask the user to enter
# the number of numbers in the sequence to generate.(Hint: The Fibonnaci seqence is a sequence of numbers
# where the next number in the sequence is the sum of the previous two numbers in the sequence.
# The sequence looks like this: 0 , 1, 1, 2, 3, 5, 8, 13, …)
def fib_dis(n):
start = 0
second = 1
print(start)
print(second)
for i in range(2,n):
c = start + second
start , second = second , c
print(c)
fib_dis(int(input("Enter The Number ")))
# Write a program (function!) that takes a list and returns a new list that contains all the elements of
# the first list minus all the duplicates.
def ret_list(listy):
return list(set(listy))
print(ret_list([1,3,4,2,3,1,2,3]))
# Write a program (using functions!) that asks the user for a long string containing multiple words.
#Print back to the user the same string, except with the words in backwards order. For example, say I type the string:
# My name is Michele
# Then I would see the string:
# Michele is name My
# shown back to me.
a="Hi I am Belgin Android"
b = a.split(" ")
final_str = ""
for i in range(len(b)-1,0,-1):
final_str+=b[i]+" "
print(final_str.strip())
# Write a password generator in Python. Be creative with how you generate passwords -
# strong passwords have a mix of lowercase letters, uppercase letters, numbers, and symbols.
# The passwords should be random, generating a new password every time the user asks for a new password.
# Include your run-time code in a main method.
import random
numbers = random.randint(0,9)
listy = [ chr(item) for item in range(65,91)] + [chr(item) for item in range(97,123) ] + ["~",'`',"!","@","#","$","%","^",".","&","*","(",")","?",">","<"]
def create_password(length):
final = ""
for i in range(0,length):
final+= listy[random.randint(1,len(listy)-1)]
return final
print("Your Final Password -> ", create_password(12))
# Under Construction
# Randomly generate a 4-digit number. Ask the user to guess a 4-digit number. For every digit that the user guessed
# correctly in the correct place, they have a “cow”. For every digit the user guessed correctly in the wrong place is a “bull.”
# Every time the user makes a guess, tell them how many “cows” and “bulls” they have.
# Once the user guesses the correct number, the game is over. Keep track of the number of guesses the user makes throughout
# teh game and tell the user at the end.
#Enter a number:
#>>> 1234
#2 cows, 0 bulls
#>>> 1256
#1 cow, 1 bull
import random
num = random.randint(1000,9999)
user_input = int(input("Enter Your Guess -> "))
if user_input == num:
print("You Are Right !")
elif len(str(user_input)) == 4:
listx = list(str(num))
listy = list(str(user_input))
temp_correct =[i for i in listy for j in listx if i == j]
#print(listx)
#print(listy)
print("Cow --> ",len(temp_correct))
print("Bull --> ",4-len(temp_correct))
else:
print("Enter A 4 Digit Integer")
# Under Construction
# Write a function that takes an ordered list of numbers (a list where the elements are in order from smallest to largest)
# and another number. The function decides whether or not the given number is inside the list and returns (then prints)
# an appropriate boolean.
# Write a function that takes an ordered list of numbers (a list where the elements are in order from smallest to largest)
# and another number. The function decides whether or not the given number is inside the list and returns (then prints)
# an appropriate boolean.
def binary_search(listy, x):
low = 0
high = len(listy) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if listy[mid] < x:
low = mid + 1
elif listy[mid] > x:
high = mid - 1
else:
return mid
return -1
listy = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
result = binary_search(listy, x)
if result != -1:
print("Element is present" )
else:
print("Element is not present ")
#Take the code from the How To Decode A Website exercise (if you didn’t do it or just want to play with some different
# code, use the code from the solution), and instead of printing the results to a screen, write the results to a txt file.
# In your code, just make up a name for the file you are saving to.
string = ''' This is bla bla bla bla bla bla bla bla '''
with open('file_to_save.txt', 'w') as open_file:
open_file.write()
# Given a .txt file that has a list of a bunch of names, count how many of each name there are in the file, and print out
# the results to the screen. I have a .txt file for you, if you want to use it!
a = {}
with open("name.txt","r") as fp:
for i in fp.readlines():
if i.strip() not in a.keys():
a[i.strip()] = 1
elif i.strip() in a.keys():
a[i.strip()] += 1
else:
print("Some Error Occured")
print(a)
# Given two .txt files that have lists of numbers in them, find the numbers that are overlapping. One .txt file has a list of
# all prime numbers under 1000, and the other .txt file has a list of happy numbers up to 1000.
# Given two .txt files that have lists of numbers in them, find the numbers that are overlapping. One .txt file has a list of
# all prime numbers under 1000, and the other .txt file has a list of happy numbers up to 1000.
file_obj_Happy = open("HappyNumber.txt","r")
file_obj_Prime = open("primenumber.txt","r")
# ------------------------- First Method ----------------------------------
Happy_Num_Var = set([int(i.strip("\n")) for i in file_obj_Happy.readlines()])
Prime_Num_Var = set([int(i.strip("\n")) for i in file_obj_Prime.readlines()])
listy = Happy_Num_Var.intersection(Prime_Num_Var)
print(list(listy))
# ------------------------- Second Method ----------------------------------
Happy_Num_Var = [int(i.strip("\n")) for i in file_obj_Happy.readlines()]
Prime_Num_Var = [int(i.strip("\n")) for i in file_obj_Prime.readlines()]
listx=[]
for i in range(0,len(Happy_Num_Var)):
if Happy_Num_Var[i] in Prime_Num_Var:
listx.append(Happy_Num_Var[i])
else:
continue
print(listx)
file_obj_Happy.close()
file_obj_Prime.close()
# Time for some fake graphics! Let’s say we want to draw game boards that look like this:
# --- --- ---
# | | | |
# --- --- ---
# | | | |
# --- --- ---
# | | | |
# --- --- ---
# This one is 3x3 (like in tic tac toe). Obviously, they come in many other sizes (8x8 for chess, 19x19 for Go, and many more).
# Ask the user what size game board they want to draw, and draw it for them to the screen using Python’s print statement.
def draw_box(n):
for f in range(n):
for i in range(n):
print("---",end=" ")
print()
for j in range(n+1):
print("| ",end=" ")
print()
for i in range(n):
print("---",end=" ")
draw_box(int(input("Enter the Number -> ")))
# This time, we’re going to do exactly the opposite. You, the user, will have in your head a number between 0 and 100.
# The program will guess a number, and you, the user, will say whether it is too high, too low, or your number.
# At the end of this exchange, your program should print out how many guesses it took to get your number.
from random import randint
def get_number(start,end):
return randint(start, end)
print("Enter If its \"Correct\" or \"Low\" or \"Big\"")
start = 87
end = 87
while True:
if start > end:
print("you are cheating!!!")
break
guess_Number = get_number(start,end)
print(start,end)
print("My Guess Number is ",guess_Number)
user_input = input("-> ").lower()
if user_input == "correct":
print("Ha I Found It")
break
elif user_input == "low":
start = guess_Number + 1
elif user_input == "high":
end = guess_Number - 1
# As you may have guessed, we are trying to build up to a full tic-tac-toe board. However, this is significantly more than half
# an hour of coding, so we’re doing it in pieces.
# Today, we will simply focus on checking whether someone has WON a game of Tic Tac Toe, not worrying about how the moves were made.
# If a game of Tic Tac Toe is represented as a list of lists, like so:
#where a 0 means an empty square, a 1 means that player 1 put their token in that space, and a 2 means that player 2
# put their token in that space.
# given a 3 by 3 list of lists that represents a Tic Tac Toe game board, tell me whether anyone has won, and tell me
# which player won, if any. A Tic Tac Toe win is 3 in a row - either in a row, a column, or a diagonal. Don’t worry about
# the case where TWO people have won - assume that in every board there will only be one winner.
# ------------- Printing Array ---------------
#for i in game:
# for j in i:
# print(j,end=" ")
# print()
# -------------- Checking The Diagonals-------------
def Diagonals():
diag=[]
for k in range(0,len(game)):
diag.append(game[k][k])
if diag == [1,1,1]:
print("Player 1 Won")
break
elif diag == [2,2,2]:
print("Player 2 Won")
break
else:
continue
# -------------- Checking The Column -------------
def Check_Column():
col1 = []
col2 = []
col3 = []
for j in range(len(game)):
col1.append(game[j][0])
col2.append(game[j][1])
col3.append(game[j][2])
if col1 == [1,1,1]:
print("Player 1 Won")
elif col1 == [2,2,2]:
print("Player 2 Won")
if col2 == [1,1,1]:
print("Player 1 Won")
elif col2 == [2,2,2]:
print("Player 2 Won")
if col3 == [1,1,1]:
print("Player 1 Won")
elif col3 == [2,2,2]:
print("Player 2 Won")
# -------------- Checking The Rows And Main -------------
def Row_Check():
for k in game:
if k == [1,1,1]:
print("Player 1 Won")
break
elif k == [2,2,2]:
print("Player 2 Won")
break
else:
continue
Row_Check()
Check_Column()
Diagonals()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment