Python Exercise

Practice your Python skills, no matter you are new to Python or already learnt Python!

Exercise 1: Textual histogram generator: Define function which histogram can print according to the numbers of symbols * (star)

#Given a list of numbers
list = [1,2,3,4]

#Define x as symbol *
x = '*'

#Define a function that prints a histogram based on listing numbers
def textualGen(list):
  for i in list:
    i = i * x
    print(i)
textualGen(list)
Result: 

*
**
***
****

Exercise 2: Define function which histogram can print according to the numbers of symbols * (star), while base on “Ascending” or “Descending” to create the order list.

#Given the list of numbers that need to re-order
a = [4,2,1,3]
b = [4,2,1,3]

#Define x as symbol =
x = '*'

#Define a function that allows ascending or descending 
def textualGen(Ascending, Descending):
  Ascending.sort()
  for i in Ascending:
    i = i * x
    print(i)
  Descending.sort(reverse=True)
  for i in Descending:
    i = i * x
    print(i)

#Produce result as histogram
textualGen(a, b)
Result: 

*
**
***
****
****
***
**
*

Exercise 3: Define a Python function, return a dictionary which counting the frequency of characters in a string, given a string as parameter.

# Given the string "ababcc" stated at the question as parameter
keyword = 'ababcc'

# Define a function for string above as parameter and return dictionary containing the frequency of the characters in the string
def dicEx(keyword):
    result = {}
    for i in keyword:
      result[i] = keyword.count(i)
    print(result)

dicEx(keyword)
Result:

{'a': 2, 'b': 2, 'c': 2}

Exercise 4: Define a Python function, return a dictionary counting the frequency of words in the string, given a string as parameter.

# Given the string " Food in hotel was really really good " as stated at question as parameter
keyword = 'Food in hotel A was really really good'

# Define a function that returns a dictionary containing the frequency of the words in the string
def dicEx(keyword):
    result = {}
    keyword_split = keyword.split()
    for i in keyword_split:
      result[i] = keyword_split.count(i)
    print(result)

dicEx(keyword)
Result: 

{'Food': 1, 'in': 1, 'hotel': 1, 'was': 1, 'really': 2, 'good': 1}

Leave a Comment

Your email address will not be published. Required fields are marked *