From 12cd6d755c76d635ecc81bfe5fe827e16952f194 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Mon, 6 Jan 2020 09:25:08 +0300 Subject: [PATCH 01/65] Update TensorFlow_python.py game challenge combining both function, for loop and objects and classes --- TensorFlow_python.py | 48 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/TensorFlow_python.py b/TensorFlow_python.py index 7a67766..410fbf2 100644 --- a/TensorFlow_python.py +++ b/TensorFlow_python.py @@ -624,5 +624,53 @@ def translator_lowercase(phrase): print(microprocessor3.company_made) +# UP NEXT IS MULTIPLE CHOICE GAME PLAYER +# Create an array of the questions and answers +# import the questions class + +from Question import Question + +questions_prompt = [ + "What is the Leading baking company? \n (a) Kcb \n (b) Equity \n (c) Transnational ", + "Who owns Google \n (a) Mark Zakurbug \n (b) Sundar Puchai \n (c) james Bond ", + "Which is the fastest hard disk? \n (a) RAM \n (b) HDD \n (c) SSD " +] + +questions = [ + Question(questions_prompt[0], "a"), + Question(questions_prompt[1], "b"), + Question(questions_prompt[2], "c"), +] + + +def run_test_question(questions): + score = 0 + for question in questions: + answer = input(question.prompt_user) + if answer == question.choose_answer: + score += 1 + print("You got " + str(score) + "/" + str(len(questions)) + " Correct") + + +run_test_question(questions) + + + + + + + + + + + + + + + + + + + From 12f4cb5973d3084ae708e699a6195b1e941cd257 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Mon, 6 Jan 2020 09:28:20 +0300 Subject: [PATCH 02/65] Create Question.py updated the Questions class --- Question.py | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Question.py diff --git a/Question.py b/Question.py new file mode 100644 index 0000000..e798016 --- /dev/null +++ b/Question.py @@ -0,0 +1,5 @@ +# create a questions class to keep track of user input and answers +class Question: + def __init__(self, prompt, answers): + self.prompt_user = prompt + self.choose_answer = answers From 58c5493082e30aeebe6ff3e0229d185efd227e04 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年3月23日 01:35:54 +0300 Subject: [PATCH 03/65] Update TensorFlow_python.py level one python coding challenges on functions --- TensorFlow_python.py | 52 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/TensorFlow_python.py b/TensorFlow_python.py index 410fbf2..e47effa 100644 --- a/TensorFlow_python.py +++ b/TensorFlow_python.py @@ -656,7 +656,57 @@ def run_test_question(questions): - +# PYTHON CODING CHALLENGES; +# upnest is python functions challenges +#Level 1 + +# 1.0 +# Write a function named tenth_power() that has one parameter named num. +# The function should return num raised to the 10th power. + +def tenth_power(num): + return num**10 +print(tenth_power(1)) #1 +print(tenth_power(0)) #0 +print(tenth_power(2)) #1024 + +# 2.0 +# Write a function named square_root() that has one parameter named num. +# Use exponents (**) to return the square root of num. +# Write your square_root function here: +def square_root(num): + return num**0.5 +print(square_root(16)) #4 +print(square_root(100)) #10 + +# 3.0 +#Create a function called win_percentage() that takes two parameters named wins and losses. +#This function should return out the total percentage of games won by a team based on these two numbers. +# Write your win_percentage function here: +def win_percentage(wins,losses): + total=((wins/(wins+losses)*100)) + return total +print(win_percentage(5, 5)) #50 +print(win_percentage(10, 0)) #100 + +# 4.0 +# Write a function named average() that has two parameters named num1 and num2. +# The function should return the average of these two numbers. +# Write your average function here: +def average(num1,num2): + return ((num1+num2)/2) +print(average(1, 100)) # 50.5 +print(average(1, -1)) #0 + +# 5.0 +# Write a function named remainder() that has two parameters named num1 and num2. +# The function should return the remainder of twice num1 divided by half of num2. +# Write your remainder function here: +def remainder(num1,num2): + rem = ((num1*2)%(num2/2)) + return rem +print(remainder(15, 14)) #2.0 +print(remainder(9, 6)) # 0.0 From 9a56b336d4987f78016855aa3fa1dcdcfc4df720 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年7月16日 18:15:10 +0300 Subject: [PATCH 04/65] Create systemsAutomation_advanced.py systems automation python --- systemsAutomation_advanced.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 systemsAutomation_advanced.py diff --git a/systemsAutomation_advanced.py b/systemsAutomation_advanced.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/systemsAutomation_advanced.py @@ -0,0 +1 @@ + From 6282dc528b317ce5e4055a0715021cd06cf07ee2 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年7月23日 08:45:33 +0300 Subject: [PATCH 05/65] Create projects_and_quiz.py projects and quizes --- projects_and_quiz.py | 59 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 projects_and_quiz.py diff --git a/projects_and_quiz.py b/projects_and_quiz.py new file mode 100644 index 0000000..0a25ba9 --- /dev/null +++ b/projects_and_quiz.py @@ -0,0 +1,59 @@ +#1.0 +In this scenario, two friends are eating dinner at a restaurant. The bill comes in the + amount of 47.28 dollars. The friends decide to split the bill evenly between them, after + adding 15% tip for the service. Calculate the tip, the total amount to pay, and each + friends share, then output a message saying "Each person needs to pay: " followed by the resulting number. + +bill = 47.28 +tip = (bill * 0.15) +total = bill + tip +share = (total/2) +print("Each person needs to pay: " + str(share)) + + +Each person needs to pay: 27.186 + + +#2.0 +This code is supposed to take two numbers, divide one by another so that the result is equal to 1, +and display the result on the screen. Unfortunately, +there is an error in the code. Find the error and fix it, so that the output is correct. +1234 +numerator = 10 +denominator = 10 +result = int(numerator / denominator) +print(result) + +1 + +# 4.0 +Combine the variables to display the sentence "How do you like Python so far?" + + +123456789 +word1 = "How" +word2 = "do" +word3 = "you" +word4 = "like" +word5 = "Python" +word6 = "so" +word7 = "far?" + +print(word1 + " " + word2 + " " + word3 + " " +word4 + " " +word5 +" " + word6 +" " + word7) + +How do you like Python so far? + + +#5.0 +This code is supposed to display "2 + 2 = 4" on the screen, but there is an error. Find the error in the code and fix it, so that the output is correct. + + +print("2 + 2 = 4" ) +Reset +2 + 2 = 4 + + +# 5.0 +What do you call a combination of numbers, symbols, or other values that produce a result when evaluated? + +ans: an Expression From e0e453fe42c280ecb50b334b44df3848b1222115 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年7月23日 08:59:27 +0300 Subject: [PATCH 06/65] Update projects_and_quiz.py commented quizzes for distinction --- projects_and_quiz.py | 46 ++++++++++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 19 deletions(-) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 0a25ba9..754e1ae 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -1,8 +1,8 @@ #1.0 -In this scenario, two friends are eating dinner at a restaurant. The bill comes in the - amount of 47.28 dollars. The friends decide to split the bill evenly between them, after - adding 15% tip for the service. Calculate the tip, the total amount to pay, and each - friends share, then output a message saying "Each person needs to pay: " followed by the resulting number. + #In this scenario, two friends are eating dinner at a restaurant. The bill comes in the + #amount of 47.28 dollars. The friends decide to split the bill evenly between them, after + #adding 15% tip for the service. Calculate the tip, the total amount to pay, and each + #friends share, then output a message saying "Each person needs to pay: " followed by the resulting number. bill = 47.28 tip = (bill * 0.15) @@ -11,23 +11,22 @@ print("Each person needs to pay: " + str(share)) -Each person needs to pay: 27.186 +# Each person needs to pay: 27.186 -#2.0 -This code is supposed to take two numbers, divide one by another so that the result is equal to 1, -and display the result on the screen. Unfortunately, -there is an error in the code. Find the error and fix it, so that the output is correct. +#2.0 +#This code is supposed to take two numbers, divide one by another so that the result is equal to 1, +#and display the result on the screen. Unfortunately, +#there is an error in the code. Find the error and fix it, so that the output is correct. 1234 numerator = 10 denominator = 10 -result = int(numerator / denominator) +result = int(numerator / denominator) print(result) - 1 # 4.0 -Combine the variables to display the sentence "How do you like Python so far?" +#Combine the variables to display the sentence "How do you like Python so far?" 123456789 @@ -41,19 +40,28 @@ print(word1 + " " + word2 + " " + word3 + " " +word4 + " " +word5 +" " + word6 +" " + word7) -How do you like Python so far? +#How do you like Python so far? #5.0 -This code is supposed to display "2 + 2 = 4" on the screen, but there is an error. Find the error in the code and fix it, so that the output is correct. +#This code is supposed to display "2 + 2 = 4" on the screen, but there is an error. Find the error in the code and fix it, so that the output is correct. print("2 + 2 = 4" ) -Reset -2 + 2 = 4 - # 5.0 -What do you call a combination of numbers, symbols, or other values that produce a result when evaluated? +#What do you call a combination of numbers, symbols, or other values that produce a result when evaluated? + +# ans: an Expression + +# 6.0 +#Flesh out the body of the print_seconds function so that it prints the +#total amount of seconds given the hours, minutes, and seconds function parameters. Remember that there are 3600 seconds in an hour and 60 seconds in a minute. + +1234 +def print_seconds(hours, minutes, seconds): + print((hours*3600) + (minutes*60) + seconds) + +print_seconds(1,2,3) -ans: an Expression +3723 From f943a68c61c2aef640f28176c733b99b99d713ef Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年7月23日 23:01:03 +0300 Subject: [PATCH 07/65] Update projects_and_quiz.py more quizes --- projects_and_quiz.py | 340 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 340 insertions(+) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 754e1ae..34b1f0f 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -65,3 +65,343 @@ def print_seconds(hours, minutes, seconds): print_seconds(1,2,3) 3723 + +#7.0 +# #Use the get_seconds function to work out the amount of seconds in 2 hours and 30 minutes, +# then add this number to the amount of seconds in 45 minutes and 15 seconds. Then print the result. + +1234567 +def get_seconds(hours, minutes, seconds): + return 3600*hours + 60*minutes + seconds + +amount_a = get_seconds(2,30,0) +amount_b = get_seconds(0,45,15) +result = amount_a + amount_b +print(result) + +11715 + +#8.0 +#Return the time in seconds after finding the sum: +def returningSeconds(hours, miutes, seconds): + return (hours*3600 + miutes*60 + seconds) +partA = returningSeconds(1,30,0) +partB = returningSeconds(2,60,5) +total = partA + partB +print(total) + +# 9.0 +# use Floor Division to calculate the seconds and hours +def calculateusingFloor(seconds): + hours = seconds//3600 + minutes = ((seconds - (hours*3600))//60) + seconds = (seconds - (hours*3600)-(minutes*60)) + return hours, minutes, seconds +hours, miutes,seconds = calculateusingFloor(4999) +print(hours, seconds,miutes) + +# 10 +#Code Reuse +# Minize the code below to make it reusable using a funcation +name = "Owen" +luckNumber=len(name) * 8 +print("Hello " + name + " Your luck number is " + str(luckNumber)) + +name2 = "Timothy" +luckyNumber2 = len(name2) * 4 +print("Hey " + name + " Your lucky number is " + str(luckyNumber2)) + +#minized using function: +def luckNumberMinimized(name): + luckNo = len(name) * 8 + print("Hello " + name + " Your Lucky number today is : " + str(luckNo)) + return name +print(luckNumberMinimized("Timz")) +print(luckNumberMinimized("Timothy")) + +# 10.1 +# REPLACE THIS STARTER CODE WITH YOUR FUNCTION +june_days = 30 +print("June has " + str(june_days) + " days.") +july_days = 31 +print("July has " + str(july_days) + " days.") + +#expected +def month_days(month, days): + result = f"{month} has {days} days." + return (result) +print (month_days("June", 30)) +print (month_days("July", 31)) + +# 10.2 +#additional +def price_check(type, price): + oder = f"{type} costs ksh. {price} only" + return oder +print(price_check("Toshiba", 50000)) +print(price_check("Apple", 120000)) + +# 11. Refactor the code to make it human friendly +def calculate(d): + q = 3.142 + z = q * (d ** 2) + print(z) +calculate(5) +# refactored: +def areas_circle(radius): + pi = 3.142 + area = pi * (radius ** 2) + print(area) +areas_circle(14) + +615.832 + +#Refactor 2 +def f1(x, y): + z = x*y # the area is base*height + print("The area is " + str(z)) +f1(2,5) + +10 + +#refactored: +def rectangle_are(base, height): + #areas is calculated by + area = base * height + print("The areas is " + str(area)) +rectangle_are(10, 50) + +500 + +#12 + #Let's revisit our lucky_number function. We want to change it, so that instead of printing + #the message, it returns the message. This way, the calling line can print the message, or + #do something else with it if needed. Fill in the blanks to complete the code to make it work. + + +def lucky_number(name): + number = len(name) * 9 + message = "Hello " + name + ". Your lucky number is " + str(number) + return message +print(lucky_number("Kay")) +print(lucky_number("Cameron")) + +#Hello Kay. Your lucky number is 27 +#Hello Cameron. Your lucky number is 63 + + +#13: +#This function compares two numbers and returns them in increasing order. +#Fill in the blanks, so the print statement displays the result of the function call in order. +#Hint: if a function returns multiple values, don't forget to store these values in multiple variables +def order_numbers(number1, number2): + if number2> number1: + return number1, number2 + else: + return number2, number1 + +smaller, bigger= order_numbers(100, 99) +print(smaller, bigger) + +# 14. Write a program function to tell new employees that their user name must a +# at least be 3 charater for signing up. +def user_name_hint(username): + if(len(username)<3): + print("User name cannot be less than 3 characters") + else: + print("Valid User name, Welcome") +user_name_hint("Timz") + +#15 check if a number id odd or positive with if; +def is_even(number): + if(number %2 == 0): + print("Even number") + else: + print("Odd number") +print(is_even(5)) + +#15.1 +#Use True or False boolean to check and return if a number divided by 2 has no remainder +def is_even2(number2): + if(number2 %2 != 0): + return True + return False +print(is_even2(2)) + +False + +#16.0 +# The number_group function should return "Positive" if the number received is positive, +# #"Negative" if it's negative, and "Zero" +# #if it's 0. Can you fill in the gaps to make that happen? + +def group_function(number): + if(number> 0): + print(Positive) + elif(number<0): + print("Negaitve") + else: + return 0 +print(group_function(6)) + +# 17: What's the value of this Python expression: (2**2) == 4? +False + +#18: +#Complete the script by filling in the missing parts. The function receives a name, +#then returns a greeting based on whether or not that name is "Taylor". + +def greeting(name): + if name == "Taylor": + return "Welcome back Taylor!" + else: + return "Hello there, " + name + +print(greeting("Taylor")) +print(greeting("John")) + + +# 19 +#If a filesystem has a block size of 4096 bytes, this means that a file +# #comprised of only one byte will still use 4096 bytes of storage. A file made +# #up of 4097 bytes will use 4096*2=8192 bytes of storage. Knowing this, can you fill +# #in the gaps in the calculate_storage function below, which calculates the total number +# #of bytes needed to store a file of a given size? + +def calculate_storage(filesize): + block_size = 4096 + # Use floor division to calculate how many blocks are fully occupied + full_blocks = filesize//block_size + # Use the modulo operator to check whether there's any remainder + partial_block_remainder = filesize%block_size + # Depending on whether there's a remainder or not, return + # the total number of bytes required to allocate enough blocks + # to store your data. + if partial_block_remainder> 0: + return (full_blocks*4096)+4096 + return (full_blocks*4096) + +print(calculate_storage(1)) # Should be 4096 +print(calculate_storage(4096)) # Should be 4096 +print(calculate_storage(4097)) # Should be 8192 +print(calculate_storage(6000)) # Should be 8192 + +#20 +#Complete the function by filling in the missing parts. The color_translator function +#receives the name of a color, then prints its hexadecimal value. Currently, it only supports the three additive +#primary colors (red, green, blue), so it returns "unknown" for all other colors +def color_translator(color): + if color == "red": + hex_color = "#ff0000" + elif color == "green": + hex_color = "#00ff00" + elif color == "blue": + hex_color = "#0000ff" + else: + hex_color = "unknown" + return hex_color + +print(color_translator("blue")) # Should be #0000ff +print(color_translator("yellow")) # Should be unknown +print(color_translator("red")) # Should be #ff0000 +print(color_translator("black")) # Should be unknown +print(color_translator("green")) # Should be #00ff00 +print(color_translator("")) # Should be unknown + +# 21 +# What's the value of this Python expression: "big"> "small" +True + +# 22 +#Students in a class receive their grades as Pass/Fail. Scores of 60 or +#more (out of 100) mean that the grade is "Pass". For lower scores, the grade +#is "Fail". In addition, scores above 95 (not included) are graded as "Top Score". +#Fill in this function so that it returns the proper grade. +def exam_grade(score): + if ((score>95)and (score<=100)): + grade = "Top Score" + elif ((score>=60)and (score<=95)): + grade = "Pass" + else: + grade = "Fail" + return grade + +print(exam_grade(65)) # Should be Pass +print(exam_grade(55)) # Should be Fail +print(exam_grade(60)) # Should be Pass +print(exam_grade(95)) # Should be Pass +print(exam_grade(100)) # Should be Top Score +print(exam_grade(0)) # Should be Fail + +# 23 +#Complete the body of the format_name function. This function receives the +#first_name and last_name parameters and then returns a properly formatted string. +def format_name(first_name, last_name): + # code goes here + if first_name!='' and last_name!='': + return ("Name: " + last_name+", "+ first_name) + elif first_name!='' or last_name!='': + return ("Name: " +last_name+first_name) + else: + return '' + return string + +print(format_name("Ernest", "Hemingway")) +# Should return the string "Name: Hemingway, Ernest" + +print(format_name("", "Madonna")) +# Should return the string "Name: Madonna" + +print(format_name("Voltaire", "")) +# Should return the string "Name: Voltaire" + +print(format_name("", "")) +# Should return an empty string + +#25 +#The longest_word function is used to compare 3 words. It should return the word with +# the most number of characters (and the first in the list when they have the same length). +# Fill in the blank to make this happen. +def longest_word(word1, word2, word3): + if len(word1)>= len(word2) and len(word1)>= len(word3): + word = word1 + elif len(word2)>= len(word1) and len(word2)>=(len(word3)): + word = word2 + else: + word = word3 + return(word) + +print(longest_word("chair", "couch", "table")) +print(longest_word("bed", "bath", "beyond")) +print(longest_word("laptop", "notebook", "desktop")) + +# 26 +#What is the output of this code? +def sum(x, y): + return(x+y) +print(sum(sum(1,2), sum(3,4))) #ans 10 + +# 27 +#What's the value of this Python expression? + +((10>= 5*2) and (10 <= 5*2) #ans True + +# 28 +#The fractional_part function divides the numerator by the denominator, and returns just the fractional +# part (a number between 0 and 1). Complete the body of the function so that it returns the right number. +# Note: Since division by 0 produces an error, if the denominator is 0, the function should return 0 +# instead of attempting the division. +def fractional_part(numerator, denominator): + # Operate with numerator and denominator to +# keep just the fractional part of the quotien + if denominator ==0: + return 0 + return numerator/denominator - (numerator//denominator) + + +print(fractional_part(5, 5)) # Should be 0 +print(fractional_part(5, 4)) # Should be 0.25 +print(fractional_part(5, 3)) # Should be 0.66... +print(fractional_part(5, 2)) # Should be 0.5 +print(fractional_part(5, 0)) # Should be 0 +print(fractional_part(0, 5)) # Should be 0 From acfc6feb6ca1d0bbe527831ee2ace9fd2074ddca Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年7月24日 23:58:15 +0300 Subject: [PATCH 08/65] Update projects_and_quiz.py while loops quizes --- projects_and_quiz.py | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 34b1f0f..77c6def 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -405,3 +405,42 @@ def fractional_part(numerator, denominator): print(fractional_part(5, 2)) # Should be 0.5 print(fractional_part(5, 0)) # Should be 0 print(fractional_part(0, 5)) # Should be 0 + + + +# 29: +#write a loop that will execute x 10 times and print the 11th result at the end +x=0 +while(x<10): + print("Still way to go x: =" + str(x)) + x=x+1 +print("finally x: = " + str(x)) + +# 30: +# write a code using any variable to check the number of attempt a person inputs in [password] attempts +# rem to use function and good varible names +def password(attempts): + x = 1 + while(x 0): + print(current) + current -= 1 + print("Zero!") +count_down(3) + From 6080654192016bfbcb757da9ffb09c934c3243fb Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年7月25日 19:24:34 +0300 Subject: [PATCH 09/65] Update projects_and_quiz.py while loops --- projects_and_quiz.py | 72 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 77c6def..aea1afe 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -435,6 +435,7 @@ def password(attempts): x+=1 print(sum) + # 31 #Fix the problrm caused by invalid answers below def count_down(start_number): @@ -444,3 +445,74 @@ def count_down(start_number): print("Zero!") count_down(3) + +# 32 +#figure out the problem in the infinite loop and correct +def print_range(start, end): + # Loop through the numbers from start to end + n = start + while n <= end: + print(n) +print_range(1, 5) # Should print 1 2 3 4 5 (each number on its own line) + +#Anws +def print_range(start, end): + # Loop through the numbers from start to end + n = start + while n <= end: + print(n) + n+=1 +print_range(1, 5) # Should print 1 2 3 4 5 (each number on its own line) + +#33 +#write code to print_prime_factors function print all +#the prime factors of a number. A prime factor is +#a number that is prime and divides another without a remainder. +def print_prime_factors(number): + # Start with two, which is the first prime + factor = 2 + # Keep going until the factor is larger than the number + while factor <= number: + # Check if factor is a divisor of number + if number % factor == 0: + # If it is, print it and divide the original number + print(factor) + number = number / factor + else: + # If it's not, increment the factor by one + factor += 1 + return "Done" + +print_prime_factors(100) +# Should print 2,2,5,5 + +# 34: +#The following code can lead to an infinite loop. +# Fix the code so that it can finish successfully for all numbers. +def is_power_of_two(n): + # Check if the number can be divided by two without a remainder + while n % 2 == 0: + n = n / 2 + # If after dividing by two the number is 1, it's a power of two + if n/2 == 1: + return True + return False +print(is_power_of_two(0)) # Should be False +print(is_power_of_two(1)) # Should be True +print(is_power_of_two(8)) # Should be True +print(is_power_of_two(9)) # Should be False + +#Ans +def is_power_of_two(n): + # Check if the number can be divided by two without a remainder + while n % 2 == 0 and n!= 0: + n = n / 2 + # If after dividing by two the number is 1, it's a power of two + if n/2 == 1: + return True + return False +print(is_power_of_two(0)) # Should be False +print(is_power_of_two(1)) # Should be True +print(is_power_of_two(8)) # Should be True +print(is_power_of_two(9)) # Should be False + From c8ce64a3bba42e3c6f6c43de1b41ff4aaf17f268 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年7月26日 23:54:40 +0300 Subject: [PATCH 10/65] Update systemsAutomation_advanced.py reverse --- systemsAutomation_advanced.py | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/systemsAutomation_advanced.py b/systemsAutomation_advanced.py index 8b13789..92ed821 100644 --- a/systemsAutomation_advanced.py +++ b/systemsAutomation_advanced.py @@ -1 +1,25 @@ - +# reverse algoritm +def rverseArray(arr, start, end): + while (start < end): + temp = arr[start] + arr[start] = arr[end] + arr[end] = temp + start += 1 + end = end-1 + +# Function to left rotate arr[] of size n by d +def leftRotate(arr, d): + n = len(arr) + rverseArray(arr, 0, d-1) + rverseArray(arr, d, n-1) + rverseArray(arr, 0, n-1) + +# Function to print an array +def printArray(arr): + for i in range(0, len(arr)): + print (arr[i]) + +# Driver function to test above functions +arr = [1, 2, 3, 4, 5, 6, 7] +leftRotate(arr, 2) # Rotate array by 2 +printArray(arr) From f9de1bd13fd3c8cc76148d0fad7e5e67d0ccfa9b Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年7月30日 07:32:40 +0300 Subject: [PATCH 11/65] Update projects_and_quiz.py functions quizes --- projects_and_quiz.py | 167 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 167 insertions(+) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index aea1afe..7117397 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -516,3 +516,170 @@ def is_power_of_two(n): print(is_power_of_two(8)) # Should be True print(is_power_of_two(9)) # Should be False + + +#37; +#Fcomplete the empty function so that it returns the sum of all the divisors of a number, without including it. +# A divisor is a number that divides into another without a remainder +def sum_divisors(n): + sum = 0 + # Return the sum of all divisors of n, not including n + return sum + +print(sum_divisors(0)) +# 0 +print(sum_divisors(3)) # Should sum of 1 +# 1 +print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18 +# 55 +print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51 +# 114 + + +#Answer +def sum_divisors(n): + x=1 + sum = 0 + if n==0: + sum +=n + else: + while n> x: + while n%x==0 and n!=x: + sum +=x + x+=1 + x+=1 + # Return the sum of all divisors of n, not including n + return sum + +print(sum_divisors(0)) +# 0 +print(sum_divisors(3)) # Should sum of 1 +# 1 +print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18 +# 55 +print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51 +# 114 + + +#38 +#he multiplication_table function prints the results of a number passed to +# it multiplied by 1 through 5. An additional requirement +# is that the result is not to exceed 25, which is done with the break +# statement. Fill in the blanks to complete the function to satisfy these conditions. + +def multiplication_table(number): + # Initialize the starting point of the multiplication table + multiplier = 1 + # Only want to loop through 5 + while multiplier <= 5: + result = ___ + # What is the additional condition to exit out of the loop? + if ___ : + break + print(str(number) + "x" + str(multiplier) + "=" + str(result)) + # Increment the variable for the loop + ___ += 1 + +multiplication_table(3) +# Should print: 3x1=3 3x2=6 3x3=9 3x4=12 3x5=15 + +multiplication_table(5) +# Should print: 5x1=5 5x2=10 5x3=15 5x4=20 5x5=25 + +multiplication_table(8) +# Should print: 8x1=8 8x2=16 8x3=24 + +#Answer +def multiplication_table(number): + # Initialize the starting point of the multiplication table + multiplier = 1 + # Only want to loop through 5 + while multiplier <= 5: + result = multiplier * number + # What is the additional condition to exit out of the loop? + if result>25 : + break + print(str(number) + "x" + str(multiplier) + "=" + str(result)) + # Increment the variable for the loop + multiplier += 1 + +multiplication_table(3) +# Should print: 3x1=3 3x2=6 3x3=9 3x4=12 3x5=15 + +multiplication_table(5) +# Should print: 5x1=5 5x2=10 5x3=15 5x4=20 5x5=25 + +multiplication_table(8) +# Should print: 8x1=8 8x2=16 8x3=24 + + + +# 39 complete the code to find sum_squares +# function, so that it returns the sum of all the squares of +# numbers between 0 and x (not included). Remember that you can +# use the range(x) function to generate a sequence of numbers from 0 to x (not included). +def square(n): + return n*n + +def sum_squares(x): + sum = 0 + for n in ___: + sum += __ + return __ + +print(sum_squares(10)) # Should be 285 + +#anws: +def square(n): + return n*n +def sum_squares(x): + sum = 0 + for n in range(x): + sum += square(n) + return sum +print(sum_squares(10)) + +#40 +#Iterate through a for loop in a list and print all your friends not less than 10 of them +friends = ['Timz', 'Owen','Chelsea','Cherono','Shem','Kiptoo','Linda','Daktari','Sean','Joy'] +for team in friends: + print("Hello Awesome :" + team) + + +# 41: +#calculate sum of values and their length using for loop and calculate the sum and avarage: +values = [0,10,20,30,40,50,60,70,80,90,100] +sum = 0 +length = 0 +for value in values: + sum += value + length += 1 +print("The sum is: " + str(sum) + " Avareg: " + (sum/length)) + +# 42 +#calculate the factorial of a number using function: +def factorial(n): + result = 1 + for i in range(1,(n+1)): + result = i * result + return result +print(factorial(4)) # should return 24 +print(factorial(5)) # should return 120 + +#or +def factorial(n): + result = 1 + for x in range(result,(n+1)): + result *= x + return result +print(factorial(4)) #34 + +#43 +# Using function and for loop ,create a temperature to celcius converstion that will +# convert starting at 0, end at 100 and interval of 10: +def to_celsius(x): + return (x-32)*5/9 +for x in range(0,101,10): + print("Temp at :" + str(x) + " is: " + str(to_celsius(x))) + + From 7a0166cc038ea42822d3a43b6c84411c66650b9d Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年7月30日 09:55:16 +0300 Subject: [PATCH 12/65] Update projects_and_quiz.py nested for loops --- projects_and_quiz.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 7117397..4c95c86 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -683,3 +683,26 @@ def to_celsius(x): print("Temp at :" + str(x) + " is: " + str(to_celsius(x))) +#44 +#create a team match for football using nested for loop.make sure there is no team that is playing +#againest itself and print the score board for the Coach; +teams = ['Chelsea', 'Arsenal','Man city', 'Man U','AFC Leopard', 'Barcelona','Liverpool'] + +for home_team in teams: + for away_team in teams: + if(home_team!=away_team): + print("[ " + home_team + " VS " + away_team +" ]") + +# 45 +# using the block 7 spinner game,use for loop to interate each block and make sure no repetition +for left in range(7): + for right in range(left,7): + print("[" + str(left) + "|" + str(right) + "]",end="") + print() +[0|0][0|1][0|2][0|3][0|4][0|5][0|6] +[1|1][1|2][1|3][1|4][1|5][1|6] +[2|2][2|3][2|4][2|5][2|6] +[3|3][3|4][3|5][3|6] +[4|4][4|5][4|6] +[5|5][5|6] +[6|6] From 4bffc9d0f12bfc3fb75bb34be24a96e01d72e22c Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年7月31日 23:53:51 +0300 Subject: [PATCH 13/65] Update projects_and_quiz.py quiz restructure --- projects_and_quiz.py | 23 ----------------------- 1 file changed, 23 deletions(-) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 4c95c86..7117397 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -683,26 +683,3 @@ def to_celsius(x): print("Temp at :" + str(x) + " is: " + str(to_celsius(x))) -#44 -#create a team match for football using nested for loop.make sure there is no team that is playing -#againest itself and print the score board for the Coach; -teams = ['Chelsea', 'Arsenal','Man city', 'Man U','AFC Leopard', 'Barcelona','Liverpool'] - -for home_team in teams: - for away_team in teams: - if(home_team!=away_team): - print("[ " + home_team + " VS " + away_team +" ]") - -# 45 -# using the block 7 spinner game,use for loop to interate each block and make sure no repetition -for left in range(7): - for right in range(left,7): - print("[" + str(left) + "|" + str(right) + "]",end="") - print() -[0|0][0|1][0|2][0|3][0|4][0|5][0|6] -[1|1][1|2][1|3][1|4][1|5][1|6] -[2|2][2|3][2|4][2|5][2|6] -[3|3][3|4][3|5][3|6] -[4|4][4|5][4|6] -[5|5][5|6] -[6|6] From 957750ae9178d7d066fae5bf462218ff735d10ae Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Sat, 1 Aug 2020 09:45:47 +0300 Subject: [PATCH 14/65] Update projects_and_quiz.py recursion and for loop --- projects_and_quiz.py | 85 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 7117397..6f02411 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -683,3 +683,88 @@ def to_celsius(x): print("Temp at :" + str(x) + " is: " + str(to_celsius(x))) +#44 +#create a team match for football using nested for loop.make sure there is no team that is playing +#againest itself and print the score board for the Coach; +teams = ['Chelsea', 'Arsenal','Man city', 'Man U','AFC Leopard', 'Barcelona','Liverpool'] + +for home_team in teams: + for away_team in teams: + if(home_team!=away_team): + print("[ " + home_team + " VS " + away_team +" ]") + +# 45 +# using the block 7 spinner game,use for loop to interate each block and make sure no repetition +for left in range(7): + for right in range(left,7): + print("[" + str(left) + "|" + str(right) + "]",end="") + print() +[0|0][0|1][0|2][0|3][0|4][0|5][0|6] +[1|1][1|2][1|3][1|4][1|5][1|6] +[2|2][2|3][2|4][2|5][2|6] +[3|3][3|4][3|5][3|6] +[4|4][4|5][4|6] +[5|5][5|6] +[6|6] + +# 46 +#Debug and Fix the code to iterate for only one worddef validate_users(users): +for user in users: + if is_valid(user): + print(user + " is valid") + else: + print(user + " is invalid") +validate_users("purplecat") + +#solved +def validate_users(users): + for user in users: + if len(user)>3: + print(user + " is valid") + else: + print(user + " is invalid") +validate_users(["purplecat"]) + + +# 47 +#create a factorial function that returns the factorial of n. +# Then, print the first 10 factorials (from 0 to 9) with the corresponding number. +# Remember that the factorial of a number is defined as the product of an integer +# and all integers before it. For example, the factorial +# of five (5!) is equal to 1*2*3*4*5=120. Also recall that the factorial of zero (0!) is equal to 1. +def factorial(n): + result = 1 + for x in range(1,n+1): + result *= x + return result +for n in range(0,10): + print(n, factorial(n)) + +# 48 +# Write a script that prints the first 10 cube numbers (x**3), starting with x=1 and ending with x=10. +for square in range(1,11): + squared = square **3 + print(squared) + +# 49 +# Write a script that prints the multiples of 7 between 0 and 100. Print one multiple per line and avoid printing any +# numbers that aren't multiples of 7. Remember that 0 is also a multiple of 7. +for multiple in range(0,100,7): + print(multiple, end = " \n") + +# 50 +# The retry function tries to execute an operation that might fail, it retries the operation for a number of attempts. Currently +# the code will keep executing the function even if it succeeds. Fill in the blank so the code stops trying after the operation succeeded. +def retry(operation, attempts): + for n in range(attempts): + if operation(): + print("Attempt " + str(n) + " succeeded") + break + else: + print("Attempt " + str(n) + " failed") +retry(create_user, 3) +retry(stop_service, 5) + +# 51 +# Using recursion create a function that calls itself using a factorial sample + From 768d36c75d0e863ad2e1727b449a9e2b5d71351e Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Sat, 1 Aug 2020 10:43:32 +0300 Subject: [PATCH 15/65] Update projects_and_quiz.py recursion more quizes and solutions --- projects_and_quiz.py | 108 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 6f02411..dc246b7 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -768,3 +768,111 @@ def retry(operation, attempts): # 51 # Using recursion create a function that calls itself using a factorial sample +# Using recursion create a function that calls itself using a factorial sample +def factorial(n): + print("Factorial called with: " + str(n)) + if n < 2: + return 1 + result = n * factorial(n-1) + print("Returning: " + str(result) + " For factorial " + str(n)) + return result +factorial(5) + +# 52 +# write a function sum_positive_numbers should return the sum of all positive numbers +# between the number n received and 1. +# For example, when n is 3 it should return 1+2+3=6, and when n is 5 it should +# return 1+2+3+4+5=15. Fill in the gaps to make this work: +def sum_positive_numbers(n): + # The base case is n being smaller than 1 + print("The positive sum is for number : " + str(n)) + if n < 1: + return 0 + total = n + sum_positive_numbers(n-1) + return total +print(sum_positive_numbers(3)) # Should be 6 +print(sum_positive_numbers(5)) # Should be + +# 53 +# Fill in the blanks to make the is_power_of function return whether the number is a power of the given base. +# Note: base is assumed to be a positive number. Tip: for functions that return a boolean value, you can return the result of a comparison. +def is_power_of(number, base): + # Base case: when number is smaller than base. + if number < base: + # If number is equal to 1, it's a power (base**0). + return __ + + # Recursive case: keep dividing number by base. + return is_power_of(__, ___) + +print(is_power_of(8,2)) # Should be True +print(is_power_of(64,4)) # Should be True +print(is_power_of(70,10)) # Should be False + +#ans +def is_power_of(number, base): + # Base case: when number is smaller than base. + if number < base: + # If number is equal to 1, it's a power (base**0). + return number == 1 + result = number//base + # Recursive case: keep dividing number by base. + return is_power_of(result, base) + +print(is_power_of(8,2)) # Should be True +print(is_power_of(64,4)) # Should be True +print(is_power_of(70,10)) # Should be False + +# 54 +# The count_users function recursively counts the amount of users that belong to a group +# in the company system, by going through each of the members of a group +# and if one of them is a group, recursively calling the function and counting the members. +# But it has a bug! Can you spot the problem and fix it? + +def count_users(group): + count = 0 + for member in get_members(group): + count += 1 + if is_group(member): + count += count_users(member) + return count + +print(count_users("sales")) # Should be 3 +print(count_users("engineering")) # Should be 8 +print(count_users("everyone")) # Should be 18 + +#ans +def count_users(group): + count = 0 + for member in get_members(group): + #count += 1 + if is_group(member): + count += count_users(member) + else: + count += 1 + return count + +print(count_users("sales")) # Should be 3 +print(count_users("engineering")) # Should be 8 +print(count_users("everyone")) # Should be 18 + +# 55 +#Implement the sum_positive_numbers function, +# as a recursive function that returns the sum of all positive numbers +# between the number n received and 1. For +# example, when n is 3 it should return 1+2+3=6, and when n is 5 it should return 1+2+3+4+5=15. + +def sum_positive_numbers(n): + return 0 +print(sum_positive_numbers(3)) # Should be 6 +print(sum_positive_numbers(5)) # Should be 15 + +#ans +def sum_positive_numbers(n): + if n < 1: + return 0 + total_sum = n + sum_positive_numbers(n-1) + return total_sum + +print(sum_positive_numbers(3)) # Should be 6 +print(sum_positive_numbers(5)) # Should be 15 From ca4f45d358ead7883ab7ef40490e870782a57942 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Sun, 2 Aug 2020 22:23:14 +0300 Subject: [PATCH 16/65] Update README.md --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index 9d660d8..5f8ef5b 100644 --- a/README.md +++ b/README.md @@ -1,2 +1 @@ -# python4TensorFlow and Machine Learning -Python from zero to Hero to get you started with machine Learning and Data science +# python for all tech py related From bb250037b62983843b071bfe17983007fd799983 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Mon, 3 Aug 2020 23:32:32 +0300 Subject: [PATCH 17/65] Update projects_and_quiz.py Code review and correction --- projects_and_quiz.py | 52 -------------------------------------------- 1 file changed, 52 deletions(-) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index dc246b7..6afcb0a 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -823,56 +823,4 @@ def is_power_of(number, base): print(is_power_of(64,4)) # Should be True print(is_power_of(70,10)) # Should be False -# 54 -# The count_users function recursively counts the amount of users that belong to a group -# in the company system, by going through each of the members of a group -# and if one of them is a group, recursively calling the function and counting the members. -# But it has a bug! Can you spot the problem and fix it? - -def count_users(group): - count = 0 - for member in get_members(group): - count += 1 - if is_group(member): - count += count_users(member) - return count - -print(count_users("sales")) # Should be 3 -print(count_users("engineering")) # Should be 8 -print(count_users("everyone")) # Should be 18 -#ans -def count_users(group): - count = 0 - for member in get_members(group): - #count += 1 - if is_group(member): - count += count_users(member) - else: - count += 1 - return count - -print(count_users("sales")) # Should be 3 -print(count_users("engineering")) # Should be 8 -print(count_users("everyone")) # Should be 18 - -# 55 -#Implement the sum_positive_numbers function, -# as a recursive function that returns the sum of all positive numbers -# between the number n received and 1. For -# example, when n is 3 it should return 1+2+3=6, and when n is 5 it should return 1+2+3+4+5=15. - -def sum_positive_numbers(n): - return 0 -print(sum_positive_numbers(3)) # Should be 6 -print(sum_positive_numbers(5)) # Should be 15 - -#ans -def sum_positive_numbers(n): - if n < 1: - return 0 - total_sum = n + sum_positive_numbers(n-1) - return total_sum - -print(sum_positive_numbers(3)) # Should be 6 -print(sum_positive_numbers(5)) # Should be 15 From ba97cff160d2bffaa4e3e9f4679bcaee7a26f3db Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Tue, 4 Aug 2020 22:42:20 +0300 Subject: [PATCH 18/65] Update projects_and_quiz.py restructured answers --- projects_and_quiz.py | 29 ----------------------------- 1 file changed, 29 deletions(-) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 6afcb0a..6c63fa1 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -793,34 +793,5 @@ def sum_positive_numbers(n): print(sum_positive_numbers(3)) # Should be 6 print(sum_positive_numbers(5)) # Should be -# 53 -# Fill in the blanks to make the is_power_of function return whether the number is a power of the given base. -# Note: base is assumed to be a positive number. Tip: for functions that return a boolean value, you can return the result of a comparison. -def is_power_of(number, base): - # Base case: when number is smaller than base. - if number < base: - # If number is equal to 1, it's a power (base**0). - return __ - - # Recursive case: keep dividing number by base. - return is_power_of(__, ___) - -print(is_power_of(8,2)) # Should be True -print(is_power_of(64,4)) # Should be True -print(is_power_of(70,10)) # Should be False - -#ans -def is_power_of(number, base): - # Base case: when number is smaller than base. - if number < base: - # If number is equal to 1, it's a power (base**0). - return number == 1 - result = number//base - # Recursive case: keep dividing number by base. - return is_power_of(result, base) - -print(is_power_of(8,2)) # Should be True -print(is_power_of(64,4)) # Should be True -print(is_power_of(70,10)) # Should be False From 380b86a86f78148eb582696f6508e44b8382d0f5 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Wed, 5 Aug 2020 23:01:18 +0300 Subject: [PATCH 19/65] Update projects_and_quiz.py nested --- projects_and_quiz.py | 229 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 229 insertions(+) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 6c63fa1..535972f 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -794,4 +794,233 @@ def sum_positive_numbers(n): print(sum_positive_numbers(5)) # Should be +#ans +def is_power_of(number, base): + # Base case: when number is smaller than base. + if number < base: + # If number is equal to 1, it's a power (base**0). + return number == 1 + result = number//base + # Recursive case: keep dividing number by base. + return is_power_of(result, base) + +print(is_power_of(8,2)) # Should be True +print(is_power_of(64,4)) # Should be True +print(is_power_of(70,10)) # Should be False + +# 54 +# The count_users function recursively counts the amount of users that belong to a group +# in the company system, by going through each of the members of a group +# and if one of them is a group, recursively calling the function and counting the members. +# But it has a bug! Can you spot the problem and fix it? + +def count_users(group): + count = 0 + for member in get_members(group): + count += 1 + if is_group(member): + count += count_users(member) + return count + +print(count_users("sales")) # Should be 3 +print(count_users("engineering")) # Should be 8 +print(count_users("everyone")) # Should be 18 + +#ans +def count_users(group): + count = 0 + for member in get_members(group): + #count += 1 + if is_group(member): + count += count_users(member) + else: + count += 1 + return count + +print(count_users("sales")) # Should be 3 +print(count_users("engineering")) # Should be 8 +print(count_users("everyone")) # Should be 18 + +# 55 +#Implement the sum_positive_numbers function, +# as a recursive function that returns the sum of all positive numbers +# between the number n received and 1. For +# example, when n is 3 it should return 1+2+3=6, and when n is 5 it should return 1+2+3+4+5=15. + +def sum_positive_numbers(n): + return 0 +print(sum_positive_numbers(3)) # Should be 6 +print(sum_positive_numbers(5)) # Should be 15 + +#ans +def sum_positive_numbers(n): + if n < 1: + return 0 + total_sum = n + sum_positive_numbers(n-1) + return total_sum +print(sum_positive_numbers(3)) # Should be 6 +print(sum_positive_numbers(5)) # Should be 15 + +# 56 +# using while loop write code to print out the numbers 1 through 7. +number = 1 +while number <= 7: + print(number, end="\n") + number += 1 + +# 57 +# The show_letters function should print out each letter of a word on a separate line. Fill in the blanks to make that happen. +def show_letters(word): + for __: + print(__) + +show_letters("Hello") +# Should print one line per letter + +#ans +def show_letters(word): + for letter in word: + print(letter) + +show_letters("Hello") +# Should print one line per letter + +# 58 +# Complete the function digits(n) that returns how many digits the number has. For example: 25 has 2 digits and 144 has +# 3 digits. Tip: you can figure out the digits of a number by dividing it by 10 once per digit until there are no digits left. + +def digits(n): + count = 0 + if n == 0: + ___ + while (___): + count += 1 + ___ + return count + +print(digits(25)) # Should print 2 +print(digits(144)) # Should print 3 +print(digits(1000)) # Should print 4 +print(digits(0)) # Should print 1 + +#Ans +def digits(n): + count = 0 + if n == 1: + digits = int(n) + 1 + while (n>0): + count += 1 + n = n//10 + return count + +print(digits(25)) # Should print 2 +print(digits(144)) # Should print 3 +print(digits(1000)) # Should print 4 +print(digits(0)) # Should print 1 + + +# 59 +# This function prints out a multiplication table (where each number is the result of multiplying the first number +# of its row by the number at the top of its column). Fill in the blanks so that calling multiplication_table(1, 3) will print out: +# 1 2 3 +# 2 4 6 +# 3 6 9 + +def multiplication_table(start, stop): + for x in ___: + for y in ___: + print(str(x*y), end=" ") + print() + +multiplication_table(1, 3) +# Should print the multiplication table shown above + +#ans +def multiplication_table(start, stop): + for x in (start,stop-1,start+stop-1): + for y in (start,stop-1,start+stop-1): + print(str(x*y), end=" ") + print() + +multiplication_table(1, 3) +# Should print the multiplication table shown above + + +# 60: +#The counter function counts down from start +# to stop when start is bigger than stop, +# and counts up from start to stop otherwise. Fill in the blanks to make this work correctly. + +def counter(start, stop): + x = start + if ___: + return_string = "Counting down: " + while x>= stop: + return_string += str(x) + if ___: + return_string += "," + ___ + else: + return_string = "Counting up: " + while x <= stop: + return_string += str(x) + if ___: + return_string += "," + ___ + return return_string + +print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10" +print(counter(2, 1)) # Should be "Counting down: 2,1" +print(counter(5, 5)) # Should be "Counting up: 5" + +#ans +def counter(start, stop): + x = start + if x> stop: + return_string = "Counting down: " + while x>= stop: + return_string += str(x) + if x> stop: + return_string += "," + x -= 1 + else: + return_string = "Counting up: " + while x <= stop: + return_string += str(x) + if x < stop: + return_string += "," + x +=1 + return return_string +print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10" +print(counter(2, 1)) # Should be "Counting down: 2,1" +print(counter(5, 5)) + + +# 61 +#The even_numbers function returns a space-separated +# string of all positive numbers that are divisible by 2, up to and +# including the maximum that's passed into the function. +# For example, even_numbers(6) returns "2 4 6". Fill in the blank to make this work. +def counter(start, stop): + x = start + if x> stop: + return_string = "Counting down: " + while x>= stop: + return_string += str(x) + if x> stop: + return_string += "," + x -= 1 + else: + return_string = "Counting up: " + while x <= stop: + return_string += str(x) + if x < stop: + return_string += "," + x +=1 + return return_string +print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10" +print(counter(2, 1)) # Should be "Counting down: 2,1" +print(counter(5, 5)) + + From a21f9f5cab4a5e5ac7cff30e3a0194b29aa3caa7 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Thu, 6 Aug 2020 23:52:18 +0300 Subject: [PATCH 20/65] Update projects_and_quiz.py --- projects_and_quiz.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 535972f..20ae934 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -1022,5 +1022,11 @@ def counter(start, stop): print(counter(2, 1)) # Should be "Counting down: 2,1" print(counter(5, 5)) + + #Dictionaries + dict1 = {"name": "Mike", "salary": 8000} +temp = dict1.pop("age") +print(temp) + From 3faa20972393f819ec39f07d79b330a03ae701c2 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Thu, 6 Aug 2020 23:53:44 +0300 Subject: [PATCH 21/65] Update projects_and_quiz.py funcrtion and dictionaries --- projects_and_quiz.py | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 20ae934..16e7def 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -1029,4 +1029,18 @@ def counter(start, stop): print(temp) - +sampleDict = { + "class":{ + "student":{ + "name":"Mike", + "marks":{ + "physics":70, + "history":80 + } + } + } +}def displayPerson(*args): + for i in args: + print(i) + +displayPerson(name="Emma", age="25") From 0a9b0c46a18aaf218bf6d3acf056badb038af291 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Fri, 7 Aug 2020 00:53:06 +0300 Subject: [PATCH 22/65] Update projects_and_quiz.py strings and dictionaries --- projects_and_quiz.py | 89 ++++++++++++++++++++++++++++++++++---------- 1 file changed, 69 insertions(+), 20 deletions(-) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 16e7def..362663b 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -1021,26 +1021,75 @@ def counter(start, stop): print(counter(1, 10)) # Should be "Counting up: 1,2,3,4,5,6,7,8,9,10" print(counter(2, 1)) # Should be "Counting down: 2,1" print(counter(5, 5)) - - #Dictionaries - dict1 = {"name": "Mike", "salary": 8000} -temp = dict1.pop("age") -print(temp) +# 62 +# Modify the double_word function so that it returns the same word repeated twice, followed +# by the length of the new doubled word. For example, double_word("hello") should return hellohello10. + +def double_word(word): + return + +print(double_word("hello")) # Should return hellohello10 +print(double_word("abc")) # Should return abcabc6 +print(double_word("")) # Should return 0 + +#ans +def double_word(word): + return word + word+ (str(len(word)*2)) +print(double_word("hello")) # Should return hellohello10 +print(double_word("abc")) # Should return abcabc6 +print(double_word("")) # Should return 0 + +#63 +# accessing a char in strign +name = "Owen" +print(name[2]) + +#64 +#use Strings and indexing to access the last char in a string +mission = "To bring tech to all the university students" +print(mission[-1]) + +#65 +# Modify the first_and_last +# function so that it returns True if the first letter of the string is +# the same as the last letter of the string, False if they’re different. +# Remember that you can access characters using message[0] +# or message[-1]. Be careful how you handle the empty string, +# which should return True since nothing is equal to nothing. +def first_and_last(message): + + return False +print(first_and_last("else")) +print(first_and_last("tree")) +print(first_and_last("")) -sampleDict = { - "class":{ - "student":{ - "name":"Mike", - "marks":{ - "physics":70, - "history":80 - } - } - } -}def displayPerson(*args): - for i in args: - print(i) - -displayPerson(name="Emma", age="25") +#ans +def first_and_last(message): + if not message or message[0] == message[-1]: + return True + else: + return False +print(first_and_last("else")) +print(first_and_last("tree")) +print(first_and_last("")) + +# 66 +#Use String slicing in any word to form the word ran +fruit = "Orange" +print(fruit[1:4]) + +fruits = "pineapple" +print(fruits[:4]) +print(fruits[4:]) + +#67 +#correcting string error +message = "Timz is a doftware developer" +print(message) + +message = "Timz is a doftware developer" +new_message = message[0:11] + " s" + message[10:] +print(message) +print(new_message) From e6bd020521af3fc44304c433f688fe5bde577c49 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Fri, 7 Aug 2020 17:51:56 +0300 Subject: [PATCH 23/65] Update projects_and_quiz.py String indexing --- projects_and_quiz.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 362663b..012affb 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -1093,3 +1093,26 @@ def first_and_last(message): new_message = message[0:11] + " s" + message[10:] print(message) print(new_message) + +#Locating string using index +message = "Timz is a doftware developer" +print(message.index("a")) +#returns 8 including the space char + +#write code to check if a member is conatained in a string +message = "Timz is a doftware developer" +print(message.index("a")) #index 8 +# check is a value or variable is contained in a word. +print("Engineer" in message) # False +print("developer" in message) #True + +#68 +# Write an automation script to automate emails from an old domain to the new domain by an organization +# use functions and return the emails if already updated +def replace_domain(email, old_email, new_email): + if "@" + old_email in email: + index = email.index("@" + old_email) + new_email = email[:index] + "@" + new_email + return new_email + return email +print(replace_domain("timzowen","timz.owen@eldohub.com","google.com")) From a2efe6f8244772ce023c9f36d30c724cd1df3c88 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Fri, 7 Aug 2020 19:38:40 +0300 Subject: [PATCH 24/65] Update projects_and_quiz.py more string s questions --- projects_and_quiz.py | 65 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 012affb..60bdb8b 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -1116,3 +1116,68 @@ def replace_domain(email, old_email, new_email): return new_email return email print(replace_domain("timzowen","timz.owen@eldohub.com","google.com")) + + + +# 68 +# use python methods to convert a string to upper and lower case. +my_name = "timzowen".upper() +my_name2 = "TIMZOWEN".lower() +white_space = " no white ".strip() +right_white_space = " Again no whites".lstrip() +left_white_strip = " No left white steps".rstrip() +print(my_name) +print(my_name2) +print(white_space) +print(left_white_strip) +print(right_white_space) + + +is_numeric = "timz".isnumeric() +is_numeric2 = "13654".isnumeric() +is_numeric3 = "123kf123".isnumeric() +print(is_numeric) +print(is_numeric2) +print(is_numeric3) + +#convert int actual number usign string and add +results = int("12345") + int("54321") +print(results) #returns 66666 + +#joining a strign with spaces +spaces_join = " ".join(["This ", "is ", "a ", "string ", "joined ", "with ","spaces."]) +print(spaces_join) +three_dots = "...".join(["This", "is", "a", "string", "joined", "with","spaces."]) +print(three_dots) +split_a_sentence = "This will be splited into list of strings".split() +print(split_a_sentence) +#returns +This is a string joined with spaces. +This...is...a...string...joined...with...spaces. +['This', 'will', 'be', 'splited', 'into', 'list', 'of', 'strings'] + +# 69 +#Fill in the gaps in the initials function so that it returns the initials of the words contained in the phrase received, +#in upper case. For example: "Universal Serial Bus" should return "USB"; "local area network" should return "LAN". +def initials(phrase): + words = phrase.___ + result = "" + for word in words: + result += ___ + return ___ + +print(initials("Universal Serial Bus")) # Should be: USB +print(initials("local area network")) # Should be: LAN +print(initials("Operating system")) # Should be: OS + +#ans +def initials(phrase): + words = phrase.split() + result = "" + for word in words: + result += word[0].upper() + return result +print(initials("Universal Serial Bus")) # Should be: USB +print(initials("local area network")) # Should be: LAN +print(initials("Operating system")) # Should be: OS + From 860ff58ccad12d71924b69e455a3bf8cd22f4b0b Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Sun, 9 Aug 2020 23:29:28 +0300 Subject: [PATCH 25/65] Update projects_and_quiz.py String formatting --- projects_and_quiz.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 60bdb8b..7d2bb64 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -1181,3 +1181,46 @@ def initials(phrase): print(initials("local area network")) # Should be: LAN print(initials("Operating system")) # Should be: OS + +# 70 +# use Strign concatination with .formart to print an intergert and String together +user_name = "Timz" +number = len(user_name)*3 +print("Hello awesome {}, Your luck number today is {}".format(user_name, number)) + +#re-format to follow a different order +user_name = "Timz" +number = len(user_name)*3 +print("Hello awesome {}, Your luck number today is {}".format(user_name, number)) +print("Congratulations, your score is {score},{name}".format(score=len(user_name)*5,name=user_name )) + +# 71 +# Modify the student_grade function using the format method, +# so that it returns the phrase "X received Y% on the exam". For example, +# student_grade("Reed", 80) should return "Reed received 80% on the exam". +def student_grade(name, grade): + return "" +print(student_grade("Reed", 80)) +print(student_grade("Paige", 92)) +print(student_grade("Jesse", 85)) + +#ans +def student_grade(name, grade): + output = "{name} received {grade}% on the exam".format(name=name,grade=grade) + return output +print(student_grade("Reed", 80)) +print(student_grade("Paige", 92)) +print(student_grade("Jesse", 85)) + +#User format to print decimal to floating decimal points +distance = 2.5 +fuel_cost = distance*1.5 +print("Hiring cost: ${:.2f}. and total cost is ${:.2f} ".format(distance,fuel_cost)) +#ans Hiring cost: 2ドル.50. and total cost is 3ドル.75 + +# 72 +# use formating tp print a nice table and output to two dp floating point +def degree_to_cel(x): + return (x-32)*5/9 +for x in range(0,101,10): + print("{:>3} F | {:>6.2f} C ".format(x,degree_to_cel(x))) From 5e41b4e6547943816afaf6516adb2db4b516192a Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Sun, 9 Aug 2020 23:39:33 +0300 Subject: [PATCH 26/65] Update README.md README.md --- README.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 5f8ef5b..35b2691 100644 --- a/README.md +++ b/README.md @@ -1 +1,11 @@ -# python for all tech py related +### Let's Learn some Python + +Python is one of the most used programming language in large fields. + +Gettting to learn the basics to being a Pro Developer will help you solve programming problems and automate system and also + +run big models in /**machine Learning**/ and /**AI**/ + +## Check out some Cheat Sheet over here + +[Checkout more about String formatting from](https://docs.python.org/3/library/stdtypes.html#string-methods") From d0ac4e6a0f4b2c2918e7a79ee4d5db052c67ca2b Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Sun, 9 Aug 2020 23:41:33 +0300 Subject: [PATCH 27/65] Update README.md readme.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 35b2691..701785e 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ Python is one of the most used programming language in large fields. Gettting to learn the basics to being a Pro Developer will help you solve programming problems and automate system and also -run big models in /**machine Learning**/ and /**AI**/ +run big models in **machine Learning** and **AI** ## Check out some Cheat Sheet over here From 5f199d67948517458a93174a60ccd41c4259e23d Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月10日 00:05:41 +0300 Subject: [PATCH 28/65] Update README.md Readme.md --- README.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/README.md b/README.md index 701785e..bf92d66 100644 --- a/README.md +++ b/README.md @@ -9,3 +9,20 @@ run big models in **machine Learning** and **AI** ## Check out some Cheat Sheet over here [Checkout more about String formatting from](https://docs.python.org/3/library/stdtypes.html#string-methods") + +## Let's get familiar with some formating techniques + + +| Expression | Meaning | example | +| ------------- |:-------------:| ---------------------------: | +| {:d} | integer value | '{:d}'.format(10.5) → '10' +| {:.2f} | floating point with that many decimals | '{:.2f}'.format(0.5) → '0.50' +| {:.2s} | string with that many characters | '{:.2s}'.format('Python') → 'Py' +| {:<6s} | string aligned to the left that many spaces | '{:<6s}'.format('py') → 'Py ' +| {:>6s} | string aligned to the right that many spaces | '{:>6s}'.format('Py') → ' Py' +| {:^6s} | string centered in that many spaces | '{:^6s}'.format('Py') → ' Py ' + +more on formating + +[Checkout more on formatting (https://docs.python.org/3/library/string.html#format-specification-mini-language") + From 42e9299a32d7938ab4b64262f799c40db1d2f6af Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月10日 00:07:29 +0300 Subject: [PATCH 29/65] Create projects_quize_2.py formating --- projects_quize_2.py | 48 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 projects_quize_2.py diff --git a/projects_quize_2.py b/projects_quize_2.py new file mode 100644 index 0000000..cc09b84 --- /dev/null +++ b/projects_quize_2.py @@ -0,0 +1,48 @@ + +# 1 + + +# Using .format + +# "base string with {} placeholders".format(variables) + +example = "format() method" + +formatted_string = "this is an example of using the {} on a string".format(example) + +print(formatted_string) + +"""Outputs: +this is an example of using the format() method on a string +""" + +# If the placeholders indicate a number, +# they’re replaced by the variable corresponding to that order (starting at zero). +# "{0} {1}".format(first, second) + +first = "apple" +second = "banana" +third = "carrot" + +formatted_string = "{0} {2} {1}".format(first, second, third) + +print(formatted_string) + +"""Outputs: +apple carrot banana +""" + +# If the placeholders indicate a field name, they’re replaced by the variable +# corresponding to that field name. This means that parameters to format need to be passed indicating the field name. + +# "{var1} {var2}".format(var1=value1, var2=value2) +"{:exp1} {:exp2}".format(value1, value2) + + +# If the placeholders include a colon, what comes after the colon is a +# formatting expression. See below for the expression reference + +# {:d} integer value +'{:d}'.format(10.5) → '10' + +# From 187903ddd11899e900ea53b234c05a9d45eafa2f Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月10日 00:10:13 +0300 Subject: [PATCH 30/65] Update projects_and_quiz.py output formating --- projects_and_quiz.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/projects_and_quiz.py b/projects_and_quiz.py index 7d2bb64..2b29563 100644 --- a/projects_and_quiz.py +++ b/projects_and_quiz.py @@ -1224,3 +1224,15 @@ def degree_to_cel(x): return (x-32)*5/9 for x in range(0,101,10): print("{:>3} F | {:>6.2f} C ".format(x,degree_to_cel(x))) + + 0 F | -17.78 C + 10 F | -12.22 C + 20 F | -6.67 C + 30 F | -1.11 C + 40 F | 4.44 C + 50 F | 10.00 C + 60 F | 15.56 C + 70 F | 21.11 C + 80 F | 26.67 C + 90 F | 32.22 C +100 F | 37.78 C From 688cacda4c255be1669ef08fac9a746603b4030a Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月11日 16:29:32 +0300 Subject: [PATCH 31/65] Update projects_quize_2.py String quiz --- projects_quize_2.py | 119 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 118 insertions(+), 1 deletion(-) diff --git a/projects_quize_2.py b/projects_quize_2.py index cc09b84..1fc2c65 100644 --- a/projects_quize_2.py +++ b/projects_quize_2.py @@ -45,4 +45,121 @@ # {:d} integer value '{:d}'.format(10.5) → '10' -# + +# 2 +# # The is_palindrome function checks if a string is a palindrome. A palindrome +# is a string that can be equally read from left to right or right to left + +# omitting blank spaces, and ignoring capitalization. Examples of palindromes are words like kayak and radar, and phrases like "Never Odd or Even". +#Fill in the blanks in this function to return True if the passed string is a palindrome, False if not. +def is_palindrome(input_string): + # We'll create two strings, to compare them + new_string = "" + reverse_string = "" + # Traverse through each letter of the input string + for string in input_string: + # Add any non-blank letters to the + # end of one string, and to the front + # of the other string. + if string.repla : + new_string = ___ + reverse_string = ___ + # Compare the strings + if ___: + return True + return False + +print(is_palindrome("Never Odd or Even")) # Should be True +print(is_palindrome("abc")) # Should be False +print(is_palindrome("kayak")) # Should be True + +#Ans +def is_palindrome(input_string): + new_string = "" + reverse_string = "" + for string in input_string.lower(): + if string.replace(" ",""): + new_string = new_string + string + reverse_string = string + reverse_string + if reverse_string == new_string: + return True + return False + +print(is_palindrome("Never Odd or Even")) # Should be True +print(is_palindrome("abc")) # Should be False +print(is_palindrome("kayak")) # Should be True + +# 3 +# Using the format method, fill in the gaps in the convert_distance function so that it returns the phrase "X miles equals Y km", +# with Y having only 1 decimal place. For example, convert_distance(12) should return "12 miles equals 19.2 km". +def convert_distance(miles): + km = miles * 1.6 + result = "{miles} miles equals {:.1f} km".formart(miles=miles, km) + return result + +print(convert_distance(12)) # Should be: 12 miles equals 19.2 km +print(convert_distance(5.5)) # Should be: 5.5 miles equals 8.8 km +print(convert_distance(11)) # Should be: 11 miles equals 17.6 km + +# ans +# Fill in the gaps in the nametag function so that it uses the format method to return first_name and the +# first initial of last_name followed by a period. For example, nametag("Jane", "Smith") should return "Jane S." +def nametag(first_name, last_name): + return("___.".format(___)) + +print(nametag("Jane", "Smith")) +# Should display "Jane S." +print(nametag("Francesco", "Rinaldi")) +# Should display "Francesco R." +print(nametag("Jean-Luc", "Grand-Pierre")) +# Should display "Jean-Luc G." + + +# 4 +#The replace_ending function replaces the old string in a sentence +#with the new string, but only if the sentence ends with the old string. +#If there is more than one occurrence of the old string in the sentence, +#only the one at the end is replaced, not all of them. For example, +#replace_ending("abcabc", "abc", "xyz") should return abcxyz, not xyzxyz or xyzabc. The string +#comparison is case-sensitive, so replace_ending("abcabc", "ABC", "xyz") should return abcabc (no changes made). +def replace_ending(sentence, old, new): + # Check if the old string is at the end of the sentence + if ___: + # Using i as the slicing index, combine the part + # of the sentence up to the matched string at the + # end with the new string + i = ___ + new_sentence = ___ + return new_sentence + + # Return the original sentence if there is no match + return sentence + +print(replace_ending("It's raining cats and cats", "cats", "dogs")) +# Should display "It's raining cats and dogs" +print(replace_ending("She sells seashells by the seashore", "seashells", "donuts")) +# Should display "She sells seashells by the seashore" +print(replace_ending("The weather is nice in May", "may", "april")) +# Should display "The weather is nice in May" +print(replace_ending("The weather is nice in May", "May", "April")) +# Should display "The weather is nice in April" + +#ans +def replace_ending(sentence, old, new): + if sentence.endswith(old): + # Using i as the slicing index, combine the part + # of the sentence up to the matched string at the + # end with the new string + i=len(sentence) + l=len(old) + new_sentence = sentence[0:i-l] + new + return new_sentence + return sentence +print(replace_ending("It's raining cats and cats", "cats", "dogs")) +# Should display "It's raining cats and dogs" +print(replace_ending("She sells seashells by the seashore", "seashells", "donuts")) +# Should display "She sells seashells by the seashore" +print(replace_ending("The weather is nice in May", "may", "april")) +# Should display "The weather is nice in May" +print(replace_ending("The weather is nice in May", "May", "April")) +# Should display "The weather is nice in April" From 6530bd1cf2c1298d06b99fe103103a8652a92c5d Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月12日 18:19:55 +0300 Subject: [PATCH 32/65] Update projects_quize_2.py lists --- projects_quize_2.py | 138 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 138 insertions(+) diff --git a/projects_quize_2.py b/projects_quize_2.py index 1fc2c65..96e67cf 100644 --- a/projects_quize_2.py +++ b/projects_quize_2.py @@ -163,3 +163,141 @@ def replace_ending(sentence, old, new): # Should display "The weather is nice in May" print(replace_ending("The weather is nice in May", "May", "April")) # Should display "The weather is nice in April" + +# List +list_x = ["we", "are","cooking!","some","Chapati"] + +#possible operation on list like strings +print(list_x) +print(list_x[0]) +print(list_x[2:]) +print(list_x[1:3]) +print(len(list_x)) +print(type(list_x)) +print("are" in type_list) + +# 5 +# Using the "split" string method from the preceding lesson, complete the get_word function +# to return the {n}th word from a passed sentence. For example, get_word("This is a lesson about lists", 4) +# should return "lesson", which is the 4th word in this sentence. Hint: remember that list indexes start at 0, not 1. +def get_word(sentence, n): + # Only proceed if n is positive + if n> 0: + words = ___ + # Only proceed if n is not more than the number of words + if n <= len(words): + return(___) + return("") + +print(get_word("This is a lesson about lists", 4)) # Should print: lesson +print(get_word("This is a lesson about lists", -4)) # Nothing +print(get_word("Now we are cooking!", 1)) # Should print: Now +print(get_word("Now we are cooking!", 5)) # Nothing + +#ans +def get_word(sentence, n): + # Only proceed if n is positive + if n> 0: + words = sentence.split() + # Only proceed if n is not more than the number of words + if n <= len(words): + return words[n-1] + return (" ") +print(get_word("This is a lesson about lists", 4)) # Should print: lesson +print(get_word("This is a lesson about lists", -4)) # Nothing +print(get_word("Now we are cooking!", 1)) # Should print: Now +print(get_word("Now we are cooking!", 5)) # Nothing + + +# 6 +# list operations +#add items to the list. +cars = ["BMW","BENZ","TOYOTA","IZUZU","FORD"] +cars.append("AUDI") +print(cars) +#add to at a specific index +cars.insert(1,"HONDA") +print(cars) +#remove elements +cars.remove("IZUZU") +print(cars) +#remove elements using indexes +cars.pop(4) +print(cars) +#replace elements using indexes +cars[1] = "ZUZUKI" +print(cars) + +#ans +['BMW', 'BENZ', 'TOYOTA', 'IZUZU', 'FORD', 'AUDI'] +['BMW', 'HONDA', 'BENZ', 'TOYOTA', 'IZUZU', 'FORD', 'AUDI'] +['BMW', 'HONDA', 'BENZ', 'TOYOTA', 'FORD', 'AUDI'] +['BMW', 'HONDA', 'BENZ', 'TOYOTA', 'AUDI'] +['BMW', 'ZUZUKI', 'BENZ', 'TOYOTA', 'AUDI'] + + +# 7 +# The skip_elements function returns a list containing every other element from an input list, +# starting with the first element. +# Complete this function to do that, using the for loop to iterate through the input list. + +def skip_elements(elements): + # Initialize variables + new_list = [] + i = 0 + + # Iterate through the list + for ___ + # Does this element belong in the resulting list? + if ___ + # Add this element to the resulting list + ___ + # Increment i + ___ + + return ___ + +print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] +print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach'] +print(skip_elements([])) # Should be [] + +#ans +def skip_elements(elements): + # Initialize variables + new_list = [] + i = 0 + + # Iterate through the list + for words in elements: + # Does this element belong in the resulting list? + if i Date: 2020年8月13日 13:29:01 +0300 Subject: [PATCH 33/65] Update projects_quize_2.py more quiz and answers on list --- projects_quize_2.py | 163 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 163 insertions(+) diff --git a/projects_quize_2.py b/projects_quize_2.py index 96e67cf..bb6a435 100644 --- a/projects_quize_2.py +++ b/projects_quize_2.py @@ -301,3 +301,166 @@ def skip_elements(elements): # 8 #Lists and Tuples +#EX +tuples_here = ('Computer','Department','IP') +print(type(tuples_here)) + +#Ex +def convert_time(seconds): + hours = seconds // 3600 + minutes = (seconds - hours * 3600) // 60 + seconds_remaining = (seconds - (minutes * 60 + hours * 3600)) + return hours, minutes, seconds_remaining +result = convert_time(2000) +hours, minutes, seconds_remaining = result +print(result) +print(type(result)) +print(convert_time(4000)) +print(hours,minutes,seconds_remaining) + +(0, 33, 20) + +(1, 6, 40) +0 33 20 + + +# 9 +# use tuples to store information about a file: its name, its type and its size in bytes. +#Fill in the gaps in this code to return the size in kilobytes (a kilobyte is 1024 bytes) up to 2 decimal places. +def file_size(file_info): + ___, ___, ___= file_info + return("{:.2f}".format(___ / 1024)) + +print(file_size(('Class Assignment', 'docx', 17875))) # Should print 17.46 +print(file_size(('Notes', 'txt', 496))) # Should print 0.48 +print(file_size(('Program', 'py', 1239))) # Should print 1.21 + +# Ans +def file_size(file_info): + name, type, size= file_info + return("{:.2f}".format(size/ 1024)) +print(file_size(('Class Assignment', 'docx', 17875))) # Should print 17.46 +print(file_size(('Notes', 'txt', 496))) # Should print 0.48 +print(file_size(('Program', 'py', 1239))) # Should print 1.21 + +# summary +#. Strings are sequences of characters, and are immutable. Lists are sequences of elements of +# any data type, and are mutable. The third sequence type is the tuple. +# Tuples are like lists, since they can contain elements of any data type. But unlike lists, tuples are immutable. + +#Ex +animal =["twiga","simba","lion","Giraffe","elephant"] +char = 0 +for wildAnimals in animal: + char += len(animal) +print("total animals characters : {}, and in avarage are:{}".format(char,char/len(animal))) + +#using enumarate to find specific index +lecturers = ["mr Kebut", "mr Owen","Dr Maganga","Dr Rugiri","prof Wanyama","prof Chepkilot"] +for index,lecture in enumerate(lecturers): + print("{} - {} ".format(index + 1, lecture)) + +1 - mr Kebut +2 - mr Owen +3 - Dr Maganga +4 - Dr Rugiri +5 - prof Wanyama +6 - prof Chepkilot + + +# 10 +#Try out the enumerate function for yourself in this quick exercise. Complete the skip_elements +#function to return every other element from the list, this time using the enumerate function +#to check if an element is on an even position or an odd position. +def skip_elements(elements): + # code goes here + + return ___ + +print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] +print(skip_elements(['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach'] + +#ans 1 +def skip_elements(elements): + # code goes here + #Create an empty list + list=[] + #iterate through using enumarate + for index,element in enumerate(elements): + #check if the elements are even and proceed + if index%2==0: + list.append("{}".format(element)) + return list +print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] +print(skip_elements( + ['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) # Should be ['Orange', 'Strawberry', 'Peach'] + +#ans 2 +def skip_elements(elements): + elements = [v for i, v in enumerate(elements) if i % 2 == 0] + return elements +print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] +print(skip_elements( + ['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) + +#ans 3 +def skip_elements(elements): + # code goes here + element = [] + for i, e in enumerate(elements): + if i % 2 == 0: + element.append(e) + return element +print(skip_elements(["a", "b", "c", "d", "e", "f", "g"])) # Should be ['a', 'c', 'e', 'g'] +print(skip_elements( + ['Orange', 'Pineapple', 'Strawberry', 'Kiwi', 'Peach'])) + +# 11 +#using enumerate function, create an automation email task to print emails and user names; +def full_list_emails(employees): + #create an empaty list to store the emails + updated_list=[] + for names,emails in employees: + updated_list.append("{} <{}".format(names,emails)) + return updated_list +print(("timz@gmail.com","Timz owen"),("owen@gmail.com","Owen Gusir")) + +#List Comperehesion +# 12 +#Use List comprehesion in to reduce the the code to almost one line: + +multiple_list = [] +for x in range(1,20): + x=x*7 + multiple_list.append(x) +print(multiple_list) + +#ans +multiples = [ x*7 for x in range(1,20)] +print((multiples)) + +#iterate using list comprehension to find the lenght of words +coding_languages = ["Python","Java","Spring",".net","Ruby"] +leght_of_strings= [ len(coding_language) for coding_language in coding_languages] +print(leght_of_strings) + +#print values of numbers between 1 and 100 and only thos deveible by 5 +disivible_by_5 = [i for i in range(1,101) if i % 3 ==0] +print(disivible_by_5) + +# 13 +# The odd_numbers function returns a list of odd numbers between +# 1 and n, inclusively. Fill in the blanks in the function, using list comprehension. +# Hint: remember that list and range counters start at 0 and end at the limit minus 1. + +def odd_numbers(n): + return [x for x in ___ if ___] +print(odd_numbers(5)) # Should print [1, 3, 5] +print(odd_numbers(10)) # Should print [1, 3, 5, 7, 9] +print(odd_numbers(11)) # Should print [1, 3, 5, 7, 9, 11] +print(odd_numbers(1)) # Should print [1] +print(odd_numbers(-1)) # Should print [] + +#ans + + From 7cc3edb14c959744dae6b55f47467cbf2e1ebd29 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月13日 19:53:19 +0300 Subject: [PATCH 34/65] Update projects_quize_2.py practice quiz on list dictionaries --- projects_quize_2.py | 111 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 111 insertions(+) diff --git a/projects_quize_2.py b/projects_quize_2.py index bb6a435..7c42e5a 100644 --- a/projects_quize_2.py +++ b/projects_quize_2.py @@ -462,5 +462,116 @@ def odd_numbers(n): print(odd_numbers(-1)) # Should print [] #ans +def odd_numbers(n): + return [ x for x in range(1,n+1) if x % 2 != 0 ] + +print(odd_numbers(5)) # Should print [1, 3, 5] +print(odd_numbers(10)) # Should print [1, 3, 5, 7, 9] +print(odd_numbers(11)) # Should print [1, 3, 5, 7, 9, 11] +print(odd_numbers(1)) # Should print [1] +print(odd_numbers(-1)) # Should print []\ + +# 14 + +#Given a list of filenames, we want to rename all the files with extension hpp to the extension h. +# To do this, we would like to generate a new list called newfilenames, consisting of the new filenames. +#Fill in the blanks in the code using any of the methods you’ve learned thus far, like a for loop or a list comprehension. +filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"] +# Generate newfilenames as a list containing the new filenames +# using as many lines of code as your chosen method requires. +___ + +print(newfilenames) +# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"] + +#ans +filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"] +newfilenames = [] +for filename in filenames: + if ".hpp" in filename: + index = filename.index(".hpp") + newfilename = filename[:index] + ".h" + else: + newfilename = filename + newfilenames.append((filename,newfilename)) +print(newfilenames) +# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"] + +#ans 2 +filenames = ["program.c", "stdio.hpp", "sample.hpp", "a.out", "math.hpp", "hpp.out"] +newfilenames=[] +for file in filenames: + if file.endswith("hpp"): + newfilenames.append(file.replace(".hpp",".h")) + else: + newfilenames.append(file) +print(newfilenames) + + +# 15 +# The format_address function separates out parts of the address string into new strings: +# house_number and street_name, and returns: "house number X on street named Y". The +# format of the input string is: numeric house number, followed by the street name +# which may contain numbers, but never by themselves, and could be several words long. For example, +# "123 Main Street", "1001 1st Ave", or "55 North Center Drive". Fill in the gaps to complete this function. +def format_address(address_string): + # Declare variables + house_number = 0 + street_name = "" + # Separate the address string into parts + separated_address = address_string.split() + # Traverse through the address parts + for address in separated_address: + # Determine if the address part is the + # house number or part of the street name + if address.isnumeric(): + house_number = address + # Does anything else need to be done + # before returning the result? + else: + street_name += address + " " + # Return the formatted string + return "house number {} on street named {}".format(house_number, street_name) + +print(format_address("123 Main Street")) +# Should print: "house number 123 on street named Main Street" + +print(format_address("1001 1st Ave")) +# Should print: "house number 1001 on street named 1st Ave" + +print(format_address("55 North Center Drive")) +# Should print "house number 55 on street named North Center Drive" + + +# 16 +# The highlight_word function changes the given word in a sentence to its upper-case +# version. For example, highlight_word("Have a nice day", "nice") returns +# "Have a NICE day". Can you write this function in just one line? +def highlight_word(sentence, word): + return(sentence.replace(word, word.upper())) + +print(highlight_word("Have a nice day", "nice")) +print(highlight_word("Shhh, don't be so loud!", "loud")) +print(highlight_word("Automating with Python is fun", "fun")) + + +# +# create a function that turns text into pig latin: a simple text transformation +# that modifies each word moving the first character to the end and appending "ay" to the end. For example, python ends up as ythonpay. +def pig_latin(text): + say = "" + # Separate the text into words + words = ___ + for word in words: + # Create the pig latin word and add it to the list + ___ + # Turn the list back into a phrase + return ___ + +print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay" +print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay" + +# ans + From e81bf7ef82d14eb8da73a020c265365d9995357f Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月13日 20:34:39 +0300 Subject: [PATCH 35/65] Update projects_quize_2.py more quizes on list --- projects_quize_2.py | 156 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 156 insertions(+) diff --git a/projects_quize_2.py b/projects_quize_2.py index 7c42e5a..4703adb 100644 --- a/projects_quize_2.py +++ b/projects_quize_2.py @@ -574,4 +574,160 @@ def pig_latin(text): # ans +# ans +def pig_latin(text): + say = "" + pig_text = [] + # Separate the text into words + words = text.split() + for word in words: + # Create the pig latin word and add it to the list + word = word[1:] + word[0] + "ay" + pig_text.append(word) + # Turn the list back into a phrase + return ' '.join(pig_text) +print(pig_latin("hello how are you")) # Should be "ellohay owhay reaay ouyay" +print(pig_latin("programming in python is fun")) # Should be "rogrammingpay niay ythonpay siay unfay" + + +# 18 +# The permissions of a file in a Linux system are split into three sets of three permissions: read, write, and execute for +# the owner, group, and others. Each of the three values can be expressed as an octal number summing each permission, with +# 4 corresponding to read, 2 to write, and 1 to execute. Or it can be written with a string using the letters r, w, and x +# or - when the permission is not granted. For example: 640 is read/write for the owner, read for the group, and no permissions +# for the others; converted to a string, it would be: "rw-r-----" 755 is read/write/execute for the owner, and read/execute +# for group and others; converted +# to a string, it would be: "rwxr-xr-x" Fill in the blanks to make the code convert a permission in octal format into a string format. +def octal_to_string(octal): + result = "" + value_letters = [(4,"r"),(2,"w"),(1,"x")] + # Iterate over each of the digits in octal + for ___ in [int(n) for n in str(octal)]: + # Check for each of the permissions values + for value, letter in value_letters: + if ___>= value: + result += ___ + ___ -= value + else: + ___ + return result + +print(octal_to_string(755)) # Should be rwxr-xr-x +print(octal_to_string(644)) # Should be rw-r--r-- +print(octal_to_string(750)) # Should be rwxr-x--- +print(octal_to_string(600)) # Should be rw------- + +# Ans +def octal_to_string(octal): + permission = ["---", "--x", "-w-", "-wx", "r--", "r-x", "rw-", "rwx"] + result = "" + # Iterate over each of the digits in octal + for ___ in [int(n) for n in str(octal)]: + result += permission[___] + return result + +print(octal_to_string(755)) +print(octal_to_string(644)) +print(octal_to_string(750)) +print(octal_to_string(600)) + +#ans +def octal_to_string(octal): + result = "" + value_letters = [(4,"r"),(2,"w"),(1,"x")] + # Iterate over each of the digits in octal + for ___ in [int(n) for n in str(octal)]: + # Check for each of the permissions values + for value, letter in value_letters: + if ___>= value: + result += letter + ___ -= value + else: + result += "-" + return result + +print(octal_to_string(755)) +print(octal_to_string(644)) +print(octal_to_string(750)) +print(octal_to_string(600)) + +#ans +def octal_to_string(octal): + result = "" + value_letters = [(4,"r"),(2,"w"),(1,"x")] + # Iterate over each of the digits in octal + for i in [int(n) for n in str(octal)]: + # Check for each of the permissions values + for value, letter in value_letters: + if i>= value: + result += letter + i -= value + else: + result += '-' + return result +print(octal_to_string(755)) +print(octal_to_string(644)) +print(octal_to_string(750)) +print(octal_to_string(600)) + + +# 19 + +# The group_list function accepts a group name and a list of members, and returns a string with the format: group_name: +# member1, member2, ... For example, group_list("g", ["a","b","c"]) returns "g: a, b, c". Fill in the gaps in this function to do that. +def group_list(group, users): + members = ___ + return ___ + +print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"])) # Should be "Marketing: Mike, Karen, Jake, Tasha" +print(group_list("Engineering", ["Kim", "Jay", "Tom"])) # Should be "Engineering: Kim, Jay, Tom" +print(group_list("Users", "")) # Should be "Users:" + +# ans +def group_list(group, users): + members = ", ".join(users) + return ("{}:{}".format(group,members)) + +print(group_list("Marketing", ["Mike", "Karen", "Jake", "Tasha"])) # Should be "Marketing: Mike, Karen, Jake, Tasha" +print(group_list("Engineering", ["Kim", "Jay", "Tom"])) # Should be "Engineering: Kim, Jay, Tom" +print(group_list("Users", "")) # Should be "Users:" + + +# 20 + +# The guest_list function reads in a list of tuples with the name, age, and profession of each party guest, and prints +# the sentence "Guest is X years old and works as __." for each one. For example, +# guest_list(('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")) should print out: Ken is 30 years old and works as Chef. +# Pat is 35 years old and works as Lawyer. Amanda is 25 years old and works as Engineer. Fill in the gaps in this function to do that. +def guest_list(guests): + for ___: + ___ + print(___.format(___)) + +guest_list([('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")]) + +#Click Run to submit code +""" +Output should match: +Ken is 30 years old and works as Chef +Pat is 35 years old and works as Lawyer +Amanda is 25 years old and works as Engineer +""" + +#ans + +def guest_list(guests): + count = 0 + if count < 3: + for guest in guests: + name, age, job = guest + print("{} is {} years old and works as {}".format(name, age, job)) + count = count + 1 +guest_list([('Ken', 30, "Chef"), ("Pat", 35, 'Lawyer'), ('Amanda', 25, "Engineer")]) + +""" +Output should match: +Ken is 30 years old and works as Chef +Pat is 35 years old and works as Lawyer +""" From 569f0c773efd11adf73d47770e0c3af35481a7af Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月14日 01:05:14 +0300 Subject: [PATCH 36/65] Update projects_quize_2.py Dictionaries and list --- projects_quize_2.py | 213 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 213 insertions(+) diff --git a/projects_quize_2.py b/projects_quize_2.py index 4703adb..6c31732 100644 --- a/projects_quize_2.py +++ b/projects_quize_2.py @@ -731,3 +731,216 @@ def guest_list(guests): Pat is 35 years old and works as Lawyer """ + +# DICTIONARIES +# store data in key and value pair +dictiona_ary = {} + + +file_counts = {"jpg":12, "png":6,"csv":15,"pdf":45,"txt":2} +#add new data +file_counts["docx"] = 12 +#delete data +del file_counts["txt"] +#replace with same key +file_counts[png]=12 + +print(file_counts) +print(file_counts["pdf"]) +print("csv" in file_counts) +print("java" in file_counts) + +#output +{'jpg': 12, 'png': 12, 'csv': 15, 'pdf': 45, 'docx': 12} +45 +True +False + +# 21 +#The "toc" dictionary represents the table of contents for a book. Fill in the blanks to do the following: 1) +#add an entry for Epilogue on page 39. 2) Change the page number for Chapter 3 to 24. 3) Display the new +#dictionary contents. 4) Display True if there is Chapter 5, False if there isn't. + +toc = {"Introduction":1, "Chapter 1":4, "Chapter 2":11, "Chapter 3":25, "Chapter 4":30} +___ # Epilogue starts on page 39 +___ # Chapter 3 now starts on page 24 +___ # What are the current contents of the dictionary? +___ # Is there a Chapter 5? + +#ans +toc = {"Introduction":1, "Chapter 1":4, "Chapter 2":11, "Chapter 3":25, "Chapter 4":30} +toc["Epilogue"]=39 # Epilogue starts on page 39 +toc["Chapter 3"]=24 # Chapter 3 now starts on page 24 +print(toc) # What are the current contents of the dictionary? +print("Chapter 5" in toc) # Is there a Chapter 5? + +#Iterating through a dictionary +file_extenstion ={"jpg":12, "png":6,"csv":15,"pdf":45,"txt":2} +for extension in file_extenstion: + print(extension) + +jpg +png +csv +pdf +txt +for ext,size in file_extenstion.items(): + print("There are {} files with extension of {}".format(size,ext)) +#output +There are 12 files with extension of jpg +There are 6 files with extension of png +There are 15 files with extension of csv +There are 45 files with extension of pdf +There are 2 files with extension of txt + +print(file_extenstion.keys()) +print(file_extenstion.values()) +# output +dict_keys(['jpg', 'png', 'csv', 'pdf', 'txt']) +dict_values([12, 6, 15, 45, 2]) + + +# 22 +# Complete the code to iterate through the keys +# and values of the cool_beasts dictionary. Remember that the items +# method returns a tuple of key, value for each element in the dictionary. +cool_beasts = {"octopuses":"tentacles", "dolphins":"fins", "rhinos":"horns"} +for ___ in cool_beasts.items(): + print("{} have {}".format(___)) + +#ans +cool_beasts = {"octopuses":"tentacles", "dolphins":"fins", "rhinos":"horns"} +for beasts,tool in cool_beasts.items(): + print("{} have {}".format(beasts,tool)) +octopuses have tentacles +dolphins have fins +rhinos have horns + + +#counting characters in a string +def count_letter(text): + result = {} + for letter in text: + if letter not in result: + result[letter]=0 + result[letter] +=1 + return result +print(count_letter("Timz owen")) +print(count_letter("Kabudaaa") ) + +#output +{'T': 1, 'i': 1, 'm': 1, 'z': 1, ' ': 1, 'o': 1, 'w': 1, 'e': 1, 'n': 1} +{'K': 1, 'a': 4, 'b': 1, 'u': 1, 'd': 1} + +# 23 +#In Python, a dictionary can only hold a single value for a given key. To workaround this, our single value can be a +# list containing multiple values. Here we have a dictionary called "wardrobe" with items of clothing and their colors. +# Fill in the blanks to print a line for each item of clothing with each color, for example: "red shirt", "blue shirt", and so on. +wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]} +for __: + for __: + print("{} {}".format(__)) + + #answer + wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]} +count=0 +for key, value in wardrobe.items(): + for i in value: + if count <3: + print("{} shirt".format(i)) + count+=1 + else: + print("{} jeans".format(i)) + +#solution 2 +wardrobe = {"shirt":["red","blue","white"], "jeans":["blue","black"]} +for color, clothings in wardrobe.items(): + for clothing in clothings: + print("{} {}".format(clothing,color)) + +# 24 +# The email_list function receives a dictionary, which contains domain names as keys, and a +# list of users as values. Fill in the blanks to generate a list that contains complete email addresses (e.g. diana.prince@gmail.com). +def email_list(domains): + emails = [] + for ___: + for user in users: + emails.___ + return(emails) + +print(email_list({"gmail.com": ["clark.kent", "diana.prince", "peter.parker"], + "yahoo.com": ["barbara.gordon", "jean.grey"], "hotmail.com": ["bruce.wayne"]})) + +#ans + +# 25 +# The groups_per_user function receives a dictionary, which contains group names with the list of users. Users can belong +# to multiple groups. Fill in the blanks to return a dictionary with the users as keys and a list of their groups as values + +def groups_per_user(group_dictionary): + user_groups = {} + # Go through group_dictionary + for ___: + # Now go through the users in the group + for ___: + # Now add the group to the the list of +# groups for this user, creating the entry +# in the dictionary if necessary + + return(user_groups) + +print(groups_per_user({"local": ["admin", "userA"], + "public": ["admin", "userB"], + "administrator": ["admin"] })) + +#solution 3 +def groups_per_user(group_dictionary): + user_groups = {} + for group, users in group_dictionary.items(): + for user in users: + user_groups.setdefault(user, []).append(group) + return user_groups +print(groups_per_user({"local": ["admin", "userA"], + "public": ["admin", "userB"], + "administrator": ["admin"] })) + +#solution 3 + +# # 26 +# Question 26 +# The add_prices function returns the total price of all of the groceries in the dictionary. Fill in the blanks to complete this function. + +def add_prices(basket): + # Initialize the variable that will be used for the calculation + total = 0 + # Iterate through the dictionary items + for ___: + # Add each price to the total calculation + # Hint: how do you access the values of + # dictionary items? + total += ___ + # Limit the return value to 2 decimal places + return round(total, 2) + +groceries = {"bananas": 1.56, "apples": 2.50, "oranges": 0.99, "bread": 4.59, + "coffee": 6.99, "milk": 3.39, "eggs": 2.98, "cheese": 5.44} + +print(add_prices(groceries)) # Should print 28.44 + +#ans +def add_prices(basket): + # Initialize the variable that will be used for the calculation + total = 0 + # Iterate through the dictionary items + for i in basket: + # Add each price to the total calculation + # Hint: how do you access the values of + # dictionary items? + total += basket[i] + # Limit the return value to 2 decimal places + return round(total, 2) + +groceries = {"bananas": 1.56, "apples": 2.50, "oranges": 0.99, "bread": 4.59, + "coffee": 6.99, "milk": 3.39, "eggs": 2.98, "cheese": 5.44} + +print(add_prices(groceries)) # Should print 28.44 From 856ec1ab56b1fb5ade208607f05167b4a73077d8 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月14日 18:47:36 +0300 Subject: [PATCH 37/65] Create project_quiz_3.py more advanced quizes --- project_quiz_3.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 project_quiz_3.py diff --git a/project_quiz_3.py b/project_quiz_3.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/project_quiz_3.py @@ -0,0 +1 @@ + From 80e8d41f63ca448386724f9cb629c02b61ba9526 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月14日 18:52:33 +0300 Subject: [PATCH 38/65] Update and rename project_quiz_3.py to projecst_quize_3.py more on dictionaries and list --- projecst_quize_3.py | 154 ++++++++++++++++++++++++++++++++++++++++++++ project_quiz_3.py | 1 - 2 files changed, 154 insertions(+), 1 deletion(-) create mode 100644 projecst_quize_3.py delete mode 100644 project_quiz_3.py diff --git a/projecst_quize_3.py b/projecst_quize_3.py new file mode 100644 index 0000000..be1f29a --- /dev/null +++ b/projecst_quize_3.py @@ -0,0 +1,154 @@ +#Coninuation from projects quiz 2 +# 27 + +# The format_address function separates out parts of the address string into new strings: house_number and street_name, +# and returns: "house number X on street named Y". The format of the input string is: numeric house number, followed by +# the street name which may contain numbers, but never by themselves, and could be several words long. For example, +# "123 Main Street", "1001 1st Ave", or "55 North Center Drive". Fill in the gaps to complete this function. + +def format_address(address_string): + # Declare variables + + # Separate the address string into parts + + # Traverse through the address parts + for __: + # Determine if the address part is the + # house number or part of the street name + + # Does anything else need to be done + # before returning the result? + + # Return the formatted string + return "house number {} on street named {}".format(__) + +print(format_address("123 Main Street")) +# Should print: "house number 123 on street named Main Street" + +print(format_address("1001 1st Ave")) +# Should print: "house number 1001 on street named 1st Ave" + +print(format_address("55 North Center Drive")) +# Should print "house number 55 on street named North Center Drive" + + +#ans +def format_address(address_string): + # Declare variables + house_number=' ' + street_name=" " + + # Separate the address string into parts + x=address_string.split(" ") + # Traverse through the address parts + for y in x: + if(y.isdigit()): + house_number=y + else: + street_name+=y + street_name+=' ' + # Determine if the address part is the + # house number or part of the street name + # Does anything else need to be done + # before returning the result? + + # Return the formatted string + return "house number {} on street named {}".format(house_number,street_name) + +print(format_address("123 Main Street")) +# Should print: "house number 123 on street named Main Street" + +print(format_address("1001 1st Ave")) +# Should print: "house number 1001 on street named 1st Ave" + +print(format_address("55 North Center Drive")) +# Should print "house number 55 on street named North Center Drive" + + +#soln 2 +def format_address(address_string): + num, st = address_string.split(' ',1) + return f"house number {num} on street named {st}" +print(format_address("123 Main Street")) +# Should print: "house number 123 on street named Main Street" + + +# soln3 +def format_address(address_string): + # Declare variables + number = '' + street = '' + # Separate the address string into parts + address_string = address_string.split() + # Traverse through the address parts + for add in address_string: + # Determine if the address part is the + # house number or part of the street name + if add.isdigit(): + number += add + # Does anything else need to be done + # before returning the result? + else : + street += add + # Return the formatted string + return "house number {} on street named {}".format(number, street) + +print(format_address("123 Main Street")) +# Should print: "house number 123 on street named Main Street" + +print(format_address("1001 1st Ave")) +# Should print: "house number 1001 on street named 1st Ave" + +print(format_address("55 North Center Drive")) +# Should print "house number 55 on street named North Center Drive" + + +# 28 + +#The highlight_word function changes the given word in a sentence to its upper-case version. +#For example, highlight_word("Have a nice day", "nice") returns "Have a NICE day". Can you write this function in just one line? +def highlight_word(sentence, word): + return(___) +print(highlight_word("Have a nice day", "nice")) +print(highlight_word("Shhh, don't be so loud!", "loud")) +print(highlight_word("Automating with Python is fun", "fun")) + +# soln 1 +def highlight_word(sentence, word): + return(sentence.replace(word,word.upper())) +print(highlight_word("Have a nice day", "nice")) +print(highlight_word("Shhh, don't be so loud!", "loud")) +print(highlight_word("Automating with Python is fun", "fun")) + + +# 29 + +# A professor with two assistants, Jamie and Drew, wants an attendance list of the students, in the order that they +# arrived in the classroom. Drew was the first one to note which students arrived, and then Jamie took over. After the +# class, they each entered their lists into the computer and emailed them to the professor, who needs to combine them +# into one, in the order of each student's arrival. Jamie emailed a follow-up, saying that her list is in reverse order. +# Complete the steps to combine them into one list as follows: +# the contents of Drew's list, followed by Jamie's list in reverse order, to get an accurate list of the students as they arrived. + +def combine_lists(list1, list2): + # Generate a new list containing the elements of list2 + # Followed by the elements of list1 in reverse order + + +Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"] +Drews_list = ["Mike", "Carol", "Greg", "Marcia"] + +print(combine_lists(Jamies_list, Drews_list)) + +#soln 1 +def combine_lists(list1, list2): + # Generate a new list containing the elements of list2 + # Followed by the elements of list1 in reverse order + new_list=list2 + for i in reversed(range(len(list1))): + new_list.append(list1[i]) + return new_list +Jamies_list = ["Alice", "Cindy", "Bobby", "Jan", "Peter"] +Drews_list = ["Mike", "Carol", "Greg", "Marcia"] + +print(combine_lists(Jamies_list, Drews_list)) diff --git a/project_quiz_3.py b/project_quiz_3.py deleted file mode 100644 index 8b13789..0000000 --- a/project_quiz_3.py +++ /dev/null @@ -1 +0,0 @@ - From bc4e907d143b08acaa3455bc31a330afa43b31c6 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月15日 22:19:05 +0300 Subject: [PATCH 39/65] Rename projecst_quize_3.py to projects_quize_3.py final dictionary and list quiz and solutions --- projecst_quize_3.py => projects_quize_3.py | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename projecst_quize_3.py => projects_quize_3.py (100%) diff --git a/projecst_quize_3.py b/projects_quize_3.py similarity index 100% rename from projecst_quize_3.py rename to projects_quize_3.py From 5001401b3fb2371dd38c1dbae5f2a89216344594 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月16日 23:04:38 +0300 Subject: [PATCH 40/65] Create quizes_projects_4_OOP.py Object-oriented programming --- quizes_projects_4_OOP.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 quizes_projects_4_OOP.py diff --git a/quizes_projects_4_OOP.py b/quizes_projects_4_OOP.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/quizes_projects_4_OOP.py @@ -0,0 +1 @@ + From 4279fa8f6248cc5cb5591fb1689813bbb3418c0b Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月17日 00:06:05 +0300 Subject: [PATCH 41/65] Update quizes_projects_4_OOP.py Hello, classes .py --- quizes_projects_4_OOP.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/quizes_projects_4_OOP.py b/quizes_projects_4_OOP.py index 8b13789..361490b 100644 --- a/quizes_projects_4_OOP.py +++ b/quizes_projects_4_OOP.py @@ -1 +1,19 @@ +# OBJECT ORIENTED PROGRAMMING WITH PYTHON QUIZES AND PROJECTS: +# Declaring a class: (empty class uses pass to show it has no members or attributes) +class Fruits: + pass + +#try out this +class Apple: + color = "" + size = "" + taste = "" +# assign a varibale the function to make it callable +callAple = Apple() +# now assign values to them using the .DOT notation +callAple.color = "Green" +callAple.size = "Small" +callAple.taste = "very sweet" +# print the elements +print(callAple.color, callAple.size,callAple.taste, end="") From 2bfe12835131a2bac1da5524c58a589198ca0e25 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月17日 10:49:50 +0300 Subject: [PATCH 42/65] Update quizes_projects_4_OOP.py OOP on classes and objects --- quizes_projects_4_OOP.py | 209 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 209 insertions(+) diff --git a/quizes_projects_4_OOP.py b/quizes_projects_4_OOP.py index 361490b..ebaf9d1 100644 --- a/quizes_projects_4_OOP.py +++ b/quizes_projects_4_OOP.py @@ -17,3 +17,212 @@ class Apple: callAple.taste = "very sweet" # print the elements print(callAple.color, callAple.size,callAple.taste, end="") + + + +# 1 +# complete the code below to print some poems +class ___: + color = 'unknown' + +rose = Flower() +rose.color = ___ + +violet = ___ +___ + +this_pun_is_for_you = ___ + +print("Roses are {},".format(rose.color)) +print("violets are {},".format(violet.color)) +print(this_pun_is_for_you) + +#soln +class Flower: + color = 'unknown' + +rose = Flower() +rose.color = "red" + +violet = Flower() +violet.color="blue" + +this_pun_is_for_you = "this pun is for you" + +print("Roses are {},".format(rose.color)) +print("violets are {},".format(violet.color)) +print(this_pun_is_for_you) + + +# 2 +#Creating new instances of class objects can be a great way to keep track of values using attributes associated with +# the object. The values of these attributes can be easily changed at the object level. The following code illustrates +# a famous quote by George Bernard Shaw,using objects to represent people. Fill in the blanks to make the code satisfy +# the behavior described in the quote. +# "If you have an apple and I have an apple and we exchange these apples then +# you and I will still each have one apple. But if you have an idea and I have +# an idea and we exchange these ideas, then each of us will have two ideas." +# George Bernard Shaw + +class Person: + apples = 0 + ideas = 0 + +johanna = Person() +johanna.apples = 1 +johanna.ideas = 1 + +martin = Person() +martin.apples = 2 +martin.ideas = 1 + +def exchange_apples(you, me): +#Here, despite G.B. Shaw's quote, our characters have started with #different amounts of apples so we can better observe the results. +#We're going to have Martin and Johanna exchange ALL their apples with #one another. +#Hint: how would you switch values of variables, +#so that "you" and "me" will exchange ALL their apples with one another? +#Do you need a temporary variable to store one of the values? +#You may need more than one line of code to do that, which is OK. + ___ + return you.apples, me.apples + +def exchange_ideas(you, me): + #"you" and "me" will share our ideas with one another. + #What operations need to be performed, so that each object receives + #the shared number of ideas? + #Hint: how would you assign the total number of ideas to + #each idea attribute? Do you need a temporary variable to store + #the sum of ideas, or can you find another way? + #Use as many lines of code as you need here. + you.ideas ___ + me.ideas ___ + return you.ideas, me.ideas + +exchange_apples(johanna, martin) +print("Johanna has {} apples and Martin has {} apples".format(johanna.apples, martin.apples)) +exchange_ideas(johanna, martin) +print("Johanna has {} ideas and Martin has {} ideas".format(johanna.ideas, martin.ideas)) + + +#soln +# "If you have an apple and I have an apple and we exchange these apples then +# you and I will still each have one apple. But if you have an idea and I have +# an idea and we exchange these ideas, then each of us will have two ideas." +# George Bernard Shaw + +class Person: + apples = 0 + ideas = 0 + +johanna = Person() +johanna.apples = 1 +johanna.ideas = 1 + +martin = Person() +martin.apples = 2 +martin.ideas = 1 + +def exchange_apples(you, me): +#Here, despite G.B. Shaw's quote, our characters have started with #different amounts of apples so we can better observe the results. +#We're going to have Martin and Johanna exchange ALL their apples with #one another. +#Hint: how would you switch values of variables, +#so that "you" and "me" will exchange ALL their apples with one another? +#Do you need a temporary variable to store one of the values? +#You may need more than one line of code to do that, which is OK. + x = 0 + x=you.apples + you.apples=me.apples + me.apples=x + return you.apples, me.apples + +def exchange_ideas(you, me): + #"you" and "me" will share our ideas with one another. + #What operations need to be performed, so that each object receives + #the shared number of ideas? + #Hint: how would you assign the total number of ideas to + #each idea attribute? Do you need a temporary variable to store + #the sum of ideas, or can you find another way? + #Use as many lines of code as you need here. + x = 0 + x = you.ideas + you.ideas += me.ideas + me.ideas+=x + + return you.ideas, me.ideas + +exchange_apples(johanna, martin) +print("Johanna has {} apples and Martin has {} apples".format(johanna.apples, martin.apples)) +exchange_ideas(johanna, martin) +print("Johanna has {} ideas and Martin has {} ideas".format(johanna.ideas, martin.ideas)) + + +# 3 + +# The City class has the following attributes: name, country (where the city is located), elevation (measured in meters), +# and population (approximate, according to recent statistics). Fill in the blanks of the max_elevation_city function to +# return the name of the city and its country (separated by a comma), when comparing the 3 defined instances for a +# specified minimal population. For example, +# calling the function for a minimum population of 1 million: max_elevation_city(1000000) should return "Sofia, Bulgaria". + +# define a basic city class +class City: + name = "" + country = "" + elevation = 0 + population = 0 + +# create a new instance of the City class and +# define each attribute +city1 = City() +city1.name = "Cusco" +city1.country = "Peru" +city1.elevation = 3399 +city1.population = 358052 + +# create a new instance of the City class and +# define each attribute +city2 = City() +city2.name = "Sofia" +city2.country = "Bulgaria" +city2.elevation = 2290 +city2.population = 1241675 + +# create a new instance of the City class and +# define each attribute +city3 = City() +city3.name = "Seoul" +city3.country = "South Korea" +city3.elevation = 38 +city3.population = 9733509 + +def max_elevation_city(min_population): + # Initialize the variable that will hold +# the information of the city with +# the highest elevation + return_city = City() + + # Evaluate the 1st instance to meet the requirements: + # does city #1 have at least min_population and + # is its elevation the highest evaluated so far? + if ___ + return_city = ___ + # Evaluate the 2nd instance to meet the requirements: + # does city #2 have at least min_population and + # is its elevation the highest evaluated so far? + if ___ + return_city = ___ + # Evaluate the 3rd instance to meet the requirements: + # does city #3 have at least min_population and + # is its elevation the highest evaluated so far? + if ___ + return_city = ___ + + #Format the return string + if return_city.name: + return ___ + else: + return "" + +print(max_elevation_city(100000)) # Should print "Cusco, Peru" +print(max_elevation_city(1000000)) # Should print "Sofia, Bulgaria" +print(max_elevation_city(10000000)) # Should print "" From 3a1d2719fae73fde1a9d7a179bccc9a0d9f31645 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月17日 10:51:09 +0300 Subject: [PATCH 43/65] Update quizes_projects_4_OOP.py soln to OOP quizzes update --- quizes_projects_4_OOP.py | 117 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) diff --git a/quizes_projects_4_OOP.py b/quizes_projects_4_OOP.py index ebaf9d1..ec53222 100644 --- a/quizes_projects_4_OOP.py +++ b/quizes_projects_4_OOP.py @@ -226,3 +226,120 @@ def max_elevation_city(min_population): print(max_elevation_city(100000)) # Should print "Cusco, Peru" print(max_elevation_city(1000000)) # Should print "Sofia, Bulgaria" print(max_elevation_city(10000000)) # Should print "" + + + +#soln +# define a basic city class +class City: + name = "" + country = "" + elevation = 0 + population = 0 + + +# create a new instance of the City class and +# define each attribute +city1 = City() +city1.name = "Cusco" +city1.country = "Peru" +city1.elevation = 3399 +city1.population = 358052 + +# create a new instance of the City class and +# define each attribute +city2 = City() +city2.name = "Sofia" +city2.country = "Bulgaria" +city2.elevation = 2290 +city2.population = 1241675 + +# create a new instance of the City class and +# define each attribute +city3 = City() +city3.name = "Seoul" +city3.country = "South Korea" +city3.elevation = 38 +city3.population = 9733509 + + +def max_elevation_city(min_population): + # Initialize the variable that will hold + # the information of the city with + # the highest elevation + return_city = City() + + # Evaluate the 1st instance to meet the requirements: + # does city #1 have at least min_population and + # is its elevation the highest evaluated so far? + if city1.population>= min_population and city1.elevation> return_city.elevation: + return_city = city1 + # Evaluate the 2nd instance to meet the requirements: + # does city #2 have at least min_population and + # is its elevation the highest evaluated so far? + if city2.population>= min_population and city2.elevation> return_city.elevation: + return_city = city2 + # Evaluate the 3rd instance to meet the requirements: + # does city #3 have at least min_population and + # is its elevation the highest evaluated so far? + if city3.population>= min_population and city3.elevation> return_city.elevation: + return_city = city3 + + # Format the return string + if return_city.name: + return ("{}, {}".format(return_city.name, return_city.country)) + else: + return "" + + +print(max_elevation_city(100000)) # Should print "Cusco, Peru" +print(max_elevation_city(1000000)) # Should print "Sofia, Bulgaria" +print(max_elevation_city(10000000)) # Should print "" + + +# 4 +# We have two pieces of furniture: a brown wood table and a red leather couch. Fill in the blanks following +# the creation of each Furniture class instance, so that the describe_furniture function can format a +# sentence that describes these pieces as follows: "This piece of furniture is made of {color} {material}" + +class Furniture: + color = "" + material = "" + +table = Furniture() +___ +___ + +couch = Furniture() +___ +___ + +def describe_furniture(piece): + return ("This piece of furniture is made of {} {}".format(piece.color, piece.material)) + +print(describe_furniture(table)) +# Should be "This piece of furniture is made of brown wood" +print(describe_furniture(couch)) +# Should be "This piece of furniture is made of red leather" + + +#soln +class Furniture: + color = "" + material = "" + +table = Furniture() +table.color="brown" +table.material="wood" + +couch = Furniture() +couch.color="red" +couch.material="leather" + +def describe_furniture(piece): + return ("This piece of furniture is made of {} {}".format(piece.color, piece.material)) + +print(describe_furniture(table)) +# Should be "This piece of furniture is made of brown wood" +print(describe_furniture(couch)) +# Should be "This piece of furniture is made of red leather" From 9d802409069a5788538ba2e238135fde2ce75f70 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月18日 22:06:09 +0300 Subject: [PATCH 44/65] Update quizes_projects_4_OOP.py classes and return values --- quizes_projects_4_OOP.py | 64 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/quizes_projects_4_OOP.py b/quizes_projects_4_OOP.py index ec53222..c9181bf 100644 --- a/quizes_projects_4_OOP.py +++ b/quizes_projects_4_OOP.py @@ -343,3 +343,67 @@ def describe_furniture(piece): # Should be "This piece of furniture is made of brown wood" print(describe_furniture(couch)) # Should be "This piece of furniture is made of red leather" + + + + +#methods in classes Exmaple +class Animals: + def animalSounds(self): + print("Wouh wouh!!") +dog = Animals() +print(dog.animalSounds()) + + +#EX 2 +class Dog: + def barking(self): + print("Wouuh, wouuh") +lion = Dog() +print(lion.barking()) + +# Ex 3 +class Bmw: + def bmwType(self): + brand="bmw3201" + print("This brand is {}, and is the best in the market".format(brand)) +brandCar = Bmw() +print(brandCar.bmwType()) + +#EX 4 +#uses self and declared above the function to allow the member varibales to be changeable +class Bmw: + brand = "bmw3201" + def bmwType(self): + print("This brand is {}, and is the best in the market".format(self.brand)) +brandCar = Bmw() +print(brandCar.bmwType()) +brandCar.brand = "BMWX3" +print(brandCar.bmwType()) + +#createing more than one instance from the same class +class Bmw: + brand = "bmw3201" + def bmwType(self): + print("This brand is {}, and is the best in the market".format(self.brand)) +brandCar = Bmw() +print(brandCar.bmwType()) +brandCar.brand = "BMWX3" +print(brandCar.bmwType()) + +#Instance 2 +newbrand = Bmw() +newbrand.brand = "BMWX6" +print(newbrand.bmwType()) + + +#Return values from classes and methods +class Monkey: + farms_attacked = 0 + + def moneky_mtoto(self): + return self.farms_attacked * 12 +monkeys = Monkey() +print(monkeys.moneky_mtoto()) +new_mobkey = monkeys.farms_attacked = 10 +print(monkeys.moneky_mtoto()) From 3b3b5eb0ce3d086d53b4c2a9ef7a3926e765dcb8 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月19日 00:44:12 +0300 Subject: [PATCH 45/65] Update quizes_projects_4_OOP.py more probelm and solution on oop --- quizes_projects_4_OOP.py | 235 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 235 insertions(+) diff --git a/quizes_projects_4_OOP.py b/quizes_projects_4_OOP.py index c9181bf..c0b5c60 100644 --- a/quizes_projects_4_OOP.py +++ b/quizes_projects_4_OOP.py @@ -407,3 +407,238 @@ def moneky_mtoto(self): print(monkeys.moneky_mtoto()) new_mobkey = monkeys.farms_attacked = 10 print(monkeys.moneky_mtoto()) + + + +# Q5 +#OK, now it’s your turn! Have a go at writing methods +# for a class. Create a Dog class with dog_years based +# on the Piglet class shown before (one human year is about 7 dog years). +class Dog: + years = 0 + __ + +fido=Dog() +fido.years=3 +print(fido.dog_years()) + +# soln +class Dog: + years = 0 + def dog_years(self): + return self.years*7 + +fido=Dog() +fido.years=3 +print(fido.dog_years()) + +# CONSTRUCTOR AND IMPORTANCT METHODS: +#Constructors allows us to pass in parameters directly to the instances created +#example +class Coffee: + def __init__(self, brand, flavour): + self.brand = brand + self.flavour = flavour +drinkCoffee = Coffee("mac Coffee", "black") +print(drinkCoffee.brand) +print(drinkCoffee.flavour) + +#Q 6: +# Want to see this in action? In this code, there's a Person class that has an attribute name, +# which gets set when constructing the object. Fill in the blanks so that 1) when an instance of the class is +# created, the attribute gets set correctly, and 2) when the greeting() method is called, the greeting states the assigned name. +class Person: + def __init__(self, name): + self.name = ___ + def greeting(self): + # Should return "hi, my name is " followed by the name of the Person. + return ___ + +# Create a new instance with a name of your choice +some_person = ___ +# Call the greeting method +print(some_person.___) + +#soln +class Person: + def __init__(self, name): + self.name = name + def greeting(self): + # Should return "hi, my name is " followed by the name of the Person. + user_name = ("hi, my name is {}".format(self.name)) + return user_name + +# Create a new instance with a name of your choice +some_person = Person("owen") +# Call the greeting method +print(some_person.greeting()) + + +#soln 2 +class Person: + def __init__(self, name): + self.name = name + def greeting(self): + # Should return "hi, my name is " followed by the name of the Person. + return "hi, my name is {}".format(self.name) + +# Create a new instance with a name of your choice +some_person = Person("Owen") +# Call the greeting method +print(some_person.greeting()) + + +#using __str__ to print direct out put and not storage address by computer on ommiting str conversion +class Computer: + def __init__(self,model,storage): + self.model =model + self.storage=storage + def __str__(self): + return "Model {} had a storage of {}".format(self.model,self.storage) +pc = Computer("HP",str(10)) +print(pc) # Model HP had a storga of 10 + + +#using DocString for documenting your work. (Typing help to the funciton or methods show what it does) +>>> def to_seconds(hours, minutes, seconds): +... """Returns the amount of seconds in the given hours, minutes and seconds.""" +... return hours*3600+minutes*60+seconds +...>>> help(to_seconds) +Help on function to_seconds in module __main__: + +to_seconds(hours, minutes, seconds) + Returns the amount of seconds in the given hours, minutes and seconds. + +#more example +class ClassName: + """Documentation for the class.""" + def method_name(self, other_parameters): + """Documentation for the method.""" + body_of_method + +def function_name(parameters): + """Documentation for the function.""" + body_of_function + + +# Q 7: +#write code to define an Elevator class. The elevator has a current floor, it also has a top and a bottom floor +# that are the minimum and maximum floors it can go to. Fill in the blanks to make the elevator go through the floors requested. + +class Elevator: + def __init__(self, bottom, top, current): + """Initializes the Elevator instance.""" + pass + def up(self): + """Makes the elevator go up one floor.""" + pass + def down(self): + """Makes the elevator go down one floor.""" + pass + def go_to(self, floor): + """Makes the elevator go to the specific floor.""" + pass + +elevator = Elevator(-1, 10, 0) + +#soln +class Elevator: + def __init__(self, bottom, top, current): + """Initializes the Elevator instance.""" + self.bottom = bottom + self.top=top + self.current=current + def up(self,current): + """Makes the elevator go up one floor.""" + if self.current < self.top: + return self.current+1 + def down(self, bottom): + """Makes the elevator go down one floor.""" + if self.current> self.top: + return self.current -1 + def go_to(self, floor): + """Makes the elevator go to the specific floor.""" + self.floor=floor + return self.floor +elevator = Elevator(-1, 10, 0) + + +#soln +class Elevator: + def __init__(self, bottom, top, current): + """Initializes the Elevator instance.""" + self.bottom = bottom + self.top = top + self.current=current + def up(self): + """Makes the elevator go up one floor.""" + if self.current < self.top: + return self.current + 1 + def down(self): + """Makes the elevator go down one floor.""" + if self.current>self.bottom: + return self.current - 1 + def go_to(self, floor): + """Makes the elevator go to the specific floor.""" + if self.floor <= self.top and self.floor>=self.bottom: + return self.current = floor + +elevator = Elevator(-1, 10, 0) + +#soln +class Elevator: + def __init__(self, bottom, top, current): + """Initializes the Elevator instance.""" + self.bottom = 0 + self.top = 0 + self.current = 0 + def up(self): + """Makes the elevator go up one floor.""" + if self.current != self.top: + return self.current + 1 + def down(self): + """Makes the elevator go down one floor.""" + if self.current != self.bottom: + return self.current - 1 + def go_to(self, floor): + """Makes the elevator go to the specific floor.""" + self.current = floor + return self.current + +elevator = Elevator(-1, 10, 0) + +#soln +class Elevator: + def __init__(self, bottom, top, current): + """Initializes the Elevator instance.""" + self.bottom = 0 + self.top = 10 + self.current = 0 + def up(self): + """Makes the elevator go up one floor.""" + if self.current == 10: + self.current += 0 + else: + self.current += 1 + def down(self): + """Makes the elevator go down one floor.""" + if self.current <= -1: + self.current -= 0 + """Makes the elevator go down one floor.""" + else: + self.current -= 1 + + def go_to(self, floor): + """Makes the elevator go to the specific floor.""" + self.current = floor + def __str__(self): + return "Current floor: {}".format(self.current) + +elevator = Elevator(-1, 10, 0) + +elevator.up() +elevator.current #should output 1 +elevator.down() +elevator.current #should output 0 +elevator.go_to(10) +elevator.current #should output 10 From 51a6d39b0b9f8d1495b3cecf522558251af36803 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月20日 23:39:12 +0300 Subject: [PATCH 46/65] Update quizes_projects_4_OOP.py Inheritance --- quizes_projects_4_OOP.py | 77 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) diff --git a/quizes_projects_4_OOP.py b/quizes_projects_4_OOP.py index c0b5c60..ab67be6 100644 --- a/quizes_projects_4_OOP.py +++ b/quizes_projects_4_OOP.py @@ -642,3 +642,80 @@ def __str__(self): elevator.current #should output 0 elevator.go_to(10) elevator.current #should output 10 + + +#INHERITANCE +#This allows us to reuse our code base: +#Inherits behavior from the root parent for all the siblings +class Cars: + def __init__(self,max_speed, model): + self.speed = max_speed + self.model = model + +#create an instance of Zubaru class +class Zubaru(Cars): + pass +class Bmw(Cars): + pass + +zubaru_squad = Zubaru("200km/h", "Zubaru impreza") +bima_squad = Bmw("400km/hr", "BMW X6") +print(zubaru_squad.speed) +print(bima_squad.model) + + +#Example 2 +class Animal: + sound="" + def __init__(self,name): + self.name = name + def speak(self): + print("{sound} I'm {name}! {sound}".format(name = self.name, sound=self.sound)) +class Piglet(Animal): + sound = "Oink" +hamlet=Piglet("Hamlet") +print(hamlet.speak()) +class Dog(Animal): + sound = "Wouuuuuuh" +barking = Dog("Simba") +print(barking.speak()) + + +# Q 8 +#Let’s create a new class together and inherit from it. Below we have a base class called Clothing. Together, +#let’s create a second class, called Shirt, that inherits methods from the Clothing class. Fill in the blanks to make it work properly. +class Clothing: + material = "" + def __init__(self,name): + self.name = name + def checkmaterial(self): + print("This {} is made of {}".format(self.___,self.___)) + +class Shirt(___): + material="Cotton" + + +polo = Shirt("Polo") +polo.checkmaterial() + + +#soln +class Clothing: + material = "" + + + def __init__(self, name): + self.name = name + + + def checkmaterial(self): + print("This {} is made of {}".format(self.name, self.material)) + + +class Shirt(Clothing): + material = "Cotton" + + +polo = Shirt("Polo") +print(polo.checkmaterial()) + From 7cfbda8a31ac79ea16cf7a3cad035dd48fc7fe02 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月22日 14:28:56 +0300 Subject: [PATCH 47/65] Update quizes_projects_4_OOP.py the final quiz on classes and objects --- quizes_projects_4_OOP.py | 136 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 136 insertions(+) diff --git a/quizes_projects_4_OOP.py b/quizes_projects_4_OOP.py index ab67be6..c6e8970 100644 --- a/quizes_projects_4_OOP.py +++ b/quizes_projects_4_OOP.py @@ -719,3 +719,139 @@ class Shirt(Clothing): polo = Shirt("Polo") print(polo.checkmaterial()) + + + +#summary + +#In object-oriented programming, the concept of inheritance allows you to build relationships between objects, +# grouping together similar concepts and reducing code duplication. Let's create a custom Fruit class with color and flavor attributes: +>>> class Fruit: +... def __init__(self, color, flavor): +... self.color = color +... self.flavor = flavor + + +#We defined a Fruit class with a constructor for color and flavor attributes. Next, we'll define an Apple class along with a new Grape +# class, both of which we want to inherit properties and behaviors from the Fruit class: +>>> class Apple(Fruit): +... pass +... +>>> class Grape(Fruit): +... pass + +# In Python, we use parentheses in the class declaration to have the class inherit from the Fruit class. So in this example, +# we’re instructing our computer that both the Apple class and Grape class inherit from the Fruit class. This means that they +# both have the same constructor method which sets the color and flavor attributes. We can now create instances of our Apple +# and Grape classes: + +>>> granny_smith = Apple("green", "tart") +>>> carnelian = Grape("purple", "sweet") +>>> print(granny_smith.flavor) +tart +>>> print(carnelian.color) +purple + + + +# COMPOSITION: +#Allows you to use an instances of a class where classes are not related to each other +class Repository: + def __init__(self): + self.packages = {} + def add_packages(self, package): + self.packages[package.name]=package + def total_size(self): + result = 0 + for package in self.packages.value(): + result += package.size + return result + + +# 9 + +# Let’s expand a bit on our Clothing classes from the previous in-video question. Your mission: Finish the +# "Stock_by_Material" method and iterate over the amount of each item of a given material that is in stock. +# When you’re finished, the script should add up to 10 cotton Polo shirts. +class Clothing: + stock={ 'name': [],'material' :[], 'amount':[]} + def __init__(self,name): + material = "" + self.name = name + def add_item(self, name, material, amount): + Clothing.stock['name'].append(self.name) + Clothing.stock['material'].append(self.material) + Clothing.stock['amount'].append(amount) + def Stock_by_Material(self, material): + count=0 + n=0 + for item in Clothing.stock['___']: + if item == material: + count += Clothing.___['amount'][n] + n+=1 + return count + +class shirt(Clothing): + material="Cotton" +class pants(Clothing): + material="Cotton" + +polo = shirt("Polo") +sweatpants = pants("Sweatpants") +polo.add_item(polo.name, polo.material, 4) +sweatpants.add_item(sweatpants.name, sweatpants.material, 6) +current_stock = polo.Stock_by_Material("Cotton") +print(current_stock) + + +#soln +class Clothing: + stock={ 'name': [],'material' :[], 'amount':[]} + def __init__(self,name): + material = "" + self.name = name + def add_item(self, name, material, amount): + Clothing.stock['name'].append(self.name) + Clothing.stock['material'].append(self.material) + Clothing.stock['amount'].append(amount) + def Stock_by_Material(self, material): + count=0 + n=0 + for item in Clothing.stock['material']: + if item == material: + count += Clothing.stock['amount'][n] + n+=1 + return count + +class shirt(Clothing): + material="Cotton" +class pants(Clothing): + material="Cotton" + +polo = shirt("Polo") +sweatpants = pants("Sweatpants") +polo.add_item(polo.name, polo.material, 4) +sweatpants.add_item(sweatpants.name, sweatpants.material, 6) +current_stock = polo.Stock_by_Material("Cotton") +print(current_stock) + + +# You can have a situation where two different classes are related, but there is no inheritance going on. +# This is referred to as composition -- where one class makes use of code contained in another class. +# For example, imagine we have a Package class which represents a software package. It contains attributes +# about the software package, like name, version, and size. We also have a Repository class which represents +# all the packages available for installation. While there’s no inheritance relationship between the two classes, +# they are related. The Repository class will contain a dictionary or +# list of Packages that are contained in the repository. Let's take a look at an example Repository class definition: +>>> class Repository: +... def __init__(self): +... self.packages = {} +... def add_package(self, package): +... self.packages[package.name] = package +... def total_size(self): +... result = 0 +... for package in self.packages.values(): +... result += package.size +... return result + + From c5ff5d07e90a48debfe1093ca6c1890a80460cbe Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月22日 14:46:34 +0300 Subject: [PATCH 48/65] Update quizes_projects_4_OOP.py updated the modules OOP --- quizes_projects_4_OOP.py | 241 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 241 insertions(+) diff --git a/quizes_projects_4_OOP.py b/quizes_projects_4_OOP.py index c6e8970..984dc7d 100644 --- a/quizes_projects_4_OOP.py +++ b/quizes_projects_4_OOP.py @@ -855,3 +855,244 @@ class pants(Clothing): ... return result +# UPNEXT ARE MODULES:: +# modules allow us to organize functions, methods,classes and any other data related together in a structured way. + +#EX 1: +import random + +print(random.randint(1,5)) +print(random.randint(1,5)) +print(random.randint(1,5)) + +2 +5 +4 + +# EX 2 +# using datetime +import datetime + +current_time = datetime.datetime.now() +print(type(current_time)) +print(current_time) +print(current_time.year) +print(current_time.time()) +print(current_time + datetime.timedelta(days=30)) #prints after certain time scheduled +#output + + +2020年08月21日 18:12:51.615840 +2020 +18:12:51.615840 +2020年09月20日 18:12:51.615840 + + +#final quiz combinations +#Begin Portion 1 + +#In this exercise, we'll create a few classes to simulate a server that's taking connections from +# the outside and then a load balancer that ensures that there are enough servers to serve those connections. +# To represent the servers that are taking care of the connections, we'll use a Server class. Each connection +# is represented by an id, that could, for example, be the IP address of the computer connecting to the server. +# For our simulation, each connection creates a random amount of load in the server, between 1 and 10. +# Run the following code that defines this Server class. + +import random + +class Server: + def __init__(self): + """Creates a new server instance, with no active connections.""" + self.connections = {} + + def add_connection(self, connection_id): + """Adds a new connection to this server.""" + connection_load = random.random()*10+1 + # Add the connection to the dictionary with the calculated load + + def close_connection(self, connection_id): + """Closes a connection on this server.""" + # Remove the connection from the dictionary + + def load(self): + """Calculates the current load for all connections.""" + total = 0 + # Add up the load for each of the connections + return total + + def __str__(self): + """Returns a string with the current load of the server""" + return "{:.2f}%".format(self.load()) + +#End Portion 1# + +#create a server instance +server = Server() +server.add_connection("192.168.1.1") + +print(server.load()) # should give you a 0 meaning no connected server + +#close server connecition +server.close_connection("192.168.1.1") +print(server.load()) + + + + + + +# LOADSERVER +class LoadBalancing: + def __init__(self): + """Initialize the load balancing system with one server""" + self.connections = {} + self.servers = [Server()] + + def add_connection(self, connection_id): + """Randomly selects a server and adds a connection to it.""" + server = random.choice(self.servers) + self.connection_id = connection_id + # Add the connection to the dictionary with the selected server + self.connections[self.connection_id]=server + print (server.load()) + # Add the connection to the server + Server.add_connection(server) + + def close_connection(self, connection_id): + """Closes the connection on the the server corresponding to connection_id.""" + # Find out the right server + server = self.connections[connection_id] + # Close the connection on the server + Server.close_connection(server) + # Remove the connection from the load balancer + del self.connections[connection_id] + + + #LOAD2 + + class LoadBalancing: + def __init__(self): + """Initialize the load balancing system with one server""" + self.connections = {} + self.servers = [Server()] + + def add_connection(self, connection_id): + """Randomly selects a server and adds a connection to it.""" + server = random.choice(self.servers) + self.connection_id = connection_id + # Add the connection to the dictionary with the selected server + self.connections[self.connection_id]=server + print (server.load()) + # Add the connection to the server + server.add_connection(server) + + def close_connection(self, connection_id): + """Closes the connection on the the server corresponding to connection_id.""" + # Find out the right server + server = self.connections[connection_id] + # Close the connection on the server + server.close_connection(server) + # Remove the connection from the load balancer + del self.connections[connection_id] + + def avg_load(self): + """Calculates the average load of all servers""" + # Sum the load of each server and divide by the amount of servers + total = 0 + for connection in self.connections.values(): + #for servs in self.connection.: + total += connection.load() + return total + + def ensure_availability(self): + """If the average load is higher than 50, spin up a new server""" + if avg_load(self)> 0.5: + print ("xxx") + pass + + def __str__(self): + """Returns a string with the load for each server.""" + loads = [str(server) for server in self.servers] + return "[{}]".format(",".join(loads)) +#End Portion 2# + + +# Alright, we now have a basic implementation of the server class. Let's look at the basic LoadBalancing class. +# This class will start with only one server available. When a connection gets added, it will randomly select a +# server to serve that connection, and then pass on the connection to the server. +# The LoadBalancing class also needs to keep track of the ongoing connections to be able to close them. This is the basic structure: +#Begin Portion 2# +class LoadBalancing: + def __init__(self): + """Initialize the load balancing system with one server""" + self.connections = {} + self.servers = [Server()] + + def add_connection(self, connection_id): + """Randomly selects a server and adds a connection to it.""" + server = random.choice(self.servers) + # Add the connection to the dictionary with the selected server + # Add the connection to the server + self.connections[connection_id] = server + server.add_connection(connection_id) + self.ensure_availability() + + def close_connection(self, connection_id): + """Closes the connection on the the server corresponding to connection_id.""" + # Find out the right server + # Close the connection on the server + # Remove the connection from the load balancer + self.connections[connection_id].close_connection(connection_id) + del self.connections[connection_id] + + def avg_load(self): + """Calculates the average load of all servers""" + # Sum the load of each server and divide by the amount of servers + total = 0 + for loads in self.servers: + total += loads.load() + return total/len(self.servers) + + def ensure_availability(self): + """If the average load is higher than 50, spin up a new server""" + if self.avg_load()> 50.00: + self.servers.append(Server()) + + def __str__(self): + """Returns a string with the load for each server.""" + loads = [str(server) for server in self.servers] + return "[{}]".format(",".join(loads)) +#End Portion 2# + +#Begin Portion 1# +import random + +class Server: + def __init__(self): + """Creates a new server instance, with no active connections.""" + self.connections = {} + + def add_connection(self, connection_id): + """Adds a new connection to this server.""" + connection_load = random.random()*10+1 + self.connections[connection_id] = connection_load + # Add the connection to the dictionary with the calculated load + + def close_connection(self, connection_id): + """Closes a connection on this server.""" + # Remove the connection from the dictionary + del self.connections[connection_id] + + def load(self): + """Calculates the current load for all connections.""" + total = 0 + # Add up the load for each of the connections + for load in self.connections.values(): + total += load + return total + + def __str__(self): + """Returns a string with the current load of the server""" + return "{:.2f}%".format(self.load()) + +# CONGRATULATIONS. Advanced python coming sooon From b0554a415a8598a4a409cec3c7ebcd9f4493d6a8 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月22日 14:52:06 +0300 Subject: [PATCH 49/65] Update README.md updated README.md --- README.md | 34 +++++++++++++++++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index bf92d66..8aec45d 100644 --- a/README.md +++ b/README.md @@ -24,5 +24,37 @@ run big models in **machine Learning** and **AI** more on formating -[Checkout more on formatting (https://docs.python.org/3/library/string.html#format-specification-mini-language") +[Checkout more on formatting (https://docs.python.org/3/library/string.html#format-specification-mini-language")] + +Classes define the behavior of all instances of a specific class. +Each variable of a specific class is an instance or object. +Objects can have attributes, which store information about the object. +You can make objects do work by calling their methods. +The first parameter of the methods (self) represents the current instance. +Methods are just like functions, but they can only be used through a class. + + +Special methods start and end with __. +Special methods have specific names, like __init__ for the constructor or __str__ for the conversion to string. + +### more on Dictionaries + +[Checkout more on dicttionaries ("https://docs.python.org/3/library/stdtypes.html#mapping-types-dict ")] + + +### Learn more about running python in jupiter here: + +[Checkout more on Jupyter ("https://www.datacamp.com/community/tutorials/tutorial-jupyter-notebook ")] + + +### Understanding modules in python + +[Checkout more on Jupyter ("https://pypi.org/")] + +In the modelues quizes, you get to simulate a real servre configuraitons. + + + + + From f7e4930510104f5f611f3d24668b8aaaf872762c Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月22日 14:52:56 +0300 Subject: [PATCH 50/65] Update README.md readme typo --- README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 8aec45d..928a978 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ run big models in **machine Learning** and **AI** more on formating -[Checkout more on formatting (https://docs.python.org/3/library/string.html#format-specification-mini-language")] +[Checkout more on formatting (https://docs.python.org/3/library/string.html#format-specification-mini-language") Classes define the behavior of all instances of a specific class. Each variable of a specific class is an instance or object. @@ -39,17 +39,17 @@ Special methods have specific names, like __init__ for the constructor or __str_ ### more on Dictionaries -[Checkout more on dicttionaries ("https://docs.python.org/3/library/stdtypes.html#mapping-types-dict ")] +[Checkout more on dicttionaries ("https://docs.python.org/3/library/stdtypes.html#mapping-types-dict ") -### Learn more about running python in jupiter here: +### Learn more about running python in jupyter here: -[Checkout more on Jupyter ("https://www.datacamp.com/community/tutorials/tutorial-jupyter-notebook ")] +[Checkout more on Jupyter ("https://www.datacamp.com/community/tutorials/tutorial-jupyter-notebook ") ### Understanding modules in python -[Checkout more on Jupyter ("https://pypi.org/")] +[Checkout more on Jupyter ("https://pypi.org/") In the modelues quizes, you get to simulate a real servre configuraitons. From e6feba074b59b8a7cbfb60bce66593810535425f Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月22日 14:57:16 +0300 Subject: [PATCH 51/65] Update README.md readme typo --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 928a978..5d0f9f2 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ run big models in **machine Learning** and **AI** ## Check out some Cheat Sheet over here -[Checkout more about String formatting from](https://docs.python.org/3/library/stdtypes.html#string-methods") +[Checkout more about String formatting from](https://docs.python.org/3/library/stdtypes.html#string-methods) ## Let's get familiar with some formating techniques @@ -39,17 +39,17 @@ Special methods have specific names, like __init__ for the constructor or __str_ ### more on Dictionaries -[Checkout more on dicttionaries ("https://docs.python.org/3/library/stdtypes.html#mapping-types-dict ") +[Checkout more on dicttionaries ](https://docs.python.org/3/library/stdtypes.html#mapping-types-dict) ### Learn more about running python in jupyter here: -[Checkout more on Jupyter ("https://www.datacamp.com/community/tutorials/tutorial-jupyter-notebook ") +[Checkout more on Jupyter ](https://www.datacamp.com/community/tutorials/tutorial-jupyter-notebook ) ### Understanding modules in python -[Checkout more on Jupyter ("https://pypi.org/") +[Checkout more on Jupyter] (https://pypi.org/) In the modelues quizes, you get to simulate a real servre configuraitons. From 52b41010678f11b36a543d53a0684af59c1c78e6 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月22日 14:58:59 +0300 Subject: [PATCH 52/65] Update README.md readme typo --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5d0f9f2..9418b1c 100644 --- a/README.md +++ b/README.md @@ -24,7 +24,7 @@ run big models in **machine Learning** and **AI** more on formating -[Checkout more on formatting (https://docs.python.org/3/library/string.html#format-specification-mini-language") +[Checkout more on formatting ](https://docs.python.org/3/library/string.html#format-specification-mini-language) Classes define the behavior of all instances of a specific class. Each variable of a specific class is an instance or object. @@ -49,7 +49,7 @@ Special methods have specific names, like __init__ for the constructor or __str_ ### Understanding modules in python -[Checkout more on Jupyter] (https://pypi.org/) +[Checkout more on Jupyter](https://pypi.org/) In the modelues quizes, you get to simulate a real servre configuraitons. From 5cb75f0a8db045117406fbe01aef8beefcdadf99 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月23日 21:59:29 +0300 Subject: [PATCH 53/65] Create Z_Final_project.py final projects files and resources --- Z_Final_project.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 Z_Final_project.py diff --git a/Z_Final_project.py b/Z_Final_project.py new file mode 100644 index 0000000..93f5cea --- /dev/null +++ b/Z_Final_project.py @@ -0,0 +1 @@ +# working on final project to combine all the learnt concepts into 1 From 1e896f29728a288b6b21b6cdebacdb8af8ce4c89 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月24日 23:20:54 +0300 Subject: [PATCH 54/65] Create quiz_random_n_sol.py random quiz n solution update --- quiz_random_n_sol.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 quiz_random_n_sol.py diff --git a/quiz_random_n_sol.py b/quiz_random_n_sol.py new file mode 100644 index 0000000..351cc2f --- /dev/null +++ b/quiz_random_n_sol.py @@ -0,0 +1,23 @@ +#1 +class Geeks: + def __init__(self, id): + self.id = id + +manager = Geeks(100) + +manager.__dict__['life'] = 49 + +print manager.life + len(manager.__dict__) # 15 + + +#2 dictionary = {} +dictionary[1] = 1 +dictionary['1'] = 2 +dictionary[1] += 1 + +sum = 0 +for k in dictionary: + sum += dictionary[k] + +print sum # 4 + From 2cfb1c34919e8eec11d2e1a29817f36e94aa3e41 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月25日 21:42:52 +0300 Subject: [PATCH 55/65] Update Z_Final_project.py Problem statement --- Z_Final_project.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Z_Final_project.py b/Z_Final_project.py index 93f5cea..a633ec8 100644 --- a/Z_Final_project.py +++ b/Z_Final_project.py @@ -1 +1,5 @@ # working on final project to combine all the learnt concepts into 1 +# problem statement. +#The CTO wants to monitor all the computer usage by all engineers. Using Python , +# write an automation script that will produce a report when each user logged in and out, +# and how long each user used the computers. From f176c522025643bf71711c779b839594a8bafc1d Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月26日 12:21:50 +0300 Subject: [PATCH 56/65] Update and rename Z_Final_project.py to projects_Mini_Final_project.py uploaded final script to a mini final projects --- Z_Final_project.py | 5 --- projects_Mini_Final_project.py | 66 ++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+), 5 deletions(-) delete mode 100644 Z_Final_project.py create mode 100644 projects_Mini_Final_project.py diff --git a/Z_Final_project.py b/Z_Final_project.py deleted file mode 100644 index a633ec8..0000000 --- a/Z_Final_project.py +++ /dev/null @@ -1,5 +0,0 @@ -# working on final project to combine all the learnt concepts into 1 -# problem statement. -#The CTO wants to monitor all the computer usage by all engineers. Using Python , -# write an automation script that will produce a report when each user logged in and out, -# and how long each user used the computers. diff --git a/projects_Mini_Final_project.py b/projects_Mini_Final_project.py new file mode 100644 index 0000000..e0158f1 --- /dev/null +++ b/projects_Mini_Final_project.py @@ -0,0 +1,66 @@ +# working on final project to combine all the learnt concepts into 1 +# problem statement. +#The CTO wants to monitor all the computer usage by all engineers. Using Python , +# write an automation script that will produce a report when each user logged in and out, +# and how long each user used the computers. + + + +# writing real script: +# first sort all the processes by date using a function: +def get_event_date(event): + return event.date +#get current user and pass the sorted date function +# first sort all the processes by date using a function: +def get_event_date(event): + return event.date +#get current user and pass the sorted date function +# first sort all the processes by date using a function: +def get_event_date(event): + return event.date +#get current user and pass the sorted date function +def current_users(events): + events.sort(key=get_event_date) + #create a dictionary to store the values + machines = {} + for event in events: + #check if a mchine exist in dictionary else add + if event.machine not in machines: + machines[event.machine] = set() + if event.type == "logout": + machines[event.machine].add(event.user) + elif event.type == "logout": + machines[event.machine].remove(event.user) + return machines +#create a different function to print the report +def generate_report(machines): + for machines,users in machines.items(): + #print only thoses who logged in and not those who loged in and out: + if len(users)>0: + users_list = ", ".join(users) + print("{} : {}".format(machines,users_list)) + +class Event: + def __init__(self, event_date, event_type, machine_name,user): + self.date = event_date + self.type = event_type + self.machine =machine_name + self.user = user +events = [ + Event("2020-05-12 12:50PM","login","mail-server local", "owen"), + Event("2021-04-12 4:50PM","logout","mail-server local", "james"), + Event("2020-05-14 2:50PM","login","workstation local", "shem"), + Event("2020-05-1 16:50PM","login","mail-server local", "Timz"), + Event("2020-06-19 18:50PM","logout","admin server local", "brian"), + Event("2020-02-12 17:50PM","login","mail-server local", "chris") + ] + +#try creation +users = current_users(events) +print(users) + +# generate user report +generate_report(users) + +# CONGRATALTIONS: +# Up next final project; From da1bbc09d4525ba92788b16cf225374d01cd11e1 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月27日 05:39:25 +0300 Subject: [PATCH 57/65] Create project_final_project_word_cloud.py problem statement --- project_final_project_word_cloud.py | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 project_final_project_word_cloud.py diff --git a/project_final_project_word_cloud.py b/project_final_project_word_cloud.py new file mode 100644 index 0000000..ddb10fa --- /dev/null +++ b/project_final_project_word_cloud.py @@ -0,0 +1,4 @@ + +#FINAL PROJECT OF SYSTEM AUTOMATION: +# using word cloud +# Create a dictionary with words and word frequencies that can be passed to the generate_from_frequencies function of the WordCloud class. From e6bd64c54a218a52f232ca9bc5cc7b7ea1a1ba57 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月27日 05:40:45 +0300 Subject: [PATCH 58/65] Update project_final_project_word_cloud.py guidelines and suggestions. --- project_final_project_word_cloud.py | 61 +++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/project_final_project_word_cloud.py b/project_final_project_word_cloud.py index ddb10fa..92a9234 100644 --- a/project_final_project_word_cloud.py +++ b/project_final_project_word_cloud.py @@ -2,3 +2,64 @@ #FINAL PROJECT OF SYSTEM AUTOMATION: # using word cloud # Create a dictionary with words and word frequencies that can be passed to the generate_from_frequencies function of the WordCloud class. + +#snipset of generating images with word cloud +cloud = wordcloud.WordCloud() +cloud.generate_from_frequencies(frequencies) +cloud.to_file("myfile.jpg") + +# start writing code: + +# Here are all the installs and imports you will need for your word cloud script and uploader widget + +!pip install wordcloud +!pip install fileupload +!pip install ipywidgets +!jupyter nbextension install --py --user fileupload +!jupyter nbextension enable --py fileupload + +import wordcloud +import numpy as np +from matplotlib import pyplot as plt +from IPython.display import display +import fileupload +import io +import sys + +# load the file with text +# This is the uploader widget + +def _upload(): + + _upload_widget = fileupload.FileUploadWidget() + + def _cb(change): + global file_contents + decoded = io.StringIO(change['owner'].data.decode('utf-8')) + filename = change['owner'].filename + print('Uploaded `{}` ({:.2f} kB)'.format( + filename, len(decoded.read()) / 2 **10)) + file_contents = decoded.getvalue() + + _upload_widget.observe(_cb, names='data') + display(_upload_widget) + +_upload() + +# remove unnecessary wordings +def calculate_frequencies(file_contents): + # Here is a list of punctuations and uninteresting words you can use to process your text + punctuations = '''!()-[]{};:'",円./?@#$%^&*_~''' + uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my", \ + "we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its", "they", "them", \ + "their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be", "been", "being", \ + "have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when", "where", "how", \ + "all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very", "can", "will", "just"] + + # write code to complete the task + + #wordcloud + cloud = wordcloud.WordCloud() + cloud.generate_from_frequencies() + return cloud.to_array() + From 813a780360f0d75c2578519956ccd7ded0513374 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年8月27日 05:41:30 +0300 Subject: [PATCH 59/65] Update project_final_project_word_cloud.py final solutions to the problem --- project_final_project_word_cloud.py | 71 +++++++++++++++++++++++++++++ 1 file changed, 71 insertions(+) diff --git a/project_final_project_word_cloud.py b/project_final_project_word_cloud.py index 92a9234..ce0d39c 100644 --- a/project_final_project_word_cloud.py +++ b/project_final_project_word_cloud.py @@ -63,3 +63,74 @@ def calculate_frequencies(file_contents): cloud.generate_from_frequencies() return cloud.to_array() + + + + #Final solution + +#soln +!pip install wordcloud +!pip install fileupload +!pip install ipywidgets +!jupyter nbextension install --py --user fileupload +!jupyter nbextension enable --py fileupload + +import wordcloud +import numpy as np +from matplotlib import pyplot as plt +from IPython.display import display +import fileupload +import io +import sys + +def _upload(): + + _upload_widget = fileupload.FileUploadWidget() + + def _cb(change): + global file_contents + decoded = io.StringIO(change['owner'].data.decode('utf-8')) + filename = change['owner'].filename + print('Uploaded `{}` ({:.2f} kB)'.format( + filename, len(decoded.read()) / 2 **10)) + file_contents = decoded.getvalue() + + _upload_widget.observe(_cb, names='data') + display(_upload_widget) + +_upload() + +def calculate_frequencies(file_contents): + # Here is a list of punctuations and uninteresting words you can use to process your text + punctuations = '''!()-[]{};:'",円./?@#$%^&*_~''' + uninteresting_words = ["the", "a", "to", "if", "is", "it", "of", "and", "or", "an", "as", "i", "me", "my", \ + "we", "our", "ours", "you", "your", "yours", "he", "she", "him", "his", "her", "hers", "its", "they", "them", \ + "their", "what", "which", "who", "whom", "this", "that", "am", "are", "was", "were", "be", "been", "being", \ + "have", "has", "had", "do", "does", "did", "but", "at", "by", "with", "from", "here", "when", "where", "how", \ + "all", "any", "both", "each", "few", "more", "some", "such", "no", "nor", "too", "very", "can", "will", "just"] + + # LEARNER CODE START HERE + frequencies = {} + file_contents = file_contents.lower() + words = file_contents.split() + + for word in words: + if word not in uninteresting_words: + if word.isalpha(): + if word not in frequencies: + frequencies[word]=1 + else: + frequencies[word] += 1 + + #wordcloud + cloud = wordcloud.WordCloud() + cloud.generate_from_frequencies(frequencies) + return cloud.to_array() + + + # Display your wordcloud image + +myimage = calculate_frequencies(file_contents) +plt.imshow(myimage, interpolation = 'nearest') +plt.axis('off') +plt.show() From ca0e50810db0f463c9228d492129dfbd71449980 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年11月14日 23:37:26 +0300 Subject: [PATCH 60/65] Create tensoflow2.py Tf version 2 --- tensoflow2.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 tensoflow2.py diff --git a/tensoflow2.py b/tensoflow2.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/tensoflow2.py @@ -0,0 +1 @@ + From b25d589c29853588bc568633837da9330d186f46 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2020年11月15日 19:58:41 +0300 Subject: [PATCH 61/65] Update Hello_worldTensorflow.py using with --- Hello_worldTensorflow.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Hello_worldTensorflow.py b/Hello_worldTensorflow.py index f9bf011..0df2be5 100644 --- a/Hello_worldTensorflow.py +++ b/Hello_worldTensorflow.py @@ -3,7 +3,8 @@ import tensorflow as tf #Create op , -#start session +#start session +# you can use the with()_to help start and close the app directly #print the op in the String format hello = tf.constant('Hello World, TensorFlow! Here') From 5b0ba85f7db9c0194da22f5a86cc2a7f99b42524 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: Wed, 9 Dec 2020 23:11:50 +0300 Subject: [PATCH 62/65] Create Solution.py Py solutions --- Solution.py | 1 + 1 file changed, 1 insertion(+) create mode 100644 Solution.py diff --git a/Solution.py b/Solution.py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Solution.py @@ -0,0 +1 @@ + From 114237565c1c86528185b42f2d718e25d177fc0f Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2021年2月11日 17:05:24 +0300 Subject: [PATCH 63/65] Update README.md structure --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 9418b1c..be3ac32 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +##### Code moved to the main read me. + ### Let's Learn some Python Python is one of the most used programming language in large fields. From 13e850d525007efac06ea75f74aecb3daabe6bba Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2021年3月10日 10:07:15 +0300 Subject: [PATCH 64/65] Create Model. Py Models --- Model. Py | 1 + 1 file changed, 1 insertion(+) create mode 100644 Model. Py diff --git a/Model. Py b/Model. Py new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/Model. Py @@ -0,0 +1 @@ + From 092785462e9552033a567913e1ed1d9268583454 Mon Sep 17 00:00:00 2001 From: Timz Owen Date: 2021年3月22日 12:35:35 +0300 Subject: [PATCH 65/65] Create LICENSE.md added license --- LICENSE.md | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 LICENSE.md diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..e81936c --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Timz Owen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE.

AltStyle によって変換されたページ (->オリジナル) /