Skip to content

Instantly share code, notes, and snippets.

@roman-on
Created May 17, 2020 23:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save roman-on/3555a8d2cb3e2890af27a5c60a035b73 to your computer and use it in GitHub Desktop.
Save roman-on/3555a8d2cb3e2890af27a5c60a035b73 to your computer and use it in GitHub Desktop.
"""
The function accepts a string as a parameter.
The function returns a dictionary, so each organ in it is a key consisting of a key:
a character from the string passed (not including spaces), and an array:
the number of times the character appears in the string.
magic_str = "abra cadabra"
count_chars(magic_str)
{'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
"""
################# made by three loops ############################################
"""
magic_str = "abra cadabra"
count_chars(magic_str)
{'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
"""
# The function returns a dictionary, so each organ in it is a key consisting of a key
def count_chars(my_str):
new_magic = magic_str.replace(" ","") # Deleting spaces
z = len(new_magic) # Length of the new str list with no spaces
a = "" # New variable for str made
x = 0 # To start the loop
while x < z: # First loop
if not (new_magic[x] in a): # Does the word from loop in the new made list?
a += new_magic[x] # If not in the list it will add the string to the new variable list
c = [] # New variable for list made
y = len(a) # The length of the new made variable "a" list of str
i = 0 # Zero point of second while loop
while i < y: # Second loop under first loop
b = new_magic.count(a[i]) # A loop index run inside the list variable "a" and counting how many times it's exists inside the new_magic list and moving the new list of counted numbers to variable "b"
i += 1
c.append(b) # Adding the variable "b" results into new made list under variable "c"
result = {} # New variable for dict made
y = len(a) # The length of the new made variable "a" list of str
i = 0 # Zero point of third while loop
while i < y: # Third loop under second loop
result [a[i]] = c[i] # A loop index run inside the list variable "a" and "c" and adding them to the new dictionary list that i made
i += 1
x += 1
return result
def main():
<call the function>
if __name__ == "__main__":
main()
################# ############################################
#################### made by one loop #####################
"""
INPUT:
magic_str = "abra cadabra"
INPUT:
count_chars(magic_str)
SUPPOSE OUTPUT:
{'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
"""
def count_chars(my_str):
result = {}
z = len(my_str)
a = ""
i = 0
while i < z:
if my_str[i] != " ":
a = my_str.count(my_str[i])
result [my_str[i]] = a
i += 1
return result
def main():
<call the function>
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment