본문 바로가기
Service/Coding

Quiz: Week 4 - Python

by 포항돼지 2022. 2. 15.

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.

 

palindrome == 회문, 앞이랑 뒤랑 똑같은거

파이썬에서 

string += string2

는 string+string2라는 뜻임

def is_palindrome(input_string):

    new_string = ""
    reverse_string = ""

    for letter in input_string:

        if letter != " ":
            new_string += letter
            reverse_string = new_string[::-1]

    if new_string.lower() == reverse_string.lower():
        return True
    return False
 
 
def is_palindrome(input_string):
    new_string = ""
    reverse_string = ""
   
    for letter in input_string:
        if letter != " ":
            new_string += letter.lower()
            reverse_string = letter.lower() + reverse_string
           
           
    if new_string == reverse_string:
        return True
    return False

print(is_palindrome("abc"))
print(is_palindrome("kayak"))
print(is_palindrome("121"))
 
 
if letter != " "
 new_string += letter.lower() #[a][b][c] 이런식으로 string 생성
 reverse_string = letter.lower() + reverse_string [a]만들어져있으면, [b] + [a] 로 붙음!!

아 도저히 이해가 안된다.. 왜 저게 reverse 가 되는거지?? 리스트 값 써야 되지않나?

아!!! 뒤로 붙는거구나!!! reverse_string이 뒤에있어서!!! 아 이제 이해됬다!!

아!!!!!!!!!!!!!!!!! 주여 감사합니다 이렇게 또 지혜주시네요, 하나님이 역시 저에게 바라시는것은 그것이군요.. 하나님의 생각으로 채울수있도록,,, 더욱 기도하기에 힘써야 겠습니다

 

------------------------------------------------------------------------------------------------------------------------

 

2. 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".

 

KM to Mile로 바꿔주는 계산기 코딩

 

def convert_distance(miles):
    km = miles * 1.6 
    result = "{} miles equals {___} 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

 

def convert_distance(miles):
    km = miles * 1.6 
    result = "{} miles equals {:.1f} km".format(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

 

{}에 :.1f 라고 소수점 1 자리에서 끊는다고 얘기 안해주면 12.2000000000000003 이렇게 나오니까 저렇게 끊어줘야함

\

 

------------------------------------------------------------------------------------------------------------------------

 

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."

First name 다음 last name 첫번재 캐릭터 프린트

 

 

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." 

 

def nametag(first_name, last_name):
    return("{} {[0]}.".format(first_name,last_name))

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." 

 

------------------------------------------------------------------------------------------------------------------------

 

Question 5

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).

문장 끝이 old string으로 끝나면 새걸로 바꿔라

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"
answer

def replace_ending(sentence, old, new):
    # Check if the old string is at the end of the sentence 
    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 = sentence.split()
        k =i[-1].replace(old,new)
        new_sentence=sentence[0:-len(old)]+k
        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"

message = 'Python is fun'
# check if the message ends with fun print(message.endswith('fun'))
# Output: True


endswith() function 써가지고 비교 한다음 replce 및 splicing

------------------------------------------------------------------------------------------------------------------------

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"]

 

answer

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.
newfilenames = []

for filename in filenames:
    if filename.endswith(".hpp"):
        newfilenames.append(filename.replace(".hpp",".h"))
    else:
        newfilenames.append(filename)

print(newfilenames) 
# Should be ["program.c", "stdio.h", "sample.h", "a.out", "math.h", "hpp.out"]

 

------------------------------------------------------------------------------------------------------------------------

Question 2

Let's 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.

첫번째 캐릭터 제일 뒤로 옮기고, 앞에 ay 붙여라

 

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"

 

answer:

def pig_latin(text):
  say = ""
  # 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" + " "
    say += word
    # Turn the list back into a phrase
  return say
    
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"

 

이렇게 word 를 새로 내가 원하는대로 순서대로 조합 시켜가지고 say string안에 += function , 으로 넣어서 print

 

------------------------------------------------------------------------------------------------------------------------

 

Question 3

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.

8진수로 변환해서, 4,2,1 값에 맞게 r,w,x로 넣어라

 

 
 
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-------
 
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)) # 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-------

씨바 모르겠다

 

------------------------------------------------------------------------------------------------------------------------

 

Question 5

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:"

answer

def group_list(group, users):
  members = ' '.join(users)
  return 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:"

 

 

------------------------------------------------------------------------------------------------------------------------

 

 

Question 6

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
"""

 

------------------------------------------------------------------------------------------------------------------------

 

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).

domain = key, user = value
인풋에 domain 이랑 유저값 받아와서 보기 좋게 바꿔바라
 
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"]}))
 
Answer:
 
def email_list(domains):
    emails = []
    for domain, users in domains.items():
      for user in users:
        emails.append(user+'@'+domain)
    return(emails)

print(email_list({"gmail.com": ["clark.kent""diana.prince""peter.parker"], "yahoo.com": ["barbara.gordon""jean.grey"], "hotmail.com": ["bruce.wayne"]}))
 
# domain, users 두개 item으로 domians input value 따로 key 와 value로 가져와서, append해가지고 보여주는식

------------------------------------------------------------------------------------------------------------------------

 

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"] }))

 

def groups_per_user(group_dictionary):
    user_groups = {}
    # Go through group_dictionary
    for group, users in group_dictionary.items():
        # Now go through the users in the group
        for user in users:
            if user not in user_groups:
                user_groups[user] = []
            user_groups[user].append(group)
            # 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"] }))

 

------------------------------------------------------------------------------------------------------------------------

 

Question 5

The add_prices function returns the total price of all of the groceries in the dictionary. Fill in the blanks to complete this function.

dictionary 안의 total grocery price를 return 해보자

 

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

answer:

def add_prices(basket):
    # Initialize the variable that will be used for the calculation
    total = 0
    # Iterate through the dictionary items
    for grocery, cost in basket.items():
        # Add each price to the total calculation
        # Hint: how do you access the values of
        # dictionary items?
        total += cost
    # 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
 

반올림을 진행하는 round 함수는 파이썬의 기본 내장 함수로 모듈 import가 필요하지는 않습니다.

round(숫자, 자릿수 번호) 형태로 사용되며, 자릿수를 지정하지 않으면, 기본적으로 일의 자리까지 반올림을 진행하게 됩니다. 사용 예시를 살펴보겠습니다.

# 일의 자리까지 round(1.28) # 1 # 소수점 첫째자리까지 round(1.28, 1) # 1.3 # 십의 자리까지 round(12.8, -1) # 10.0
 
wardrobe = {'shirt': ['red''blue''white'], 'jeans': ['blue''black']}
new_items = {'jeans': ['white'], 'scarf': ['yellow'], 'socks': ['black''brown']}
wardrobe.update(new_items)

 

이렇게 dictionary update치면, 마지막으로 update된 벨류값 통째로 할당이 됨, 있던 key value 값 통째로 할당되고, 없는 value라면 업데이트 해도 그대로있음

'Service > Coding' 카테고리의 다른 글

Quiz Week 5 - Python  (0) 2022.02.15
Quiz week 4 - Python  (0) 2022.02.15
Quiz 3 week - Python  (0) 2022.02.15
Google Python Automation Certification - Week 6  (0) 2022.02.09
Google Python Automation Certification - Week 5  (0) 2022.02.05