ColdMeekly<3 16 Posted May 30, 2016 Welcome to ColdMeekly<3's Weekly Python Challenges 2! Ever had the feeling that you feel that there is nothing else to do with Python*? Or do you just prefer someone setting you work instead? Below you will have a chance to work on code from scratch, and learn Python* that way, or you could have a look at how other people had solved the problem, and improve their code. Below are This Weeks Challenges, please do post your approaches if you had made an attempt, and share your experience with newcomers.Note: For each and every one of these i recommend to use http://trinket.io/ , Unless i specify otherwise. *These do not necessarily have to be done in python. Answers for previous questions: Question 1: Title: Lightning Distance Calculator Answer: #Ligthning Distance Calculator speedOfSound = 340 #m/s time = int(input("Please type the amount of second the sound was delayed for: ")) distance = speedOfSound * time print("The ligthning struck " + str(distance) + " Miles away from you") Question 2: Title: Window Cleaner's Quotes Answer: numberOfWindows = int(input("How many windows need to be cleaned?")) #Asks for the user to input the amount of windows, and attempts to make it an integer cost = 10 #Set the cost to 10 since the initial cost is 10 for i in range(numberOfWindows): #Loop through, numberOfWindows times if i < 5: #If window count below or equal to 5: (Don't forget i starts with 0) cost += 2 #Increment cost by 2 elif i < 10: #Else, if window count below or equal to 10: (Don't forget i starts with 0) cost += 1.50 #Increment cost by 1.50 else: #Else, if none of the above are met: cost += 1 #Increment cost by 1 print("Your quoted cost is $" + str(cost)) #Output the price! Question 3: Title: Sweet Shop Answer: print(" --- Price List --- ") print("") print("A - Marshmallow: $0.20") print("B - Bubble gum: $0.30") print("C - Jelly Bean: $0.15") print("D - Candy Stick: $0.35") print("E - Cola Whips: $0.22") print("") print("X - Exit") print("") #Above, is the menu which we will print to the user. menu = {"A":[0.2,"Marshmallow"],"B":[0.3,"Bubble gum"],"C":[0.15,"Jelly Bean"],"D":[0.35,"Candy Stick"],"E":[0.22,"Cola Whip"],"X":[0]} #A dictionary which contains the selection Letter, price and name. wallet = float(input("How much do you want to spend?")) #Ask user for the amount of money they have. choice = 0 #Initialise the choice variable to 0. while choice != "X": #While loop, which terminates program when user types "X". choice = str(input("Which sweet do you want to buy?")) #Ask the user for their selection. while choice not in menu: choice = str(input("Which sweet do you want to buy?")) #Keep Asking the user until they select an item from the menu. priceOfSweet = float(menu[choice][0]) #Set variable to the price of the chosen sweet. nameOfSweet = str(menu[choice][1]) #Set variable to the name of the chosen sweet. amount = int(input("How many " + nameOfSweet + "s do you want to buy?")) #Ask user for their desired quantity. cost = priceOfSweet * amount #Set variable to cost of the amount of sweets. if wallet > cost: #Check if the user can afford it. wallet -= cost #Take away money print("You had bought {} {}s for ${}.").format(amount,nameOfSweet,round(cost,2)) print("Your wallet has ${} left.").format(wallet) #Print a couple bits of info back to the user else: print ("You do not have enough money for {} {}s.").format(amount,nameOfSweet) #Else, print that they didn't have enough money for it. Question 4: Title: Gradient Animation Info: Since this challenge consisted of many different gradients, i simply created a gradient generator, for 2 different colors. Answer: import turtle g=int(input("How many gradients do you want there to be?")) myPen = turtle.Turtle() myPen.speed(0) # This function draws a box by drawing each side of the square and using the fill function def box(height,size,r,g,b): myPen.color(r,g,b) myPen.begin_fill() # 0 deg. myPen.forward(size) myPen.left(90) # 90 deg. myPen.forward(height) myPen.left(90) # 180 deg. myPen.forward(size) myPen.left(90) # 270 deg. myPen.forward(height) myPen.end_fill() myPen.setheading(0) #Position myPen in top left area of the screen myPen.penup() myPen.goto(-200,-100) myPen.pendown() #colorStartRed = input("RGB Code for color 1: Red (0-255): ") #colorStartGreen = input("RGB Code for color 1: Green (0-255): ") #colorStartBlue = input("RGB Code for color 1: Blue (0-255): ") colourStartArray = [] colourEndArray = [] colourStart = input("Please input Hex code with a #:") colourEnd = input("Please input Hex code with a #:") noHashStart=colourStart[1:] noHashEnd=colourEnd[1:] for i in range(0,(len(noHashStart)),2): hexSplit=(noHashStart[i:i+2]) denaryNumber = int(hexSplit, 16) colourStartArray.append(denaryNumber) for j in range(0,(len(noHashEnd)),2): hexSplit=(noHashEnd[j:j+2]) denaryNumber= int(hexSplit, 16) colourEndArray.append(denaryNumber) #colorEndRed = input("RGB Code for color 2: Red (0-255): ") #colorEndGreen = input("RGB Code for color 2: Green (0-255): ") #colorEndBlue = input("RGB Code for color 2: Blue (0-255): ") colourStartRed = colourStartArray[0] colourStartGreen = colourStartArray[1] colourStartBlue = colourStartArray[2] colourEndRed = colourEndArray[0] colourEndGreen = colourEndArray[1] colourEndBlue = colourEndArray[2] height = 200 box(height, int(450/(g+2)), colourStartRed, colourStartGreen, colourStartBlue) #Replace the code below to draw an extra 6 boxes of different colours to create a gradient effect between colorStart and colorEnd for i in range(1,g+1): myPen.penup() myPen.forward(int(450/(g+2))) myPen.pendown() box(height ,int(450/(g+2)) , int(colourStartRed+(i*((colourEndRed-colourStartRed)/(g+1)))), int(colourStartGreen+(i*((colourEndGreen-colourStartGreen)/(g+1)))), int(colourStartBlue+(i*((colourEndBlue-colourStartBlue)/(g+1))))) box(height ,int(450/(g+2)) , colourEndRed, colourEndGreen, colourEndBlue) Question 5: Title: Molecular Mass Calculator Answer: import os import math import re def mainMenu(): os.system('clear') print("Welcome to [Person]'s Molecular Mass Calculator!\n\n 1 - Single Element --> Molecular Mass\n 2 - Multiple Element --> Molecular Mass\n") menu = raw_input("Please choose an option from the menu") if menu == "1": a = ask() os.system('cls') print("The Molecular Mass of " + a + " is : " + str(mass(a))) input("\nPlease Press ENTER to continue to Main Menu...") mainMenu() elif menu == "2": a = ask() os.system('cls') print("The Molecular Mass of " + a + " is : " + str(converter(a))) input("\nPlease Press ENTER to continue to Main Menu...") mainMenu() else: os.system('cls') mainMenu() def ask(): os.system('clear') ask = raw_input("\nPlease Enter an Element to convert :") return ask def converter(element): total = 0 i = 0 # Tested regexp ([A-Z][a-z]*)(\d*) # Made it simpler by ordering the elements in Atomic number order elements = ['H','He','Li','Be','B','C','N','O','F','Ne','Na','Mg','Al','Si','P','S','Cl','Ar','K','Ca','Sc','Ti','V','Cr','Mn','Fe','Co','Ni','Cu','Zn','Ga','Ge','As','Se','Br','Kr','Rb','Sr','Y','Zr','Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn','Sb','Te','I','Xe','Cs','Ba','La','Ce','Pr','Nd','Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb','Lu','Hf','Ta','W','Re','Os','Ir','Pt','Au','Hg','Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th','Pa','U','Np','Pu','Am','Cm','Bk','Cf','Es','Fm','Md','No','Lr','Rf','Db','Sg','Bh','Hs','Mt','Ds','Rg','Uub','Uut','Uuq','Uup','Uuh','Uus','Uuo'] molecularMass = ['1.0079','4.0026','6.941','9.0122','10.811','12.0107','14.0067','15.9994','18.9984','20.1797','22.9897','24.305','26.9815','28.0855','30.9738','32.065','35.453','39.0983','39.948','40.078','44.9559','47.867','50.9415','51.9961','54.938','55.845','58.6934','58.9332','63.546','65.39','69.723','72.64','74.9216','78.96','79.904','83.8','85.4678','87.62','88.9059','91.224','92.9064','95.94','98','101.07','102.9055','106.42','107.8682','112.411','114.818','118.71','121.76','126.9045','127.6','131.293','132.9055','137.327','138.9055','140.116','140.9077','144.24','145','150.36','151.964','157.25','158.9253','162.5','164.9303','167.259','168.9342','173.04','174.967','178.49','180.9479','183.84','186.207','190.23','192.217','195.078','196.9665','200.59','204.3833','207.2','208.9804','209','210','222','223','226','227','231.0359','232.0381','237','238.0289','243','244','247','247','251','252','257','258','259','261','262','262','264','266','268','272','277','0','0','0','0','0','0','0','0'] a = re.split(r'([A-Z][a-z]*)(\d*)',element) lengthElement = len(element) i=i+1 while '' in a: a.remove('') b = len(a) # This is total amount of Elements. for g in range(0,b): c = a[g] searchObj = re.search( r'([A-Z][a-z]*)(\d*)', a[g]) index = elements.index(searchObj.group(1)) atomic = molecularMass[index] if searchObj.group(2): total += float(atomic)*int(searchObj.group(2)) else: total += float(atomic) return total print(total) def mass(element): elements = ['H','He','Li','Be','B','C','N','O','F','Ne','Na','Mg','Al','Si','P','S','Cl','Ar','K','Ca','Sc','Ti','V','Cr','Mn','Fe','Co','Ni','Cu','Zn','Ga','Ge','As','Se','Br','Kr','Rb','Sr','Y','Zr','Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn','Sb','Te','I','Xe','Cs','Ba','La','Ce','Pr','Nd','Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb','Lu','Hf','Ta','W','Re','Os','Ir','Pt','Au','Hg','Tl','Pb','Bi','Po','At','Rn','Fr','Ra','Ac','Th','Pa','U','Np','Pu','Am','Cm','Bk','Cf','Es','Fm','Md','No','Lr','Rf','Db','Sg','Bh','Hs','Mt','Ds','Rg','Uub','Uut','Uuq','Uup','Uuh','Uus','Uuo'] molecularMass = ['1.0079','4.0026','6.941','9.0122','10.811','12.0107','14.0067','15.9994','18.9984','20.1797','22.9897','24.305','26.9815','28.0855','30.9738','32.065','35.453','39.0983','39.948','40.078','44.9559','47.867','50.9415','51.9961','54.938','55.845','58.6934','58.9332','63.546','65.39','69.723','72.64','74.9216','78.96','79.904','83.8','85.4678','87.62','88.9059','91.224','92.9064','95.94','98','101.07','102.9055','106.42','107.8682','112.411','114.818','118.71','121.76','126.9045','127.6','131.293','132.9055','137.327','138.9055','140.116','140.9077','144.24','145','150.36','151.964','157.25','158.9253','162.5','164.9303','167.259','168.9342','173.04','174.967','178.49','180.9479','183.84','186.207','190.23','192.217','195.078','196.9665','200.59','204.3833','207.2','208.9804','209','210','222','223','226','227','231.0359','232.0381','237','238.0289','243','244','247','247','251','252','257','258','259','261','262','262','264','266','268','272','277','0','0','0','0','0','0','0','0'] index = elements.index(element) mass = molecularMass[index] return mass mainMenu() New Challenges <3: Challenge #1 - Easy Title: How Eco Friendly Are You?Difficulty: BeginnerTime Needed: 3/10Details:It would not be hot news for you to hear that throughout your everyday life, whatever you do, you are having an impact on the environment. Words like pollution, global warming, carbon dioxide, recycling, energy saving, waste reduction are no mystery to you. For this challenge you are going to design a quiz that people can take to find out how green or Eco-friendly they are. The quiz will consist of eight questions and will be used to give the end-user a score. Your Challenge Here are the eight questions for the quiz ------------------------------------------------------------- How do you come to school? By Car (-50pts) By Bus (-10pts) On Foot (+100pts) Cycling (+100pts) Did you travel by plane in the last 12 months? No (+100pts) Yes once (-25pts) Yes twice (-50pts) At least 3 times (-100pts) Do you use your recycling bins at home? Never (-50pts) Rarely (+10pts) Often (+50pts) Yes every day (+100pts) When you go shopping do you? Bring your own reusable carrier bags (+20pts) Ask for plastic bags (-20pts) At home do you use Energy saving bulbs? Yes (+30pts) No (-30pts) When you clean your teeth, do you let the water run? Yes (-30pts) Sometimes (-10pts) No, never (+20pts) Is your house equipped with solar panels? Yes (+100pts) No (0pt) When it’s getting a bit colder at the end of the summer do you? Put an extra layer on (e.g. jumper, extra blanket) (+50pts) Turn the heater on? (-50pts) ------------------------------------------------------------- ╔═════════════════════╦═══════════════╗ ║ Score ║ Category ║ ╠═════════════════════╬═══════════════╣ ║ Negative score (<0) ║ Amber ║ ║ Between 0 and 100 ║ Light Green ║ ║ Between 101 and 200 ║ Emerald Green ║ ║ Above 200 ║ Deep Green ║ ╚═════════════════════╩═══════════════╝ Let’s get coding: We have started the code for you but only completed the first question. Your task consists of: 1.)Completing the code to ask all seven questions, 2.)Giving the user their final score and the category they belong to (Amber, Light Green, Emerald Green or Deep Green) based on their final score. Don't know how to start? Check the code below: print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("~ The eco-friendly quiz ~") print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") print("") print("Instructions: Answer each question of this test accurately. Be honest with your answers.") print("At the end you will be given your eco-score that tells you how eco-friendly you are!") print("You will be able to compare this score with your friends and hopefully be inspired to change your daily routines and become even more eco-friendly!") print("") ecoScore = 0 print("Question 1:") print("How do you come to school every day?") answer = input("1 - By car, 2 - By bus or train, 3 - On foot, 4 - On your bike or scooter?") if answer=="1": ecoScore -= 50 elif answer=="2": ecoScore -= 10 elif answer=="3" or answer=="4": ecoScore += 100 else: print("Not a valid answer.") print("") print("Question 2:") print("How often did you take the plane over the last 12 months?") ###Complete the code from here### Challenge #2 - Easy Title: Quote of the DayDifficulty: BeginnerTime Needed: 3/10Details:By completing this challenge you will learn how data can be stored using lists. You will store a series of quotes in a list and append new quotes to your list. You will also find out how to pick up a random value from a list using the random.choice() function. What is the "list" you're talking about? In Python, a list is used to save a collection of values. For instance, to save all the different days of the week we could declare a variable called “daysOfTheWeek” and assign a list as follows (Notice the use of square brackets): daysOfTheWeek = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] Based on this what do you think len(daysOfTheWeek) would return? What’s about daysOfTheWeek[0]? Or daysOfTheWeek[3]? The Challenge: In this challenge we decided to create list to store a collection of inspirational quotes. We then randomly pick a quote from this list to display it to the end-user. import random #Initialize an empty list that will be stored our bank of quotes quotes = [] #Append a few quotes to our list quotes.append("The harder I work, the luckier I get.") quotes.append("A person who never made a mistake never tried anything new.") quotes.append("Nothing will work unless you do.") quotes.append("The best preparation for good work tomorrow is to do good work today.") quotes.append("Choose a job you love, and you will never have to work a day in your life.") #Randomly pick a quote from our bank of quotes dailyQuote = random.choice(quotes) print("############################") print("# Quote of the Day #") print("############################") print("") print(dailyQuote) Your Task: Look at this page. Update the code above to give more daily items. For instance you could: Store a list of science based facts and display the “fact of the day”, store a list of French words and display the “French word of the day”, store a list of maths equations (e.g. 45 + 52 = ?) and display the “Maths Challenge of the day”, etc. Challenge #3 - Medium Title: Penalty ShootoutDifficulty: BeginnerTime Needed: 3/10Details:For this challenge you are going to write a computer program where the user tries to score a goal against the computer. The user will be asked where do they want to shoot and will have to choose one of the following five options: TL: Top Left, BL: Bottom Left, M: Middle, TR: Top Right, BR: Bottom Right. The computer will act as the goal keeper and randomly choose one of these options too. The program will decide if there is a goal or not by comparing the user’s choice with the computer option. Complete the code I have started the code for you. You need to complete it further import random print(" ________________________________ ") print(" | | ") print(" | | ") print(" | Penalty Shootout | ") print(" | | ") print("_____|______________________________|_____") print("") print("") #Let the computer decides where it wants the goal to dive options=["TL","BL","M","TR","BR"] computerOption = random.choice(options) #Now let's ask the user where they want to shoot #Then we can check if the goal blocked the ball or not Extension Task 1: Create a second level where the computer can block up to two locations which are next to each other such as: Bottom left and right left, Bottom left and middle, Top right and middle, etc. Extension Task 2: Give the end-user a choice: do they want to shoot the penalty or be the goal keeper? Adapt your code to cater for both options. Extension Task 3: Create a program where the computer and the player take it in turn. The program adds up the scores and stops on a best of 5 scores. (e.g. 3-0, 4-1, 4-2, 5-3, 5-4) Challenge #4 - Medium Title: Limit 33Difficulty: IntermediateTime Needed: 4/10Details:By completing this challenge you will learn about loops. Rules of the Game A player starts with a total of zero. On each turn a random number between 1 and 10 is generated and added to the player’s total. If the player’s total exceeds 33, the player has lost and the game ends: Game Over. At the end of each turn the player is asked whether they want to complete another turn or quit. If they quit, the player is given a score as follows: For instance with a total of 29, the player would score 10 x (29-23) = 60 points. The maximum score they can reach is 10 x (33-23) = 100 when they reach a total of 33! Zero point if their total is below 24 or above 33. 10 x (total – 23) points if their total is between 24 to 33. Challenge #5 - Medium Title: HTML Code BuilderDifficulty: IntermediateTime Needed: 4/10Details:By completing this challenge you will learn about loops. Your Challenge Write a python script (or reuse the script above) to prompt the user to enter the number of rows and the number of columns they need for their table. The program should then generate the HTML code for the required table. Challenge #6 - Medium Title: Even Fibonacci numbersDifficulty: IntermediateTime Needed: 4/10Details:By completing this challenge you will about manipulating numbers. Your Challenge Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. Challenge #7 - Insane Title: Double base palindromesDifficulty: InsaneTime Needed: 10/10Details:By completing this challenge you will about manipulating numbers. Your Challenge The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. (Please note that the palindromic number, in either base, may not include leading zeros.) A palindromic number, is a number which would give the same number, no matter if it's read right to left. or left to right. (e.g. 585, 171, 1331, 68786) Have fun guys <3 Hope you like it! P.S - If people want more "Hard" challenges, request it below, i would include them :) Next week's is coming out on: 6/06/2016 Answers will be released at end of week (My personal take on it) Quote Share this post Link to post
Fluxy 1,660 Posted May 31, 2016 10/10 mobile viewing experience 1 Gunstar reacted to this Quote Share this post Link to post